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.
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 -
Here is an example from MDN that explains this really well:
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