Open In App

How to allow CORS in Express ?

Last Updated : 18 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The word CORS stands for “Cross-Origin Resource Sharing”. Cross-Origin Resource Sharing is an HTTP-header based mechanism implemented by the browser which allows a server or an API(Application Programming Interface) to indicate any origins (different in terms of protocol, hostname, or port) other than its origin from which the unknown origin gets permission to access and load resources.

Project Setup and Module Installation:

Step 1: Create a Node.js application and name it gfg-cors using the following command.  

mkdir geeksforgeeks && cd geeksforgeeks
npm init 

Step 2: Install the dependency modules using the following command.

npm i express cors

Step 3: Create a 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: This is the code inside the index.html and script.js file.

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>Sample webpage</title>
    <script src="script.js"></script>
</head>
  
<body>
</body>
  
</html>


Javascript




    .then((res) => res.json())
    .then((data) => console.log(data))


As we are done with the basic file of codes, now move to the main topic and see how to allow CORS in Express

Enabling CORS for all routes: If you want to allow the selected origins to access your site then you need to configure cors as shown below.

Syntax:

const cors = require(cors)
app.use(cors())

Example: Enabling CORS for all routes of server, the new index.js will like:

index.js




// Requiring module
const express = require('express')
const cors = require('cors')
  
// Creating express app
const app = express()
  
// enabling CORS for any unknown origin(https://xyz.example.com)
app.use(cors());
  
// sample api routes for testing
app.get('/', (req, res) => {
    res.json("welcome to our server")
});
  
app.get('/secret', (req, res) => {
    const secret = Math.floor(Math.random() * 100)
    res.json({ secret })
});
  
// Port Number
const port = 5000;
  
// Server setup
app.listen(port, () => {
    console.log(`Server running on port ${port}.`)
})


Step to run the application: Run the server.js using the following command.

node server.js

Output:

CORS for a specified route:

But there might be the case where only a certain number of unknown origins should be allowed to access resources from our server, and we need to protect our server from the potential intruder(any URL not following same-origin policy) due to confidentiality. Here we will enable CORS requests for a certain number of origins as shown below :});

Syntax:

let corsOptions = {
   origin : ['http://localhost:5500'],
}

index.js




// index.js file
  
// Requiring module
const express = require('express')
const cors = require('cors')
  
// Creating express app
const app = express()
  
// enabling CORS for some specific origins only.
let corsOptions = {
   origin : ['http://localhost:5500'],
}
  
app.use(cors(corsOptions))
  
// sample api routes for testing
app.get('/',(req, res) => {
   res.json("welcome to our server")
});
  
app.get('/secret', cors(corsOptions) , (req, res) => {
   const secret =  Math.floor(Math.random()*100)
   res.json({secret})
});
  
// Port Number
const port = 5000;
  
// Server setup
app.listen(port, () => {
   console.log(`Server running on port ${port}.`)
});


Step to run the application: Run the server.js using the following command.

node server.js

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads