What is CORS, why can an API call fail with a CORS error, and what is a preflight request?
Answer
CORS is a browser-enforced HTTP-header mechanism that relaxes the same-origin policy for approved origins. An origin is the scheme, host and port combination. When browser JavaScript calls a different origin, the browser may first send an OPTIONS preflight containing Origin, Access-Control-Request-Method and possibly Access-Control-Request-Headers. The server must return matching Access-Control-Allow-* policy headers. A call can work in curl or Postman yet fail in the browser because those clients do not enforce the browser same-origin policy. CORS is not authentication and does not replace server-side authorization.
Strong answer includes
- same-origin policy and scheme/host/port origin
- OPTIONS preflight and Access-Control headers
- browser-only enforcement is not API authorization
Practical example
The frontend on app.example.com sends JSON with an Authorization header to api.example.com. The browser preflights with OPTIONS, but the API does not allow Authorization in Access-Control-Allow-Headers, so the browser blocks the real call even though the endpoint works in Postman.