Introduction
Cross‑Origin Resource Sharing (CORS) errors are a common hurdle when building APIs with Node.js. This guide walks you through diagnosing and fixing CORS issues quickly so your frontend can talk to your backend without headaches.
Why CORS Fails
- The browser blocks requests that don't include the correct
Access-Control-Allow-Originheader. - Mis‑configured middleware, missing headers, or wrong HTTP methods can trigger the error.
Step‑by‑Step Fix
1. Install and Use cors Middleware
npm install cors --save
// app.js
const express = require('express');
const cors = require('cors');
const app = express();
// Basic configuration – allow all origins (use with caution in production)
app.use(cors());
app.get('/api/data', (req, res) => {
res.json({ message: 'CORS works!' });
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
2. Fine‑Tune the Options
const corsOptions = {
origin: ['https://example.com', 'https://app.example.com'], // whitelist
methods: ['GET','POST','PUT','DELETE'],
credentials: true, // enable cookies
allowedHeaders: ['Content-Type', 'Authorization']
};
app.use(cors(corsOptions));
3. Handle Pre‑flight Requests
app.options('*', cors(corsOptions)); // enable pre‑flight for all routes
4. Verify with Curl or Browser DevTools
curl -i -X OPTIONS http://localhost:3000/api/data -H "Origin: https://example.com" -H "Access-Control-Request-Method: GET"
You should see Access-Control-Allow-Origin and other CORS headers in the response.
Common Pitfalls
| Symptom | Likely Cause | Fix |
|---|---|---|
No 'Access-Control-Allow-Origin' header |
Middleware not added before routes | Move app.use(cors()) to the top |
CORS preflight response 404 |
Missing app.options handler |
Add app.options('*', cors())
|
| Credentials blocked |
Access-Control-Allow-Origin is *
|
Specify explicit origin and set credentials: true
|
Debugging Checklist
-
Middleware order – ensure
cors()runs before your routes. -
Origin matching – use exact strings or regex; wildcards are not allowed when
credentialsare true. -
Headers list – include any custom headers you send (
X‑My‑Header). -
Server logs – print
req.headers.originto confirm what the browser sends.
Automate the Fix
If you need to apply the same configuration across multiple services, download a ready‑made script:
These resources bundle the CORS setup and can be integrated into CI pipelines.
Conclusion
Fixing CORS in a Node.js application is usually a matter of adding the right middleware, configuring it for your environment, and testing the pre‑flight flow. Follow the checklist above, and you’ll eliminate those frustrating browser errors in minutes.
Happy coding!
Top comments (0)