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

1

12

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");
Neckerchief answered 4/1, 2013 at 14:38 Comment(0)
B
12

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 
Bisayas answered 5/1, 2013 at 17:41 Comment(2)
Great answer, Ivan. My question is, are you saying, in JavaScript, any REST API it consumes requires a mechanism like the above examples? Or to rephrase, all REST API developers should consider the Cross-Origin issue when developing them?Righthanded
@Righthanded -- yeah, it think does. Remote requests made by JavaScript in the browser are affected by SOP, so it's something to be considered by API developers if they want the API to be available to such clients.Bisayas

© 2022 - 2024 — McMap. All rights reserved.