无法使用 Fetch API 从本地主机加载 Deezer API 资源

Cannot load Deezer API resources from localhost with the Fetch API

我正在尝试从本地主机访问 Deezer API,但我不断收到以下错误:

Fetch API cannot load http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' 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.

localhost 的响应 headers 确实有 Access-Control-Allow-Origin header (Access-Control-Allow-Origin:*).

我正在使用 fetch,例如: fetch('http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem').

我做错了什么?

向服务器发出的 CORS 或跨源请求

http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem

在这种情况下,所有现代浏览器都启用预检。

通常会失败,如果服务器没有响应 Access-control headers。

fetch 的情况下,因为你基本上是在摆弄 Javascript

需要服务器响应Access-control-Allow-OriginHeaders,这是灵活的。

你对此无能为力,除非 API 本身变得更加灵活和开放。

但是您可以使用 fetch 并将模式设置为 no-cors

IFFF 你只想缓存你发出的请求的结果,作为响应,而不是自己使用它

阅读Opaque Responses

No-CORS定义

no-cors — Prevents the method from being anything other than HEAD, GET or POST. If any ServiceWorkers intercept these requests, they may not add or override any headers except for these. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains

目前无法提出此请求。您可以从您自己的后端将请求代理到 API 或使用 jsonp。这是一个具有类似 fetch 语法的库 https://github.com/camsong/fetch-jsonp. Usage example https://jsfiddle.net/4dmfo0dd/1/

fetchJsonp('https://api.deezer.com/search/track/autocomplete?limit=1&q=eminem&output=jsonp')
.then(function(response) {
    return response.json();
  })
  .then(json => console.log(json))
  .catch(function(error) { console.log(error); });

您可以通过 public CORS 代理发出请求;为此,请尝试将您的代码更改为:

fetch('https://cors-anywhere.herokuapp.com/http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem')

通过https://cors-anywhere.herokuapp.com发送请求,后者将请求转发给http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem,然后接收响应。 https://cors-anywhere.herokuapp.com 后端将 Access-Control-Allow-Origin header 添加到响应并将其传递回您的请求前端代码。

然后浏览器将允许您的前端代码访问响应,因为带有 Access-Control-Allow-Origin 响应 header 的响应是浏览器所看到的。

您还可以使用 https://github.com/Rob--W/cors-anywhere/

轻松设置自己的 CORS 代理

有关当您使用 XHR 从前端 JavaScript 代码发送 cross-origin 请求或 [=33= 中的 Fetch API 或 AJAX 方法时浏览器执行的操作的详细信息] 库——以及关于必须接收什么响应 header 以便浏览器允许前端代码访问响应的详细信息——参见 https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS