Sobes.tech
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:

  1. When a browser makes a request to a resource from another origin (e.g., an AJAX request), it automatically adds an Origin header indicating the request's origin.
  2. The server, upon receiving the request, checks the Origin header and decides whether to allow access.
  3. If access is permitted, the server responds with an Access-Control-Allow-Origin header specifying the allowed origin (or * for all).
  4. 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.