我尝试从本地主机访问 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.
本地主机响应标头确实具有 Access-Control-Allow-Origin 标头
(访问控制允许来源:*)。
我正在使用像这样的获取:fetch('http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem')
.
我究竟做错了什么?
您可以通过公共 CORS 代理发出请求;为此,请尝试将代码更改为:
fetch('https://cors-anywhere.herokuapp.com/http://api.deezer.com/search/track/autocomplete?limit=1&q=eminem')
这会通过以下方式发送请求https://cors-anywhere.herokuapp.com 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
响应头是浏览器看到的。
您还可以使用以下命令设置自己的 CORS 代理https://github.com/Rob--W/cors-anywhere/ https://github.com/Rob--W/cors-anywhere/
有关当您使用 XHR 或 JavaScript 库中的 Fetch API 或 AJAX 方法从前端 JS 代码发送跨域请求时浏览器执行的操作的详细信息,以及有关浏览器必须接收哪些响应标头才能允许前端代码访问反应——见https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)