Junior — Middle
Explain the working principle of the CORS mechanism and its purpose in resource sharing between different domains.
sobes.tech AI
Answer from AI
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from accessing resources located on another domain. By default, the browser blocks such requests due to the same-origin policy.
CORS allows the server to explicitly specify which domains can access its resources by adding special HTTP headers, such as Access-Control-Allow-Origin. When a browser makes a request to another domain, it first sends a preflight request (OPTIONS) to check if such a exchange is permitted.
The purpose of CORS is to protect users and servers from unwanted cross-origin requests, preventing attacks like CSRF and controlling access to resources.
Example of a server response header:
Access-Control-Allow-Origin: https://example.com