How to Deal with CORS Error in Express Node.js Project ?

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

To enable CORS we will be using the cors npm package in our node express application. This cors package provides pre-defined methods for configuration and other setup options to use cors in the application.

Steps to Set-up Project and Install CORS Module

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

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 Structure:

Updated dependencies in the package.json file.

"dependencies": {
"cors": "^2.8.5",
"express": "^4.19.2"
}

Example: Write down the following code in the index.html, script.js, and server.js files.

HTML
<!-- 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>
JavaScript
// Filename - script.js

fetch('http://localhost:5000/gfg-articles')
.then((res) => res.json())
.then((gfg_articles) => console.log(gfg_articles));
Node
// Filename - 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.

Add this cors configuration in the server

// CORS is enabled for the selected origins
let corsOptions = {
    origin: [ 'http://localhost:5500', 'http://localhost:3000' ]
};

Example: Updated server code with cors configuration.

Node
// Filename - 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.