Cross-Origin Resource Sharing (CORS) errors occur in ExpressJS applications when a web page attempts to make requests to a domain different from the one that served it, and the server hasn't been configured to allow such requests.

CORS errors are common in NodeJS projects when working with APIs.
Common CORS Error Messages
Here are some typical CORS error messages you might encounter:
No 'Access-Control-Allow-Origin' Header
Access to fetch at 'http://api.com/data' from origin 'https://www.frontend.com/' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.CORS Method Not Allowed
Access to XMLHttpRequest at 'http://api.com/data' from origin 'https://www.frontend.com/' has been blocked by CORS policy:
The method 'POST' is not allowed.CORS Credential Not Allowed
Access to fetch at 'http://api.com/data' from origin 'https://www.frontend.com/' has been blocked by CORS policy:
Request with credentials cannot be sent to cross-origin.To fix the issue we need to enable CORS in our Application
Enabling CORS in Express
To enable Cross-Origin Resource Sharing (CORS) in your NodeJS Express application, follow these structured steps:
Step 1: Set Up the Project
Create a new directory for your project, navigate into it, and initialize the NodeJS application:
mkdir gfg-corscd gfg-corsnpm init -yStep 2: Install Dependencies
Install the necessary modules, including Express and the CORS middleware:
npm i express corsStep 3: Organize the Project Structure
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.
<!-- index.html -->
<html>
<head>
<script src="script.js" defer></script>
</head>
<body>
<h1>Client Application</h1>
<div id="data"></div>
</body>
</html>
//script.js
document.addEventListener('DOMContentLoaded', () => {
fetch('http://localhost:5000/api/data')
.then(response => response.json())
.then(data => {
document.getElementById('data').textContent = data.message;
})
.catch(error => console.error('Error:', error));
});
//server.js
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
app.use(cors());
app.get('/api/data', (req, res) => {
res.json({ message: 'CORS is enabled for all origins!' });
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
In this example
- HTML (index.html): Sets up the structure of the client-side application, including a heading and a placeholder <div> to display data fetched from the server.
- JavaScript (script.js): Contains a script that waits for the DOM to load, then uses the Fetch API to request data from the server's /api/data endpoint and displays the response in the designated <div>.
- NodeJS (server.js): Sets up an Express server, applies the CORS middleware to allow cross-origin requests, and defines a route (/api/data) that responds with a JSON message when accessed.
Step to Run the Application: Run the server.js using the following command.
node server.jsOutput: Open index.html in a browser. Ensure that the client and server are running on different ports to test CORS functionality.

Configuring CORS for Specific Origins
If you want to allow only certain domains, you can configure the cors middleware accordingly
const corsOptions = {
origin: 'http://example.com/', // Allow only this domain
methods: 'GET,POST', // Allow only specific HTTP methods
allowedHeaders: 'Content-Type,Authorization' // Allow specific headers
};
app.use(cors(corsOptions));
This ensures that only http://example.com/ can access your API.
Handling CORS Errors Manually
If you don't want to use the cors package, you can manually set headers in Express
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
This manually sets CORS headers to allow all origins and specific HTTP methods.
Handling Preflight Requests
Browsers send preflight requests (OPTIONS method) before making certain API requests. To handle them
app.options('*', (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.sendStatus(200);
});
This ensures that preflight requests are properly handled, preventing CORS errors.
Enabling CORS for Specific Routes
Instead of applying CORS globally, you can enable it for specific routes
app.get('/public-data', cors(), (req, res) => {
res.json({ message: "Public data accessible to all origins" });
});
const restrictedCors = cors({ origin: 'http://trusted-domain.com/' });
app.get('/secure-data', restrictedCors, (req, res) => {
res.json({ message: "Data accessible only to trusted-domain.com" });
});
This gives you control over which routes are exposed to different origins.
CORS in Production Environment
When deploying to production, ensure that CORS is properly configured:
- Use environment variables to specify allowed origins dynamically.
- Allow only trusted domains instead of using * (wildcard).
- Limit allowed HTTP methods and headers to minimize security risks.
- Handle credentials properly if your API requires authentication.
const corsOptions = {
origin: process.env.ALLOWED_ORIGIN || 'http://default-domain.com/',
methods: 'GET,POST,PUT,DELETE',
credentials: true
};
app.use(cors(corsOptions));
This ensures that only a trusted domain can access the API.