无法使用 Fetch API 从 localhost 加载 Deezer API 资源

2022-01-15 00:00:00 cors localhost javascript fetch-api deezer

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

I'm trying to access the Deezer API from localhost, but I'm keep getting the following error:

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 的响应标头确实有 Access-Control-Allow-Origin 标头(访问控制允许来源:*).

localhost's response's headers does have Access-Control-Allow-Origin header (Access-Control-Allow-Origin:*).

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

I'm using fetch like: fetch('http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem').

我做错了什么?

推荐答案

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

You can make the request through a public CORS proxy; to do that try changing your code to:

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 标头添加到响应中,并将其传递回您的请求前端代码.

That sends the request through https://cors-anywhere.herokuapp.com, which forwards the request to http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem and then receives the response. The https://cors-anywhere.herokuapp.com backend adds the Access-Control-Allow-Origin header to the response and passes that back to your requesting frontend code.

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

The browser will then allow your frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.

您还可以使用 https://github.com 轻松设置自己的 CORS 代理/Rob--W/cors-anywhere/

详细了解当您使用 XHR 或 JavaScript 库中的 Fetch API 或 AJAX 方法从前端 JavaScript 代码发送跨域请求时浏览器会做什么,以及有关必须接收哪些响应标头才能让浏览器允许前端代码的详细信息访问响应 - 请参阅 https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.

For details about what browsers do when you send cross-origin requests from frontend JavaScript code using XHR or the Fetch API or AJAX methods from JavaScript libraries—and details about what response headers must be received in order for browsers to allow frontend code to access the responses—see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.

相关文章