How to Fix CORS Errors in Node.js Fast – A Quick Guide for Developers
CORS (Cross‑Origin Resource Sharing) errors are a common roadblock when building APIs with Node.js. This post shows you how to eliminate them fast.
1. Understand the Error
When the browser blocks a request you’ll see something like:
Access to fetch at 'http://api.example.com/data' from origin 'http://localhost:3000' has been blocked by CORS policy
The server must send the correct Access‑Control‑Allow-Origin header.
2. Install the Official Middleware
npm install cors --save
3. Basic Setup
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors()); // <-- enables CORS for all routes
4. Restrict to Specific Origins (Production)
const allowedOrigins = ['http://localhost:3000','https://myapp.com'];
app.use(cors({
origin: function(origin, callback){
if(!origin) return callback(null, true);
if(allowedOrigins.indexOf(origin) === -1){
return callback(new Error('Not allowed by CORS'), false);
}
return callback(null, true);
},
credentials: true
}));
5. Handle Pre‑flight Requests
app.options('*', cors()); // enable pre‑flight for all routes
6. Debugging Tips
- Check the response headers with the browser dev tools.
- Use
curl -I http://localhost:4000/apito see raw headers. - Ensure no other middleware overrides the CORS header later in the chain.
7. Deploy‑Ready Configuration
if (process.env.NODE_ENV === 'production') {
app.use(cors({
origin: ['https://myapp.com'],
methods: ['GET','POST','PUT','DELETE'],
credentials: true,
maxAge: 86400
}));
}
8. One‑Click Fix
If you prefer a ready‑made script, Download the pre‑configured script here. It bundles the above setup and works with Express 4+.
For a full repository with tests and CI, Get the complete patch tool or Access the full repository fix.
9. Wrap‑up
Fixing CORS is usually a matter of adding the right headers early in the request lifecycle. With the steps above you can eliminate those frustrating errors and keep your CI/CD pipeline moving.
Top comments (0)