DEV Community


Posted on

What is actually CORS?

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.

Here we have requests that use CORS:

  • 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.

Accessible methods

There are "simple" requests that don't trigger CORS preflight. But this requests must follow all the conditions below:

  1. One of the allowed methods:

    • GET
    • HEAD
    • POST
  2. 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:

    • Accept
    • Accept-Language
    • Content-Language
    • Content-Type (but note the additional requirements below)
    • DPR
    • Downlink
    • Save-Data
    • Viewport-Width
    • Width
  3. The only allowed values for the Content-Type header are:

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain
  4. No event listeners are registered on any XMLHttpRequestUpload object used in the request; these are accessed using the XMLHttpRequest.upload property.

  5. No ReadableStream object is used in the request.

Let's imagine a little dialog between server and client:

  • 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.

For additional information thanks MDN and Wikipedia

Top comments (0)