CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors
CORS (Cross-Origin Resource Sharing) decides when a web page may read a response from another origin. Learn what an origin is, which requests trigger a preflight, the exact headers your server must send, and how to fix the most common CORS errors, with a local server we ran.
- CORS is enforced by the browser. The server still receives the request and sends the data; the browser decides whether your JavaScript may read it.
- An origin is scheme + host + port.
http://localhost:3000andhttp://localhost:8000are different origins. - Requests with JSON bodies, custom headers like
Authorization, or methods like PUT and DELETE trigger an OPTIONS preflight first. - Fix CORS on the server, never by disabling browser security or adding headers to the request.
Few errors confuse web developers like the red console message saying a request “has been blocked by CORS policy”. The API works in Postman and curl, the server logs show the request arriving, and yet the front end gets nothing. Once you understand that CORS is a browser permission system, not a server error, the fix becomes clear.
To show what happens on the wire, we built a small Python server (Python 3.13.6, standard library only) and sent it the same headers a browser sends. The browser enforcement steps described here follow the Fetch standard and MDN documentation; we did not run a browser test for this article.
What is CORS?
CORS, short for Cross-Origin Resource Sharing, is a set of HTTP headers that lets a server tell browsers which other origins may read its responses. Browsers block cross-origin reads by default to protect users. CORS is the controlled way to relax that rule for front ends you trust, such as your React app on one domain calling your API on another.
What is an origin?
An origin is the combination of scheme, host and port. Change any one and it is a different origin:
| Compared with https://app.example.com | Same origin? | Why |
|---|---|---|
| https://app.example.com/orders | Yes | Only the path differs |
| http://app.example.com | No | Scheme differs |
| https://api.example.com | No | Host differs (subdomain) |
| https://app.example.com:8443 | No | Port differs |
That is why local development hits CORS so often: a front end on port 3000 calling an API on port 8000 is cross-origin, even on the same machine.
The same-origin policy
CORS exists because of the same-origin policy. Without it, any website you visit could use JavaScript to call your bank, your email or your company intranet with your cookies attached and read the replies. The policy says a page may send many kinds of requests to other origins, but it may not read the responses unless the other origin agrees. CORS headers are that agreement.
Simple requests: no preflight
Some requests are considered “simple” and are sent straight away. Broadly, a request is simple when:
- the method is GET, HEAD or POST,
- it only uses safelisted headers such as
AcceptandContent-Language, and - any
Content-Typeistext/plain,multipart/form-dataorapplication/x-www-form-urlencoded.
The browser adds an Origin header, sends the request, and then checks the response for Access-Control-Allow-Origin. If the header is missing or does not match, the response is hidden from your code. These are the request types an HTML form could already send before CORS existed, which is why they skip the extra check.
Preflight requests: the OPTIONS check
Anything else gets a preflight. A fetch with Content-Type: application/json, an Authorization header, or a PUT, PATCH or DELETE method all qualify, so most modern API calls are preflighted. Before the real request, the browser sends:
OPTIONS /api/orders HTTP/1.1
Origin: http://localhost:3000
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type, authorization
The server must answer with a 2xx status and headers that approve the origin, method and headers. Only then does the browser send the real PUT. If the preflight fails, the real request is never sent at all. The HTTP methods guide explains OPTIONS and the other verbs.
The CORS response headers
| Header | Purpose |
|---|---|
Access-Control-Allow-Origin |
The origin allowed to read the response, or * for any origin |
Access-Control-Allow-Methods |
Methods allowed for the real request (preflight) |
Access-Control-Allow-Headers |
Request headers allowed (preflight) |
Access-Control-Allow-Credentials |
true to allow cookies or HTTP auth |
Access-Control-Max-Age |
Seconds the browser may cache the preflight result |
Access-Control-Expose-Headers |
Response headers JavaScript may read beyond the safelisted ones |
Vary: Origin |
Tells caches the response depends on the Origin header |
What our test server returned
We ran two servers on localhost. The first knew nothing about CORS. The second allowed one origin, http://localhost:3000, and answered preflights. Then we sent requests with Python urllib, adding the headers a browser would add. The core of the CORS-aware server:
ALLOWED = {"http://localhost:3000"}
def cors(self):
origin = self.headers.get("Origin")
if origin in ALLOWED:
self.send_header("Access-Control-Allow-Origin", origin)
self.send_header("Vary", "Origin")
self.send_header("Access-Control-Allow-Credentials", "true")
def do_OPTIONS(self):
self.send_response(204)
self.cors()
if self.headers.get("Origin") in ALLOWED:
self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
self.send_header("Access-Control-Max-Age", "600")
self.end_headers()
The results, exactly as printed:
| Request | Status | CORS headers in response |
|---|---|---|
| GET to the plain server, Origin localhost:3000 | 200, body returned | None |
| OPTIONS preflight to the plain server | 501 | None |
| OPTIONS preflight to the CORS server | 204 | Allow-Origin, Vary, Allow-Credentials, Allow-Methods, Allow-Headers, Max-Age 600 |
| GET to the CORS server, allowed origin | 200, body returned | Allow-Origin: http://localhost:3000, Vary, Allow-Credentials |
| GET to the CORS server, Origin https://evil.example | 200, body returned | None |
| GET with no Origin, like curl | 200, body returned | None |
Two lessons stand out. First, the plain server answered the preflight with 501, because Python’s basic handler has no OPTIONS method. Many real frameworks return 404 or 405 for OPTIONS until you enable CORS, and that alone produces a CORS error in the browser. Second, the server returned the data to every caller. For the evil origin, the only difference was the missing header, which tells a browser to hide the response. The server itself blocked nothing.
Cookies, credentials and the wildcard
By default, cross-origin fetch does not send cookies. When the front end uses credentials: "include", the rules tighten:
- The server must send
Access-Control-Allow-Credentials: true. Access-Control-Allow-Originmust be the exact origin, not*.- Cookies also need suitable
SameSiteandSecuresettings to be sent cross-site.
That is why our server echoes the allowed origin from a list instead of sending *. Never echo back any Origin header blindly with credentials enabled: that lets every website read your users’ private data. Token-based APIs that send a bearer token in the Authorization header, such as a JWT, do not need credentials mode, but the header still triggers a preflight.
Fixing the most common CORS errors
| Error message mentions | Likely cause | Fix on the server |
|---|---|---|
| No Access-Control-Allow-Origin header | CORS not enabled, or the request crashed before headers were added | Enable CORS for that route; also add headers on error responses |
| Response to preflight does not have HTTP ok status | OPTIONS returns 404, 405 or 501, or auth middleware blocks it | Handle OPTIONS before authentication and return 204 |
| Header not allowed by Access-Control-Allow-Headers | Front end sends Authorization or a custom header | List that header in Allow-Headers |
| Method not allowed | PUT, PATCH or DELETE missing from Allow-Methods | Add the method |
| Wildcard cannot be used with credentials | * plus credentials |
Return the exact origin and Vary: Origin |
| Origin value does not match | Trailing slash, wrong port or http vs https | Compare full origins exactly; no paths or slashes |
Tip: open the browser Network tab, find the OPTIONS request and read its status and response headers. Most CORS bugs are visible right there.
A server error is a common hidden cause: if your API returns a 500 page without CORS headers, the browser reports a CORS error and hides the real problem. Check the server logs and add CORS headers to error responses too. Our HTTP status codes cheat sheet helps decode what came back.
Development proxies
During local development, front-end dev servers such as Vite or webpack can proxy /api calls to your back end. The browser then talks to one origin only, and CORS never applies. That is a convenient fix for development, but production still needs correct server headers, or the same origin for the app and the API.
CORS is not an API security layer
Our test made this concrete: requests from curl, scripts and servers ignore CORS completely, and even a disallowed origin still reached the server. CORS protects users’ browsers from malicious pages reading responses, nothing more. Your API still needs authentication, authorization, input validation and rate limiting. CORS also does not stop a browser from sending simple cross-site requests, so CSRF protection remains a separate concern. Our REST API best practices cover the rest.
How to test CORS
- Send a preflight with curl:
curl -i -X OPTIONS -H "Origin: http://localhost:3000" -H "Access-Control-Request-Method: PUT" https://api.example.com/orders. - Assert in API tests that allowed origins get the exact header and others get none; see our API testing with Python guide.
- Test error responses and unauthenticated preflights, not just the happy path.
- Check
Vary: Originso a CDN does not serve one origin’s headers to another, as our HTTP caching guide explains.
CORS checklist
- Allow-list exact origins; avoid
*for authenticated APIs. - Answer OPTIONS with 204 before auth middleware runs.
- List every method and request header the front end uses.
- Send
Vary: Originwhen the origin header changes per request. - Set a sensible
Max-Age. Browsers cap it, so very large values do not help. - Never fix CORS by disabling browser security; fix the server.
Final thoughts
CORS feels mysterious until you see it as a conversation between the browser and the server. The browser announces its origin, asks permission with a preflight when needed, and reveals the response only if the server’s headers agree. Configure exact origins, methods and headers on the server, handle OPTIONS early, and remember that CORS protects users, not your API. With that model, every CORS error message points straight to its fix.
Frequently asked questions
What does CORS stand for?
CORS stands for Cross-Origin Resource Sharing. It is a set of HTTP headers that lets a server tell browsers which other origins may read its responses.
Why does my API work in Postman but not in the browser?
Postman and curl do not enforce CORS. Browsers do, so the server must send the right Access-Control headers for the page origin, including a successful answer to the OPTIONS preflight.
What triggers a CORS preflight request?
Methods other than GET, HEAD and POST, custom headers such as Authorization, or a Content-Type like application/json. The browser then sends an OPTIONS request before the real one.
Can I fix CORS from the front end?
No. Adding headers to the request does not help, because the browser checks the response headers from the server. Fix the server, or use a development proxy so both run on one origin.
Is it safe to allow all origins with a wildcard?
Only for truly public data that needs no login. A wildcard cannot be combined with credentials, and APIs that use cookies should allow a list of exact trusted origins.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.