尝试从本地主机访问api时如何解决"Access-Control-Allow-Origin"错误 [英] How to solve 'Access-Control-Allow-Origin' error when trying to access api from localhost
问题描述
我已经看到很多有关此错误的主题,但是我对js和api还是很陌生,所以我不太了解,所以我为菜鸟身份道歉.
I've seen a lot of topics on this error, but I'm very new to js and apis, so I couldn't really understand much, so I apologize for noob status.
我正在尝试从sportradar访问api.我正在从create-react-app使用axios创建的一个简单的react项目上对其进行测试.当我console.log数据时,出现以下错误: https://dzwonsemrish7.cloudfront.net/items/372w3g2b3F141t2P0K1G/Image%202018-09-04%20at%2011.33.38%20AM.png
I'm trying to access an api from sportradar. I'm testing it out on a simple react project created from create-react-app and using axios. When I console.log the data I get these errors: https://dzwonsemrish7.cloudfront.net/items/372w3g2b3F141t2P0K1G/Image%202018-09-04%20at%2011.33.38%20AM.png
我猜我无法从本地主机访问它?这是我的请求功能:
I guess I can't access it from a local host? here is my function with the request:
getPlayerInfo() {
const apiKey = "my-api-key";
const playerID = "41c44740-d0f6-44ab-8347-3b5d515e5ecf";
const url = `http://api.sportradar.us/nfl/official/trial/v5/en/players/${playerID}/profile.json?api_key=${apiKey}`;
axios.get(url).then(response => console.log(response));
}
推荐答案
如果后端支持CORS,则可能需要在请求中添加以下标头:
If the backend support CORS, you probably need to add to your request this header:
headers: {"Access-Control-Allow-Origin": "*"}
您的代码如下:
getPlayerInfo() {
const apiKey = "my-api-key";
const playerID = "41c44740-d0f6-44ab-8347-3b5d515e5ecf";
const url = `http://api.sportradar.us/nfl/official/trial/v5/en/players/${playerID}/profile.json?api_key=${apiKey}`;
const config = {
headers: {'Access-Control-Allow-Origin': '*'}
};
axios.get(url,config).then(response => console.log(response));
}
希望这会有所帮助!
这篇关于尝试从本地主机访问api时如何解决"Access-Control-Allow-Origin"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!