Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.
XMLHttpRequest to make a request for
For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example,
XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.
The motivation is that the
<form> element from HTML 4.0 (which predates cross-site
fetch) can submit simple requests to any origin, so anyone writing a server must already be protecting against cross-site request forgery (CSRF). Under this assumption, the server doesn't have to opt-in (by responding to a preflight request) to receive any request that looks like a form submission, since the threat of CSRF is no worse than that of form submission. However, the server still must opt-in using
Access-Control-Allow-Origin to share the response with the script.
A simple request is one that meets all the following conditions:
- One of the allowed methods:
- Apart from the headers automatically set by the user agent (for example,
User-Agent, or the other headers defined in the Fetch spec as a forbidden header name, the only headers which are allowed to be manually set are those which the Fetch spec defines as a CORS-safelisted request-header, which are:
Unlike simple requests, for "preflighted" requests the browser first sends an HTTP request using the
OPTIONS method to the resource on the other origin, in order to determine if the actual request is safe to send. Such cross-origin requests are preflighted since they may have implications for user data.