Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Difficulty Level : Medium
  • Last Updated : 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 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 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




.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 = {
};
  
// 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.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!