CORS (Cross-Origin Resource Sharing)

Today, I want to write a bit about CORS and explain what it is in my understanding.

CORS is a mechanism that tells the browser to give a web application running at one origin, access to some resources from a different origin.

Now, first of all, how do you identify the origin of an application? MDN explained this beautifully here:

There are three parameters that an origin is defined by. They are:

  • The protocol (http or https)
  • The port (80, 8080, etc)
  • and the domain

Applications that have these three parameters to be the same are said to have the same origin. For example,

and

have the same origin. Why? This is because they have the same protocol (http), the same domain (example.com) and are served over the same port (80) PS: A server delivers HTTP content through port 80 by default.

Another example,

and

have different origins. Why? Because they have different protocols, domains and are served over different ports.

Having understood this, let’s read the definition of CORS again:

CORS is a mechanism that tells the browser to give a web application running at one origin, access to some resources from a different origin.

Makes more sense now?

The XMLHTTPRequest and Fetch (my favorite) methods use the same-origin policy. i.e. you can only request resources from the same origin that the application was loaded from except in the case where the other origin has the appropriate set header. For instance, see the below:

async function postData(url = 'https://example.com', data = {}) {
  const response = await fetch(url, {
    method: 'POST', 
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
    },
    ...

This URL,

will be accessible to other origins for resource sharing because CORS has been initiated in the header.