0

I am trying to consume an api which responds with JSON. But I am getting this error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. However I am able to parse the same json locally.

 function getData(lat,long) {

 var url = "http://utilities- oyorooms.herokuapp.com/api/v2/search/hotels?filters[coordinates][longitude]=" + long + "&filters[coordinates][latitude]=" + lat + "&filters[coordinates][distance]=20&fields=name,longitude,latitude,oyo_id&access_token=MXB2cE44LWJGaTViWExHQ0xCOC06VUtucEhhVV9mclNNeWdrNFBveFY=&additional_fields=room_pricing";

$.getJSON(url, function( data ) {

$(data).each(function( key, val ) {


$.each(val.hotels , function(k , v ){  
     alert(v.distance);




});        
});
});

 }
Forkmohit
  • 733
  • 3
  • 12
  • 31

2 Answers2

0

However I am able to parse the same json locally.

Right. The SOP applies to browsers making cross-origin ajax requests (well, and to a couple of other browser things, like iframes, loading images into canvases, and such). If you paste a URL into the address bar, that isn't subject to the SOP. If you use curl or wget from the command line to retrieve it, that isn't subject to the SOP. But if you use ajax (getJSON is ajax) in a browser, it is subject to the SOP.

You cannot work around this purely with a browser (that's the whole point). If the endpoint doesn't support CORS and allow your origin to make requests to it (which they would have to do server-side at their end), you cannot do it from a browser with ajax.

You could do it by setting up your own server, making your request to your server, and having your server call the other server to get the data, because your server wouldn't be subject to the SOP. If you did that a lot, and if the endpoint didn't want you to, expect to find them blocking your server's IP at some stage.

If you control the server-side of the endpoint you're calling and want to enable access to it from the origin of your page, this answer explains how you would do that (with pseudocode).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

The Cross-Origin Request Policy prevents Ajax request which are comming from another website. You have 3 Options to prevent this:

  1. Serve the HTML/JS files from the same Domain+Port as the JSON-Backend
  2. Build a Proxy Server to serve the JSON
  3. Add the following HTTP Header to the Backend:

Access-Control-Allow-Origin: http://foo.example

http://foo.example has to be the URL of the Webserver serving your HTML/JS

Torben H.
  • 160
  • 8