1. Home
  2. Blog
  3. Software Development

Software Development

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.

9 min read
CORS explained: preflight requests, headers and how to fix CORS errors

Key takeaways

  • 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:3000 and http://localhost:8000 are 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 Accept and Content-Language, and
  • any Content-Type is text/plain, multipart/form-data or application/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-Origin must be the exact origin, not *.
  • Cookies also need suitable SameSite and Secure settings 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: Origin so 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: Origin when 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
Software Development

CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors

CORS explained: origins, simple and preflight requests, the response headers your server must send, credentials, and how to fix common…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Databases & SQL

SQL CAST Explained: Convert Data Types With Tested Examples

SQL CAST explained with tested examples: text to number, truncation, integer division, numbers stored as text, dates, bad input and…

Read article →
Databases & SQL

SQL DISTINCT: How to Remove Duplicate Rows (and Its Traps)

SQL DISTINCT explained with tested queries: one and many columns, NULLs, COUNT DISTINCT, DISTINCT vs GROUP BY, the SUM DISTINCT…

Read article →
Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce explained step by step with 12 practical examples: sums, tallies, grouping, Maps, pipelines, sequential promises and the empty…

Read article →
Software Development

Python Random Module: randint, choice, seed and More

The Python random module explained: randint, randrange, choice, choices, sample, shuffle, seed, weights and when to use secrets instead, with…

Read article →
Software Development

Python Slicing Explained: Start, Stop and Step With Examples

Python slicing explained with start, stop and step, negative indexes, reversing, copying and slice assignment, with tested examples and a…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
Software Development

URL Encoding Explained: Spaces, Plus Signs and UTF-8

URL encoding explained with tested Python and JavaScript code: percent encoding, reserved characters, %20 vs plus, UTF-8 bytes, encodeURI vs…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Software Development

JavaScript Set: Union, Intersection and Removing Duplicates

JavaScript Set explained with tested examples: add, has, delete, deduplicating arrays, the new union and intersection methods, equality rules and…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →