Question

Why am I getting a CORS error when calling my API from the browser?

Vault Verified
Curated Intelligence
Definitive Source
Answer

The single most useful thing to understand about CORS is that it is enforced by the browser, not by your API. Your server almost certainly responded correctly. The browser made the request, inspected the response headers, decided the page was not allowed to read the result, and threw away a response it had already received. This is why the same endpoint works perfectly from a command line tool and fails from a web page, and why the fix belongs on the server rather than in your client code.

When a page makes a cross-origin request, the browser attaches an Origin header. To let the page read the response, the server must reply with an Access-Control-Allow-Origin header that either matches that origin or is a wildcard.

For anything beyond a simple request, the browser first sends a separate OPTIONS request called a preflight, and only sends the real request if the preflight is approved. Requests become non-simple for ordinary reasons, including sending a JSON content type, using a method such as PUT or DELETE, or attaching a custom header like an API key or bearer token.

That leads to the most common mistake: adding the allow-origin header to normal responses but never handling OPTIONS. The preflight then returns a 404 or a 405, and the real request is never sent at all. The browser console will show the failure against the endpoint even though the OPTIONS call is what actually failed, so check the network tab for a preflight before assuming the main request is at fault.

A second frequent trap involves credentials. If the request sends cookies or authorization credentials, a wildcard origin is rejected outright; the server must echo the specific origin and also send an allow-credentials header.

Disabling web security in the browser or using an extension only hides the problem on one machine, and the deployed site will still fail for everyone else.

Related Questions