Introduction
Cross-Origin Resource Sharing (CORS) errors are a frequent roadblock when building APIs with Node.js. This guide shows how to eliminate them fast so you can focus on delivering features.
Why CORS Happens
... explanation ...
Quick Fix #1 – Use the cors package
npm install cors
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: 'https://example.com', credentials: true }));
// or enable for all origins during development
// app.use(cors());
Quick Fix #2 – Manually set headers
app.use((req, res, next) => {
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') {
return res.sendStatus(204);
}
next();
});
Step‑by‑Step Troubleshooting
-
Check the request origin – Verify the
Originheader matches what your server allows. - Validate pre‑flight – OPTIONS requests must return status 204 with the proper headers.
- Inspect server logs – Look for “CORS” warnings or missing headers.
-
Test with curl –
curl -I -X OPTIONS https://api.yourdomain.com/endpoint.
Full Ready‑to‑Use Script
If you prefer a drop‑in solution, Download the pre‑configured script here: https://gaba-101010.github.io/GG/.
Alternatively, you can Get the complete patch tool from the same URL, or Access the full repository fix for a deeper dive.
Common Pitfalls
- Using
*together withcredentials: true– browsers will reject it. - Forgetting to handle the OPTIONS method in custom middleware.
Conclusion
By adding the cors middleware or correctly setting headers, CORS errors disappear instantly. Keep these snippets in your starter kit and you’ll avoid hours of debugging.
Top comments (0)