Open In App

Use of CORS in Node.js

Last Updated : 18 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The word CORS stands for “Cross-Origin Resource Sharing”. Cross-Origin Resource Sharing is an HTTP-header based mechanism implemented by the browser which allows a server or an API(Application Programming Interface) to indicate any origins (different in terms of protocol, hostname, or port) other than its origin from which the unknown origin gets permission to access and load resources. The cors package available in the npm registry is used to tackle CORS errors in a Node.js application. 

Let’s understand using an example.

Step 1: Installation 

As the CORS package is available in npm(node package manager) that Node.js third-party package, we must have Node.js installed in our local system. To verify type the following command in the terminal.

node -v

The command will show the version of Node.js installed in your system. If it gives some error, make you install Node.js properly, for that follow this link.

Step 2:  Project setup and folder structure. First, create a folder in your system named “geeksforgeeks” and move to the folder using a command prompt. Use the following command to do so.

mkdir geeksforgeeks && cd geeksforgeeks

Inside that folder create two separate folders: client and server(using same mkdir command). Inside the client, the folder creates index.html and script.js files. Inside the server folder type the following command to generate the package.json file :

npm init

Now, create an index.js file inside the server folder to write the server-side logic. Our current folder structure should look like this.

Project Structure: It will look like the following.

Step 3: Now inside the same directory, install necessary packages( express and cors) using the following command :

npm install express cors

Step 4: This is the code inside the index.html file. This is the main HTML code that will be shown to the client in the browser.

HTML




<!DOCTYPE html>
<html lang="en">
   
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Sample webpage</title>
    <script src="script.js"></script>
</head>
   
<body></body>
   
</html>
 
<!-- Frontend will be running on port 5500. -->


We are allowing requests from some particular origins using the corsOptions object.

let corsOptions = {
    origin : ['http://localhost:5500'],
}    
# this corsOptions object enables CORS action for all origins running on port 5500 only.
# So if an application is running on any port other than 5000(own origin) and 5500, 
  no CORS action will be enabled.

Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads