如何使用提取来检索JSONP?

时间:2019-01-02 19:05:34

标签: javascript ajax cors fetch

我无法从此公共端点加载数据:

http://api.flickr.com/services/feeds/photos_public.gne?format=json

我收到以下错误:

Access to fetch at 'http://api.flickr.com/services/feeds/photos_public.gne?format=json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

该怎么做?

1 个答案:

答案 0 :(得分:1)

Jsonp并非如此,因为它旨在解决同一原始策略。如果flickr API支持CORS,则可以将其与fetch一起使用,但是如果要使用jsonp,则需要添加脚本标记和回调。进一步阅读:https://en.wikipedia.org/wiki/JSONP

示例:

<script type="application/javascript">
window.jsonFlickrFeed = function(response) {
  alert(response);
};
</script>
<script type="application/javascript" src="http://api.flickr.com/services/feeds/photos_public.gne?format=json">
</script>