What is CORS?
CORS is a browser security mechanism that controls whether a web page can make requests to a different domain than the one that served it.
CORS (Cross-Origin Resource Sharing) is a browser security feature that controls whether a web page can request resources from a different origin (domain, protocol, or port) than the one it was loaded from. It's why you sometimes see "blocked by CORS policy" errors in the console.
Why It Exists:
Browsers enforce the same-origin policy to stop malicious sites from reading data from other sites using your credentials. CORS is the controlled way for servers to say "these other origins are allowed."
How It Works:
- The browser sends a request with an
Originheader - The server responds with
Access-Control-Allow-Origin - If the origin is allowed, the browser lets the page read the response
- For some requests, the browser first sends a preflight
OPTIONSrequest to check permissions
Key Headers:
- Access-Control-Allow-Origin: Which origins are permitted
- Access-Control-Allow-Methods: Which HTTP methods are allowed
- Access-Control-Allow-Headers: Which custom headers are allowed
- Access-Control-Allow-Credentials: Whether cookies can be sent
FAQ
Is CORS a security feature of my server?
Not exactly. CORS is enforced by the browser. Your server declares a policy, but the browser is what blocks disallowed cross-origin reads. Non-browser clients ignore CORS entirely.
How do I fix a CORS error?
Configure the server that hosts the API to send the correct Access-Control-Allow-Origin (and related) headers for your front-end's origin. You cannot fix it from front-end code alone.