Cross-Origin Resource Sharing (CORS)
CORS is a browser-based security mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.
Why Does It Exist?
For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. This is called the Same-Origin Policy (SOP). SOP prevents a malicious website from reading sensitive data from another site (e.g., your bank) using your authenticated session. CORS provides a way to safely relax this policy.
How It Works
- Simple Requests: Certain requests (like GET/POST with standard headers) are sent directly. The server returns an
Access-Control-Allow-Originheader. If it doesn’t match the client’s origin, the browser blocks the response. - Preflight Requests (OPTIONS): For “non-simple” requests (e.g., using
PUT,DELETE, or custom headers likeContent-Type: application/json), the browser first sends anOPTIONSrequest to the server. - The Handshake: The server responds to the preflight with allowed methods, headers, and origins. If the server approves, the browser then sends the actual request.
Key Headers
Origin: Sent by the client to indicate where the request is coming from.Access-Control-Allow-Origin: Sent by the server to indicate which origins are allowed.Access-Control-Allow-Methods: Lists permitted HTTP methods.Access-Control-Allow-Headers: Lists permitted custom headers.Access-Control-Allow-Credentials: Indicates if the response can be shared when the credentials flag is true (e.g., cookies).