How CORS works
CORS is how a server tells the browser that a page from another origin may read its responses. The idea to keep: the browser blocks that read by default, and the server's headers lift the block.
The short version
An origin is a scheme, a domain and a port. A page's script can read responses from its own origin, and from another origin only if the server sends CORS headers that allow it. The browser adds an Origin header to cross-origin requests, and the server answers with Access-Control-Allow-Origin.
Step by step
- A script on origin A calls
fetch()for a URL on origin B. - A simple request (GET, HEAD or POST with a basic content type) goes out directly with an
Originheader. - Anything else, such as a PUT or a custom header, first gets an
OPTIONSpreflight withAccess-Control-Request-MethodandAccess-Control-Request-Headers. - The server answers with
Access-Control-Allow-Origin,Access-Control-Allow-MethodsandAccess-Control-Allow-Headers. - The browser sends the real request. Its response must carry
Access-Control-Allow-Origin, or the script cannot read it. Access-Control-Max-Agetells the browser how long to cache the preflight answer.
| Simple request | Preflighted request | |
|---|---|---|
| Typical case | GET, HEAD, basic POST | PUT, custom header |
| Sent first | the request itself | OPTIONS |
| Server must allow | the origin | origin, methods, headers |
Why it matters
The browser decides whether your script may read a response, so a CORS error means the server did not send the right headers. The upside is that a server can open itself to chosen origins. The catch is cookies: with credentials the server must name the origin instead of * and send Access-Control-Allow-Credentials: true.
Sources
- MDN, Cross-Origin Resource Sharing (CORS): origins, the Origin header, simple and preflighted requests, preflight headers, Max-Age, credentials
- MDN, Access-Control-Allow-Origin: a single origin or
*, and why credentials need an explicit origin - MDN, Preflight request: the OPTIONS request the browser sends on its own