Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

javascript - How to solve 'Access-Control-Allow-Origin' error when trying to access api from localhost

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.

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));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the backend support CORS, you probably need to add to your request this header:

headers: {"Access-Control-Allow-Origin": "*"}

Your code would be like this:

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));
}

Hope this helps !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...