Backend & Data
CORS, explained without the headache
You call your API from your front-end, and the browser console lights up red: "blocked by CORS policy." The instinct is to think your server is misconfigured or rejecting the request. It usually isn't. The request often reached the server fine — the browser refused to hand you the response. Understanding who's enforcing the rule, and why, makes CORS go from baffling to boring.
Why the browser cares
By default, browsers enforce the same-origin policy: JavaScript on a.com can't freely read responses from b.com. This exists to protect users — without it, a malicious site you visit could quietly use your logged-in session to read your email or bank account via JavaScript. CORS (Cross-Origin Resource Sharing) is the controlled exception: a way for b.com to say "it's fine, a.com is allowed to read my responses."
The preflight handshake
For non-trivial requests, the browser sends a preflight — an OPTIONS request that asks "is a.com allowed to make this call?" The server answers with headers, chiefly Access-Control-Allow-Origin, naming who's permitted. If the origin is on the list, the browser sends the real request and lets your code read the response. If not, the response arrives but the browser blocks your JavaScript from reading it — hence the console error.
CORS isn't your server saying no. It's the browser asking the server "is this cross-site call allowed?" and refusing to show your code the answer unless the server says yes. Fix it on the server's headers.
How to actually fix it
- Set the headers on the server you're calling — add
Access-Control-Allow-Originfor your front-end's origin (and the allowed methods/headers). That's the real fix, done where the policy lives. - Don't reach for
*reflexively. Allowing every origin is fine for a truly public API, but wrong for anything that carries credentials — be specific. - It's a browser thing. Server-to-server calls, curl, and mobile apps don't do CORS at all — which is your clue that the browser, not the network, is the enforcer.
Once you internalise that CORS is the browser guarding the user's other tabs — not your API being difficult — the error stops being a wall and becomes a checklist: it's a cross-origin call, the browser wants the server's blessing, so go add the header.