Probably you run into CORS trying to make some request, and don't even understand why it throws you an error in your console. In this post, i want to make it clear what is CORS. Let's begin.
Cross-Origin-Resource-Sharing(CORS) - is just a mechanism that gives access to browser to download resource across domain boundaries. What does it mean? This means that browser restricts cross-origin HTTP request initiated from script for security reason. Fetch API and XMLHttpRequest follow the same-origin policy. It means that unless the response from other origins has the right CORS headers you cannot download resource from origin other than application was loaded.
- Invocations of the XMLHttpRequest or Fetch APIs.
- Web Fonts (for cross-domain font usage in @font-face within CSS), so that servers can deploy TrueType fonts that can only be cross-site loaded and used by web sites that are permitted to do so.
- WebGL textures.
- Images/video frames drawn to a canvas using drawImage().
- CSS Shapes from images.
There are "simple" requests that don't trigger CORS preflight. But this requests must follow all the conditions below:
One of the allowed methods:
Apart from the headers automatically set by the user agent 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:
- Content-Type (but note the additional requirements below)
The only allowed values for the Content-Type header are:
No event listeners are registered on any XMLHttpRequestUpload object used in the request; these are accessed using the XMLHttpRequest.upload property.
No ReadableStream object is used in the request.
Client: Hey server! Give me some data, please.
Server: Hi, firstly let me check if your request is
"simple" or not. If yes i'll give you data and list of
allowed methods and allowed origins in response.
Client: Okay, no problem. Do your work.