简体   繁体   English

使用XMLHttpRequest的Flickr API调用不起作用

[英]Flickr API call with XMLHttpRequest not working

I am trying to get a list in JSON result from Flickr and plain js XMLHttpRequest not working. 我试图从Flickr中获取JSON结果列表,并且普通js XMLHttpRequest无法正常工作。

Here is ajax call example with no callback and not working 这是一个没有回调且无法正常工作的ajax调用示例

 var url = "https://api.flickr.com/services/feeds/photos_public.gne?tags=rat&format=json&nojsoncallback=1"; xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { console.log(xhr.status); console.log(xhr.readyState); if (xhr.readyState == 4 && xhr.status == 200) { var data = JSON.parse(xhr.responseText); console.log(data); }else { console.log("error"); } } xhr.open("GET", url) xhr.send(); 

I'm getting the error - 我遇到了错误-

js:1 Access to XMLHttpRequest at 'https://api.flickr.com/services/feeds/photos_public.gne?tags=rat&format=json&nojsoncallback=1' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

could you tell me where is the problem? 你能告诉我问题出在哪里吗?

The Flickr API doesn't support CORS. Flickr API不支持CORS。 There is no way to access it directly, from JS embedded in a webpage on a different origin, without using the JSONP API. 如果不使用JSONP API,则无法从其他来源的网页中嵌入的JS直接访问它。

Flickr does provide an XML version (remove format=json&callback=? from the URL) and a plain JSON version (use format=json&nojsoncallback=1 ) but without Flickr's granting permission with CORS you can't access it directly. Flickr确实提供了XML版本(从URL删除format=json&callback=? )和纯JSON版本(使用format=json&nojsoncallback=1 ),但是没有Flickr授予CORS的许可,您将无法直接访问它。 You could use a proxy server (either one on the same origin as your webpage, or one which inserts CORS into the response). 您可以使用代理服务器(可以是与网页起源相同的代理服务器,也可以是将CORS插入响应中的代理服务器)。


No 'Access-Control-Allow-Origin' header is present on the requested resource. 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 Origin 'null.jsbin.com'; 来源'null.jsbin.com'; is therefore not allowed access. 因此,不允许访问。 But why I am not getting same error with getJSON 但是为什么我没有得到与getJSON相同的错误

Because jQuery uses the JSONP technique instead XMLHttpRequest when you have callback=? 因为当您有callback=?时,jQuery使用JSONP技术而不是XMLHttpRequest callback=? in the URL. 在网址中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM