使用新的 Fetch API 为 JSON 发出跨域请求

Make cross domain request for JSON with new Fetch API

我在提取时遇到 CORS 问题并且已经用尽了 google。在下面的代码笔中,我试图点击 flickr 的 open api 来获取一些图片。你会看到两个按钮。 "Search with jquery" 工作正常,使用 $.getJSON。

当然,我想使用 Fetch。 "Search with Fetch" 不起作用。当我尝试发送相同的请求时,出现此错误:

Fetch API cannot load http://api.flickr.com/services/feeds/photos_public.gne?tags=dog&tagmode=any. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
console_runner-ba402f0a8d1d2ce5a72889b81a71a979.js:1 TypeError: Failed to fetch(…)

当我添加 mode: 'no-cors' 时,我得到的只是一个不包含任何数据的 opaque 响应。

自己试试吧! http://codepen.io/morgs32/pen/OMGEpm?editors=0110

想要一只手。谢谢。

Flickr API 似乎正在使用 JSONP

如果您 运行 curl 'http://api.flickr.com/services/feeds/photos_public.gne?tags=asd&tagmode=any&format=json' -H 'Host: api.flickr.com' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_; rv:47.0) Gecko/20100101 Firefox/47.0' -H 'Accept: */*' 在控制台中,您不会收到 JSON 响应:

jsonFlickrFeed({
    "title": "Recent Uploads tagged asd",
    "link": "http://www.flickr.com/photos/tags/asd/",
    "description": "",
    "modified": "2016-02-16T18:34:00Z",
    "generator": "http://www.flickr.com/",
    "items": [
   {
     ...
})

JSONP 自动被 getJSON 支持,但 fetch 不支持。