Recently in one of my project, I had to make a REST API calls using JQuery. I used JQuery ajax method to call the API but it did not work as expected. On validating the response received from server using firebug, I noticed following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com/api. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
I did a web search and found that the issue was related to CORS or Cross-Origin Request Sharing.
According to Wikipedia definition “Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the resource originated”. So if CORS is meant to be a mechanism to allow request from one domain to other, then how come it is not allowing my site to consume the api of the other site? As per my understanding, below is the answer to this question.
Let us assume that we have two sites, Site A which is the client and Site B which is the server providing REST API.
- Site A using AJAX, request data from Site B through REST API.
- Site B responds to the request in form of JSON string.
- Browser on which Site A is currently loaded, checks if the response contains the header “Access-Control-Allow-Origin”
- If the response from Site B do not contain “Access-Control-Allow-Origin” header then the request is rejected by browser.
Now if we revisit the error captured in firebug, its now clear what “Reason: CORS header ‘Access-Control-Allow-Origin'” means. I believe this is a security measure to restrict unauthorised access to resource of a server, unless CORS header is enabled for the requesting domain.