我对react有点陌生,我正尝试从Nomics获取Crypto数据。我阅读了他们的文档,并将axios用于我的GET请求,如下所示:
fetchChartData(currency, start) {
const data = {
key: "key",
currency: currency,
start: start
}
return axios({
method: "get",
url: API_URL + '/exchange-rates/history',
headers: {
"Access-Control-Allow-Origin": "*",
crossorigin: true
},
data
})
}我得到的是:
Access to XMLHttpRequest at 'https://api.nomics.com/v1/currencies/ticker' from origin
'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
on the requested resource.所以我决定使用Moesif Origin and CORS changer
Access to XMLHttpRequest at 'https://api.nomics.com/v1/exchange-rates/history' from origin 'http://localhost:3000'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check:
It does not have HTTP ok status.我不知道为什么它会被阻塞,因为它在文档中说“本地主机请求总是被允许来简化开发”。
我修复这个问题的其他尝试是在头和代理中添加一些东西。我的代理是这样的,(以前从未使用过代理):
const API_URL = `https://cors-anywhere.herokuapp.com/https://api.nomics.com/v1`
fetchChartData(currency, start) {
const key = "key";
return axios({
method: "get",
url: API_URL +
'/exchange-rates/history?' +
`?key=${key}
¤cy=${currency}
&start=${start}`
})
}然而,使用proxy时,我只得到了一个401 (未授权)。1:https://i.stack.imgur.com/zIT7L.png
发布于 2020-07-25 04:52:58
The Problem
问题是您正在使用的域与API期望开发的域不匹配。为了CORS目的(也称为同源策略),基于三个部分来标识域:协议、主机和端口。使用以下域名:,我将在下面解释这三个部分:
了解上面的信息很重要,这样您就可以识别代码片段中的问题。文档指出,localhost始终受支持用于开发。但是,您的域http://localhost:3000与文档不匹配,因为端口不同。
修复的
您需要在http://localhost (默认端口80)本地运行应用程序,才能成功调用并通过CORS预检测试。我没有看到上面提到的,但是如果文档需要一个安全的localhost环境,那么您可能希望在https://localhost (默认端口443)上本地运行应用程序。此外,您可能必须创建一个自签名SSL证书才能正常工作。
https://stackoverflow.com/questions/63081183
复制相似问题