Mechanics & Security Model:
- Definition: CORS is a browser-enforced security mechanism that controls whether a web application running at one origin can request resources from a different origin (domain, protocol, or port), relaxing the Same-Origin Policy (SOP).
1. Simple Requests vs Preflight Requests:
- Simple Requests: Standard GET, POST, or HEAD requests using default headers (Accept, Content-Type: application/x-www-form-urlencoded, multipart/form-data, text/plain). The browser executes the request directly and evaluates the response Access-Control-Allow-Origin header.
2. Preflight Requests (OPTIONS):
- Triggered when requests use custom headers (Authorization, X-Custom), non-simple HTTP verbs (PUT, DELETE, PATCH), or JSON payloads (Content-Type: application/json).
- Preflight Flow: The browser automatically sends an HTTP OPTIONS request before the actual request.
- Request Headers: Origin, Access-Control-Request-Method: POST, Access-Control-Request-Headers: authorization, content-type.
- Server Response: Returns 204 or 200 with Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Max-Age (caching preflight). If headers match, the browser proceeds with the real request.