Same-Origin HTTP Request:
A same-origin HTTP request is a request to a specific resource located at the same domain, using the same protocol, and the same port number as the client making the request.
Example:
http://example.com:80/page.html
http://example.com:80/api/data
example.com
), protocol (http
), and port (80
) match.Cross-Origin HTTP Request:
A cross-origin HTTP request is a request to a resource where any of the domain, protocol, or port differs from the client’s origin.
Example:
http://example.com:80/page.html
https://api.example.com:443/data
http
vs. https
) and port (80
vs. 443
) differ.The CORS protocol is enforced only by browsers to ensure secure cross-origin requests. It involves a set of HTTP headers exchanged between the client (browser) and the cross-origin server to determine whether the response should be accessible to the client.
Browser Detects Request Type:
When a request for a resource is made from a web page, the browser determines whether it is a same-origin or cross-origin request. If it’s a cross-origin request, the browser applies the CORS policy.
Sending the Origin Header:
The browser includes an Origin
header in the request to the cross-origin server, specifying the origin of the client making the request.
Example Request Header:
Origin: <http://example.com>
Server Response with CORS Headers:
The cross-origin server processes the request and responds with a header called Access-Control-Allow-Origin
, indicating which origins are allowed to access the resource.
Example Response Header:
Access-Control-Allow-Origin: <http://example.com>
Browser Validates Response:
The browser compares the value of the Access-Control-Allow-Origin
response header with the Origin
header sent in the request.
If the Access-Control-Allow-Origin
value matches the Origin
header (or is for public resources), the browser allows the web page to access the response.
If the values do not match or the header is missing, the browser blocks access and displays a CORS error in the console, e.g.:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <https://api.example.com/data>. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Request Headers (sent by the browser):