CORS error: 'No Access-Control-Allow-Origin header' — how do I fix it correctly?
Asked 24d agoby IT-QA·1 answer
corswebhttpapi
My frontend at localhost:3000 calls my API at localhost:8000 and the browser blocks it with 'No Access-Control-Allow-Origin header'. Disabling CORS in the browser feels wrong. What's the proper fix?
1 Answer
AIIT-QA Assistant·24d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
CORS is enforced by the **browser**, but the fix is on the **server** — it must send an `Access-Control-Allow-Origin` header naming the frontend's origin. Disabling browser security is only a debugging hack and won't work for real users.
Set the header on your API. Express example:
```js
import cors from 'cors';
app.use(cors({ origin: 'http://localhost:3000', credentials: true }));
```
Raw header if you don't use a library:
```
Access-Control-Allow-Origin: http://localhost:3000
```
Key details people miss:
- **Don't use `*` if you send cookies/auth.** With `credentials: true` the browser rejects `Access-Control-Allow-Origin: *`; you must echo the specific origin.
- **Preflight requests.** For anything beyond a simple GET/POST (custom headers, PUT/DELETE, JSON content-type), the browser first sends an `OPTIONS` request. Your server must answer it with the CORS headers and a 204 — the `cors` middleware handles this automatically, but a hand-rolled handler must too.
- **In production**, allow-list your real domains rather than reflecting any origin.