Fix CORS Errors in Node.js Fast: A Complete Guide
Cross‑Origin Resource Sharing (CORS) errors are one of the most common roadblocks when building APIs with Node.js and Express. In this article we’ll walk through the root causes, show how to diagnose the problem, and give you a step‑by‑step recipe to eliminate the error in seconds.
What Is CORS?
CORS is a browser security mechanism that restricts web pages from making requests to a different origin (domain, protocol, or port) than the one that served the page. When the server does not explicitly allow the origin, the browser blocks the response and logs a message like:
Access to fetch at 'https://api.example.com/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Common Scenarios That Trigger CORS Errors
| Scenario | Typical Cause |
|---|---|
Front‑end on localhost:3000 calling API on api.example.com
|
Missing Access-Control-Allow-Origin header |
| API behind a reverse proxy (NGINX) | Proxy strips CORS headers |
Pre‑flight OPTIONS request returns 404 |
No route handling for OPTIONS
|
Credentials (withCredentials:true) used without Access-Control-Allow-Credentials
|
Header mismatch |
Step‑by‑Step Fix Using Express
1. Install the Official cors Middleware
npm install cors --save
2. Apply It Early in Your Middleware Chain
const express = require('express');
const cors = require('cors');
const app = express();
// Allow all origins (development) – replace with a whitelist for production
app.use(cors({
origin: '*',
methods: ['GET','POST','PUT','DELETE','OPTIONS'],
allowedHeaders: ['Content-Type','Authorization']
}));
// If you need credentials:
// app.use(cors({ origin: 'https://myfrontend.com', credentials: true }));
app.use(express.json());
app.get('/api/hello', (req, res) => {
res.json({msg: 'CORS is now working!'});
});
app.listen(4000, () => console.log('Server listening on port 4000'));
Tip: Place
app.use(cors())before any route definitions; otherwise the headers won’t be attached.
3. Manually Set Headers (When You Can’t Use Middleware)
If you prefer a lightweight approach or are using a custom server (e.g., http module), set the headers yourself:
const http = require('http');
const server = http.createServer((req, res) => {
// Always add CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
// Pre‑flight request – respond with 204 No Content
res.writeHead(204);
return res.end();
}
// Your normal request handling below
if (req.url === '/api/data') {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({data: 'Hello world'}));
} else {
res.writeHead(404);
res.end();
}
});
server.listen(5000, () => console.log('Raw HTTP server on 5000'));
Debugging Checklist
- Open the browser dev tools → Network tab – locate the failing request and inspect the Response Headers.
-
Check the pre‑flight
OPTIONSresponse – it must return status 200‑204 and include the CORS headers. -
Verify the server is not overriding headers – frameworks like
helmetcan strip them if mis‑configured. - If you’re behind a proxy – ensure NGINX/Apache forwards the CORS headers. Example NGINX snippet:
location /api/ {
proxy_pass http://localhost:4000;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods "GET,POST,OPTIONS";
add_header Access-Control-Allow-Headers "Content-Type,Authorization";
}
- Use an online validator – paste the response headers into https://www.test-cors.org/ to see what the browser perceives.
Automate the Fix with a Ready‑Made Script
We’ve packaged the above configuration into a single drop‑in script that you can clone, adjust, and run instantly. It includes environment‑aware whitelisting and optional credential support.
These links point to a public repo containing a setup-cors.js utility that injects the correct middleware into any existing Express project.
Conclusion
CORS errors are rarely about React or Angular—they’re almost always a missing header on the server side. By adding the cors middleware, handling OPTIONS requests, and confirming proxy configurations, you can resolve most CORS issues in under a minute.
Stay ahead of the curve: automate the fix, keep your whitelist tight in production, and monitor the Network tab for any regressions. Happy coding!
Top comments (0)