【发布时间】:2021-11-02 11:26:24
【问题描述】:
我可以使用 Postman 从 Fruityvice 获取此 API。但是当我在本地运行它时,我遇到了 CORS 问题。
我一直在引用 Attempted Solution 和 Attemped Solution 2 来尝试清除错误,但没有成功。
任何指针以及我哪里出错了?谢谢!
初始提取调用
const fetchFruitInformation = async() => {
const response = await fetch("https://www.fruityvice.com/api/fruit/all");
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
};
错误
CORS 策略阻止了从源“http://localhost:3000”获取“https://www.fruityvice.com/api/fruit/all”的访问权限:否“Access-Control-Allow-” Origin' 标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
然后我添加{mode: 'no-cors'} 和{mode: 'cors}
更新的 Fetch 调用
const fetchFruitInformation = async() => {
const response = await fetch("https://www.fruityvice.com/api/fruit/all", {
mode: 'no-cors'
});
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
};
会引发错误
apiCalls.js:7 Uncaught (in promise) 错误 在 fetchFruitInformation (apiCalls.js:7)
【问题讨论】:
-
为什么是
no-cors?它说“如果不透明的响应满足您的需求” - 我认为它不会,因为您试图实际读取服务器返回的响应......
标签: javascript reactjs cors