How to deal with CORS error in express Node.js Project ? - GeeksforGeeks

25 Jul, 2021
CORS, also known as Cross-Origin Resource Sharing, should be enabled if you want to make a request between your client and server when they are on different URLs.
Let us consider client to be on http://localhost:5500 and the server on http://localhost:5000. Now if you try to make a request from your client to the server you will get the error stating that blocked by the CORS policy.
How To Enable CORS?
We will use cors, a node.js package to enable CORS in express Node.js Project.
Project Setup and Module Installation:
Step 1: Create a Node.js application and name it gfg-cors using the following command.  mkdir gfg-cors && cd gfg-cors
npm init 
Step 1: Create a Node.js application and name it gfg-cors using the following command.  
mkdir gfg-cors && cd gfg-cors
npm init 
Step 2: Install the dependency modules using the following command.npm i express cors
npm i express cors
Step 3: Create client directory and server.js file in the root directory. Then create index.html and script.js in the client directory.
Step 3: Create client directory and server.js file in the root directory. Then create index.html and script.js in the client directory.
Project Directory: It will look like this.
 
Example:Write down the following code in the index.html, script.js, and server.js files.
index.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>gfg-cors</title>    <script src="script.js"></script> </head><body>  </body></html>
script.js
fetch('http://localhost:5000/gfg-articles').then((res) => res.json()).then((gfg_articles) => console.log(gfg_articles));
server.js
// Requiring moduleconst express = require('express');const cors = require('cors');  // Creating express app objectconst app = express();  // CORS is enabled for all originsapp.use(cors());  // Example api app.get('/gfg-articles',     (req, res) => res.json('gfg-articles'));  // Port Numberconst port = 5000;  // Server setupapp.listen(port, () => `Server running on port ${port}`);
Note: If you want to allow the selected origins to access your site then you need to configure cors as shown below.
server.js
// Requiring moduleconst express = require('express');const cors = require('cors');  // Creating express app objectconst app = express();  // CORS is enabled for the selected originslet corsOptions = {    origin: [ 'http://localhost:5500', 'http://localhost:3000' ]};  // Using cors as a middlewareapp.get('/gfg-articles',cors(corsOptions),    (req,res) => res.json('gfg-articles'))  // Port numberconst port = 5000;  // Server setupapp.listen(port, () => `Server running on port ${port}`);
If you just want to allow a particular origin to access your site, then corsOptions will be as follows:
let corsOptions = {
    origin: 'http://localhost:5500'
};
Step to run the application: Run the server.js using the following command.
node server.js
Output: Open index.html and then check the following output in the console.
Express.js
NodeJS-Questions
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
Mongoose Populate() Method
How to connect Node.js with React.js ?
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
Express.js req.params Property
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript