2

How to bypass CORS (Cross-Origin Resource Sharing) issue using headers or json-p

Intro

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:

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.

  1. Site A using AJAX, request data from Site B through REST API.
  2. Site B responds to the request in form of JSON string.
  3. Browser on which Site A is currently loaded, checks if the response contains the header “Access-Control-Allow-Origin”
  4. 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.

Swaroop Shankar V

2 Comments

  1. You can also check the open source program [Bypass Cors](https://chrishham.github.io/BypassCors/) ,
    an installable Electron App (Windows/Mac/Linux), that lets you Bypass ALL CORS Restrictions permanently,
    by allowing you to set your own custom Headers (+Origin).

    It is specifically designed to work with Web Apps and its perfect for Real Time Scraping.

    Disclaimer: I am the author of the program.

    • Thanks, Christopher, your project looks interesting. Will give it a try

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.