What is CORS?
sobes.tech AI
Answer from AI
CORS (Cross-Origin Resource Sharing) is a mechanism that allows web pages to request resources from a different domain, port, or protocol than the one from which the page was loaded. This is done using additional HTTP headers.
By default, browsers apply the Same-Origin Policy (SOP), which prohibits scripts running on one page from accessing data from another source (domain, port, protocol). CORS relaxes this policy in a controlled manner, allowing the server to explicitly permit cross-domain requests.
How CORS works:
- Simple request: If the request meets certain criteria (e.g., uses GET or POST method, only allows specific headers), the browser sends the request directly with an
Originheader indicating the request source. The server, upon receiving this header, can respond with anAccess-Control-Allow-Originheader indicating the permitted source. - Preflight request: For "non-simple" requests (e.g., using
PUT,DELETEmethods, or custom headers), the browser first sends a preflightOPTIONSrequest. This asks the server whether the actual request is allowed. The server responds with headers indicating allowed methods, headers, and sources. If the preflight request succeeds, the browser sends the actual request.
Main CORS headers:
Origin: Sent by the browser in the request, indicating the source (domain, port, protocol) of the page initiating the request.Access-Control-Allow-Origin: Sent by the server in response, indicating which source is allowed to receive the response. It can be a specific domain,*(any source), or dynamically generated based on theOriginheader.Access-Control-Allow-Methods: Sent by the server in response to a preflight request, indicating allowed HTTP methods (GET, POST, PUT, DELETE, etc.).Access-Control-Allow-Headers: Sent by the server in response to a preflight request, indicating allowed request headers.Access-Control-Allow-Credentials: Sent by the server in response, indicating whether cookies and other credentials are allowed in the request.
Example of server response headers allowing requests from https://example.com:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
CORS is essential for the proper functioning of many web applications that use cross-origin AJAX requests, such as API interactions, font loading, using web fonts from CDN, etc. Proper CORS configuration on the server is critical for security and functionality.