Cross-Origin Resource Sharing (CORS) is a security feature that lets a server tell the browser which websites (origins) can access its resources.
When a browser makes a request, it includes an Origin
header. If the request
goes to a server with the same origin, the browser allows it and processes the
response.
If the request goes to a different URL, it’s considered a cross-origin request.
In response, the server will add an Access-Control-Allow-Origin
header. The
value of this header must match the Origin
header from the request.
The server can also allow any URL to make a request by using a wildcard *
.
If there’s a mismatch, the browser will block the response data from being shared with the client. This results in an error, but for security reasons, the browser doesn’t provide much information about what went wrong.
You can fix the mismatch by configuring the server to respond with the correct CORS headers.
This is done by adding an Access-Control-Allow-Origin
header to the server’s
response, specifying which domains can access the resources.
For some cross-origin requests, the browser first sends a preflight request to check if the server allows them.
This is the OPTIONS
request you sometimes see in network tab before seeing the
actual request.
It happens when:
GET
, POST
, or HEAD
The server responds with CORS headers Access-Control-Allow-Methods
and
Access-Control-Allow-Headers
, to say which methods and headers are allowed.
If the response allows the request, the browser proceeds with sending it.
If not, the request is blocked, and a CORS error appears in the console.
Find this post helpful? Subscribe and get notified when I post something new!