Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do REST APIs work with JavaScript when the same-origin policy exists for browsers?

I am working with Flickr's REST API and it's working fine. By that, I mean I'm making an AJAX call to the Flickr API and getting a JSON object back, parsing the object, etc. etc.

But this raises a question in my mind. If browsers follow the same-origin policy, then how can they make these types of API requests?

This DEMO fiddle is working, but it sends a cross-domain request to the Flickr domain.

How does this cross-domain request work?

The cross-domain request:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=" +
          id + "&lang=en-us&format=json&jsoncallback=1");
like image 895
GajendraSinghParihar Avatar asked Jan 04 '13 14:01

GajendraSinghParihar


1 Answers

What you need to understand is that, while browsers do enforce the same origin policy (SOP), there are exceptions when SOP is not enforced. For example, if you have an HTML page - you can insert <img> tags that point to images on any domain. Therefore, the SOP doesn't apply here and you are making a cross-origin HTTP GET request for an image.

The demo you linked to works since it uses a mechanism that works in a similar way. The mechanism is called JSONP - http://en.wikipedia.org/wiki/JSONP and I suggest you read the wiki entry and some other blog posts. In essence, JSONP dynamically injects <script> tags to send a request to any domain (the parameters of the request are added as URL query params), since the same origin policy does not apply to <script> tags (as it doesn't apply to <img> tags).

Another way to invoke REST APIs on other domains is to use the cross-origin resource sharing mechanism (CORS) - http://en.wikipedia.org/wiki/Cross-origin_resource_sharing. In essence, this mechanism enables that browsers don't deny cross-origin request, but rather ask the target service if it wants to allow a specific cross-origin request. The target service tells the browser that it wants to allow cross-origin requests by inserting special HTTP headers in responses:

Access-Control-Allow-Origin: http://www.example.com 
like image 168
Ivan Zuzak Avatar answered Sep 21 '22 13:09

Ivan Zuzak