首页 > 解决方案 > 如何使用 fetch 检索 JSONP?

问题描述

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

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.

这个怎么做?

标签: javascriptajaxcorsfetch

解决方案


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>

推荐阅读