If you are a developer, you might have seen the following error many times especially when dealing with APIs.
For security reasons, browser blocks the cross-origin
HTTP requests. It allows requests that are originated from the same origin.
Browser enforces a security feature called Same Origin Policy by which it allows the same origin requests and blocks different origin requests.
What is CORS and how does it work?
CORS - Cross Origin Resource Sharing
CORS is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin -MDN
What is this Origin all about? It's a combination of Scheme
, Host
and Port
.
Scheme - Protocol. Ex:
http
orhttps
Host - Address of the host. Ex:
domian-a.com
orsub.domain-a.com
Port - Communication endpoint. Ex:
8080
If the combination of all these three are the same, then browser identifies the request as Same Origin.
How CORS Works
CORS allows Servers to explicitly whitelist certain or all origins to bypass the same origin policy.
When a server is configured for CORS, it will return an extra header "Access-Control-Allow-Origin" on all the responses.
For example, when I make a request to the server https://domain-b.com
from my client https://domain-a.com
, the server's response will contain the following header if CORS is enabled for the client.
Access-Control-Allow-Origin: https://domain-a.com
How to enable CORS
First, identify the origins to be whitelisted. Either you can whitelist all the origins or certain origins. Be careful when whitelisting all the origins. Only if you don't want to restrict any origin to access the server resources, whitelist all.
Second, add a CORS middleware to the server.
Here is an example of enabling CORS on a node
application.
Here is another example on ASP .Net WebAPI
.
Install-Package Microsoft.AspNet.WebApi.Cors
Hope it helps!