The `cors` package needs to be used as middleware *before* your routes, and you need to specify the correct origin: ```js const cors = require('cors') // Allow specific origin app.use(cors({ origin: 'http://localhost:3000', credentials: true, // if you're sending cookies })) ``` **Common mistakes:** 1. **Placing `cors()` after route definitions** — middleware runs in order; if routes are defined first, CORS headers never get set. 2. **Using `cors()` with no options** — allows all origins with `*`, which blocks credentials. If you need cookies/auth headers, you must specify the exact origin. 3. **Preflight requests** — `PUT`/`DELETE`/requests with custom headers trigger an `OPTIONS` preflight. If your server doesn't handle OPTIONS, the preflight fails. `cors()` handles this automatically, but custom middleware might not. 4. **Proxy alternative** — in development, configure your React dev server to proxy instead: ```json // package.json (React app) "proxy": "http://localhost:5000" ``` Then fetch from `/api/data` (relative path) — no CORS needed since same origin. In production, the correct fix is usually to serve both frontend and API from the same domain (reverse proxy via nginx/Caddy), eliminating CORS entirely.
c3e759b1-b036-4f23-9671-13961fe4c00f
The cors package needs to be used as middleware before your routes, and you need to specify the correct origin:
const cors = require('cors')
// Allow specific origin
app.use(cors({
origin: 'http://localhost:3000',
credentials: true, // if you're sending cookies
}))Common mistakes:
Placing
cors()after route definitions — middleware runs in order; if routes are defined first, CORS headers never get set.Using
cors()with no options — allows all origins with*, which blocks credentials. If you need cookies/auth headers, you must specify the exact origin.Preflight requests —
PUT/DELETE/requests with custom headers trigger anOPTIONSpreflight. If your server doesn't handle OPTIONS, the preflight fails.cors()handles this automatically, but custom middleware might not.Proxy alternative — in development, configure your React dev server to proxy instead:
// package.json (React app)
"proxy": "http://localhost:5000"Then fetch from /api/data (relative path) — no CORS needed since same origin.
In production, the correct fix is usually to serve both frontend and API from the same domain (reverse proxy via nginx/Caddy), eliminating CORS entirely.