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

空扰寡人 提交于 2019-12-09 04:08:44

问题


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");

回答1:


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 


来源:https://stackoverflow.com/questions/14159154/how-do-rest-apis-work-with-javascript-when-the-same-origin-policy-exists-for-bro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!