Introduction
Cross‑Origin Resource Sharing (CORS) errors are a common hurdle when building fast APIs with Node.js. This post walks you through the root causes and provides a bullet‑proof solution using the cors middleware and custom headers.
1. Understand the CORS Error
When the browser blocks a request, you’ll see messages 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.
The server must explicitly allow the requesting origin.
2. Install the Official Middleware
npm install cors --save
// app.js
const express = require('express');
const cors = require('cors');
const app = express();
// Basic usage – allow all origins (useful for development)
app.use(cors());
// Or fine‑grained configuration
const corsOptions = {
origin: ['http://localhost:3000', 'https://myapp.com'],
methods: ['GET','POST','PUT','DELETE'],
credentials: true,
exposedHeaders: ['Content-Length','X-My-Custom-Header']
};
app.use(cors(corsOptions));
app.get('/api/data', (req, res) => {
res.json({msg:'CORS is now working!'});
});
app.listen(4000, () => console.log('Server listening on port 4000'));
3. Manual Header Injection (When Middleware Is Not an Option)
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // replace * with a specific domain in production
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(204);
}
next();
});
4. Common Pitfalls & Debugging Tips
-
Middleware order –
app.use(cors())must be declared before route handlers. - Proxy servers – If you sit behind Nginx or Apache, propagate the headers:
location /api/ {
proxy_pass http://localhost:4000;
proxy_set_header Access-Control-Allow-Origin "*";
}
-
Credentials – When
credentials:trueis set, you cannot use*for the origin; specify the exact domain. -
Pre‑flight failures – Ensure the
OPTIONSmethod returns a 204 status with the appropriate headers.
5. Automated Fix Script (Optional)
If you need to patch multiple services quickly, grab the ready‑made script:
Download the pre‑configured script here
6. Full Repository for Reference
All the examples and a Docker‑ready setup are available in the public repo.
Get the complete patch tool
7. Wrap‑Up
By adding the cors middleware or manually setting the headers, you eliminate the dreaded CORS block and keep your Node.js Fast API responsive. Remember to lock down the origins before moving to production.
For a deeper dive, explore the official Express CORS documentation and consider automated testing with tools like Postman.
Further Reading
- Express CORS Middleware: https://expressjs.com/en/resources/middleware/cors.html
- MDN Web Docs on CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Access the full repository fix: https://gaba-101010.github.io/GG/
Top comments (0)