我一直在想办法解决这个问题。
我在本地机器上运行 React.js http://localhost:3000我正在尝试使用 fetch 方法从 http://api.population.io:80/1.0/countries
根据 API 所有者的说法,“标准响应格式是 JSON (application/json) 和用于跨域请求的 CORS。”
我已经尝试了各种标题组合,我现在拥有的是这个设置:
fetch("http://api.population.io:80/1.0/countries",{
method: 'GET',
mode: 'cors',
headers: new Headers({
"Content-Type": "application/json",
'Access-Control-Allow-Origin':'*'
})
})
根据 Chrome,将通过请求发送以下 header :
Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-origin,content-type
Access-Control-Request-Method: GET
Origin: http://localhost:3000
Referer: http://localhost:3000/reports
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
当然,服务器会返回 403 状态代码和以下消息:
Failed to load http://api.population.io/1.0/countries: 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:3000' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我知道 chrome 插件可以让我解决这个问题,但这并不理想,恐怕我不知道该怎么做,我一整天都在努力解决这个问题,我终于在尝试了几乎所有我能找到的东西后,凌晨 4 点放弃了。
如果有人足够聪明来启发我,我一定会很感激,我什至愿意给你寄一堆啤酒来帮助我解决这个问题。
最佳答案
CORS header 需要在服务器的响应中正确设置。您不能通过在请求中提供更多 header 来使 CORS 工作。在响应不成功的情况下,响应省略 CORS header 的情况并不少见(就像您的情况一样 - 您收到 403 响应)。
因此,您需要弄清楚为什么响应不成功,以及为什么它不包含 CORS header 。无论哪种方式,您都无法在请求中发送更多 CORS header 来解决问题。
关于javascript - API 获取失败,请求的资源上不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51119677/