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 module 
const express = require('express'); 
const cors = require('cors'); 
  
// Creating express app object 
const app = express(); 
  
// CORS is enabled for all origins 
app.use(cors()); 
  
// Example api  
app.get('/gfg-articles',  
    (req, res) => res.json('gfg-articles')); 
  
// Port Number 
const port = 5000; 
  
// Server setup 
app.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 module 
const express = require('express'); 
const cors = require('cors'); 
  
// Creating express app object 
const app = express(); 
  
// CORS is enabled for the selected origins 
let corsOptions = { 
    origin: [ 'http://localhost:5500', 'http://localhost:3000' ] 
}; 
  
// Using cors as a middleware 
app.get('/gfg-articles',cors(corsOptions), 
    (req,res) => res.json('gfg-articles')) 
  
// Port number 
const port = 5000; 
  
// Server setup 
app.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.
                                
Express.js express.Router() Function
Express.js req.params Property
JWT Authentication with Node.js
Mongoose Populate() Method
How to build a basic CRUD app with Node.js and ReactJS ?
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?