Junior — Middle
How is the CORS policy checked in browsers?
sobes.tech AI
Answer from AI
The Same-Origin Policy in browsers restricts web pages from accessing resources loaded from a different domain, protocol, or port. CORS (Cross-Origin Resource Sharing) is a mechanism that allows a server to explicitly permit access to its resources from other origins.
CORS verification occurs as follows:
- When a browser makes a request to a resource from another origin (e.g., an AJAX request), it automatically adds an
Originheader indicating the request's origin. - The server, upon receiving the request, checks the
Originheader and decides whether to allow access. - If access is permitted, the server responds with an
Access-Control-Allow-Originheader specifying the allowed origin (or*for all). - If the browser sees this header and it matches the page's origin, the request is considered successful.
For some types of requests (e.g., with custom headers or methods other than GET/POST), the browser first sends a preflight OPTIONS request to check permissions.
Thus, CORS verification is an interaction between the browser and the server through special HTTP headers, ensuring secure access to resources across different origins.