Middle+
What is CORS? How does it work? What is the difference between simple requests (GET, POST) and preflight requests (OPTIONS)? What does CORS look at when sending a request?
sobes.tech AI
Answer from AI
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to resources on a different domain than the one from which the page was loaded.
How CORS works:
When a web page tries to make a request to another domain, the browser checks whether the server of that domain allows such requests. The server must include specific headers in its response (e.g., Access-Control-Allow-Origin) indicating which sources (domains) can access its resources.
Simple requests and preflight requests:
- Simple requests are requests with methods GET, POST, or HEAD, and with a specific set of headers and content types (e.g.,
application/x-www-form-urlencoded). For these requests, the browser sends the main request directly and checks the response. - Preflight requests (OPTIONS) are sent by the browser before the main request if it is not a simple request (e.g., using PUT, DELETE, or custom headers). The goal is to check whether the server permits such a request.
What CORS checks when sending a request:
- The
Originheader indicates the source of the request. - The server's response must include
Access-Control-Allow-Originwith the allowed source or*. - For preflight requests, the server must also include
Access-Control-Allow-Methods(allowed methods) andAccess-Control-Allow-Headers(allowed headers).
If these conditions are not met, the browser blocks access to the response from JavaScript, ensuring security.