Often times when calling an API, you may see an error in your console that looks like this:

Access to fetch at 'http://somesite.com' from origin 'http://yoursite.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value that is not equal to the supplied origin

In this post, we are going to learn why this error happens and how you can fix it.

What is the Access-Control-Allow-Origin header?

Access-Control-Allow-Origin is a CORS header. CORS, or Cross Origin Resource Sharing, is a mechanism for browsers to let a site running at origin A to request resources from origin B.

Origin is not just the hostname, but a combination of port, hostname and scheme, such as - http://mysite.example.com:8080/

Here’s an example of where this comes into action -

  1. I have an origin A: http://mysite.com and I want to get resources from origin B: http://yoursite.com.
  2. To protect your security, the browser will not let me access resources from yoursite.com and will block my request.
  3. In order to allow origin A to access your resources, your origin B will need to let the browser know that it is okay for me to get resources from your origin.

Here is an example from MDN that explains this really well:

https://mdn.mozillademos.org/files/14295/CORS_principle.png

With the help of CORS, browsers allow origins to share resources amongst each other.

There are a few headers that allow sharing of resources across origins, but the main one is Access-Control-Allow-Origin. This tells the browser what origins are allowed to receive requests from this server.

#developer #javascript

The Access-Control-Allow-Origin Header Explained – With a CORS Example
2.45 GEEK