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

Tom*_*ato 7 javascript localhost cors deezer fetch-api

我正在尝试从localhost访问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.
Run Code Online (Sandbox Code Playgroud)

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

我使用的是像获取: fetch('http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem').

我究竟做错了什么?

sid*_*ker 11

您可以通过公共CORS代理发出请求; 要做到这一点尝试将您的代码更改为:

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

它通过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页眉到响应并传递回你的请求前端代码.

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

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

有关使用XHR或JavaScript库中的Fetch API或AJAX方法从前端JavaScript代码发送跨源请求时浏览器执行的操作的详细信息 - 以及有关浏览器允许前端代码访问的必须接收响应标头的详细信息回复 - 请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.