CORS
CORS (Cross-Origin Resource Sharing) is a system, consisting of transmitting HTTP headers, that determines whether browsers block frontend JavaScript code from accessing responses for cross-origin requests.
The same-origin security policy forbids cross-origin access to resources. But CORS gives web servers the ability to say they want to opt into allowing cross-origin access to their resources.
What requests use CORS?
- Invocations of fetch() or XMLHttpRequest, as discussed above.
- Web Fonts (for cross-domain font usage in @font-face within CSS), so that servers can deploy TrueType fonts that can only be loaded cross-origin and used by websites that are permitted to do so.
- WebGL textures.
- Images/video frames drawn to a canvas using drawImage().
- CSS Shapes from images.
Requests with credentials
The most interesting capability exposed by both fetch() or XMLHttpRequest and CORS is the ability to make “credentialed” requests that are aware of HTTP cookies and HTTP Authentication information. By default, in cross-origin fetch() or XMLHttpRequest calls, browsers will not send credentials.
To ask for a fetch() request to include credentials, set the credentials option to “include”. To ask for an XMLHttpRequest request to include credentials, set the XMLHttpRequest.withCredentials property to true.
In this example, content originally loaded from https://foo.example makes a GET request to a resource on https://bar.other which sets Cookies. Content on foo.example might contain JavaScript like this:
const url = “https://bar.other/resources/credentialed-content/“;
const request = new Request(url, { credentials: “include” });
const fetchPromise = fetch(request); fetchPromise.then((response) => console.log(response));
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS#examples_of_access_control_scenarios