Open In App

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?



We will use cors, a node.js package to enable CORS in express Node.js Project.

Project Setup and Module Installation:

Project Directory: It will look like this.

 

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




<!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>




.then((res) => res.json())
.then((gfg_articles) => console.log(gfg_articles));




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




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


Article Tags :