CORS (Cross Origin Resource Sharing) - jellyfish-tom/TIL GitHub Wiki
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.
Functional overview
The Cross-Origin Resource Sharing standard works by adding new HTTP headers that let servers describe which origins are permitted to read that information from a web browser. Additionally, for HTTP request methods that can cause side-effects on server data (in particular, HTTP methods other than GET, or POST with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request. Servers can also inform clients whether "credentials" (such as Cookies and HTTP Authentication) should be sent with requests.
CORS failures result in errors but for security reasons, specifics about the error are not available to JavaScript. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser's console for details.
Pre-flighted requests
A pre-flighted request is one that uses a method such as PUT or DELETE. These methods can cause a change in state on the server, so the browser sends a request to the server to check if the request is allowed. The server then responds with the appropriate headers, and if the response is successful, the browser sends the actual request.
CORS mechanism
The CORS mechanism works by adding HTTP headers to cross-origin HTTP requests and responses. These headers indicate whether the request or response is allowed to access the resources.
How does CORS work?
When a browser sends a request to a server, it includes an Origin header. This header contains the origin of the request, which is the domain, protocol, and port of the page making the request.
The server can then decide whether to allow or deny the request. If the request is allowed, the server includes the Access-Control-Allow-Origin header in the response. This header specifies the origin that is allowed to access the resources.
If the request is denied, the server includes the Access-Control-Allow-Origin header with a value of "*", which indicates that no origin is allowed to access the resources.