尽管这是一个非常常见的问题,但我搜索的解决方案似乎并没有为我解决这个问题。
import React from "react";
import axios from "axios";
class GamesList extends React.Component {
componentDidMount = async () => {
const response = await axios.get("https://api-v3.igdb.com/games", {
headers: {
"user-key": "<API-KEY>",
"Access-Control-Allow-Origin": "http://localhost:3000",
},
});
console.log(response);
};
render() {
return <div>MANY GAMES</div>;
}
}
export default GamesList;
我在运行此代码时收到的错误消息是:
Access to XMLHttpRequest at 'https://api-v3.igdb.com/games' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET https://api-v3.igdb.com/games net::ERR_FAILED
uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
我也尝试过设置"Access-Control-Allow-Origin": "*"
,尽管错误没有改变。
有没有不需要使用/创建代理的简单修复方法?
- UPDATE -遵循@HMR的评论,我已经根据igdb的文档编辑了下面的代码,尽管我仍然收到相同的错误。我在哪里做错了呢?
import React from "react";
import axios from "axios";
class GamesList extends React.Component {
componentDidMount = async () => {
// As mention in the docs, I'm using POST with the necessary body
axios.post("https://api-v3.igdb.com/headers", {
body: {
api_header: {
header: "Access-Control-Allow-Origin",
value: "*",
},
},
});
// now to make the actual request
const response = await axios.get("https://api-v3.igdb.com/games", {
headers: {
"user-key": "<API-KEY>",
"Access-Control-Allow-Origin": "http://localhost:3000",
},
});
console.log(response);
};
render() {
return <div>MANY GAMES</div>;
}
}
export default GamesList;
即使在postman内部将以下内容发布到https://api-v3.igdb.com/headers/
,也会返回Not found
{
"api_header": {
"header": "Access-Control-Allow-Origin",
"value": "*"
}
}
--最终更新--正如@goto1和@HMR在下面提到的,api本身似乎不能正确支持CORS。
我最终还是选择了代理!我正在使用https://github.com/Rob--W/cors-anywhere/ (注意:我必须手动使用npm install proxy-from-env
)
在使用node server.js
启动服务器之后,我可以将服务器的地址添加到我的igdb api请求前面。最终代码:
import React from "react";
import axios from "axios";
class GamesList extends React.Component {
componentDidMount = async () => {
const response = await axios.get("http://0.0.0.0:8080/https://api-v3.igdb.com/games", {
headers: {
"user-key": "<API-KEY>",
},
});
console.log(response); // WORKS!
};
render() {
return <div>MANY GAMES</div>;
}
}
export default GamesList;
发布于 2020-04-17 23:53:28
您是否尝试过在package.json中设置localhost:3000,而不是在axios标头中设置
https://stackoverflow.com/questions/61272703
复制相似问题