Search code examples
javascriptreactjsapixmlhttprequestaxios

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

Solution

  • 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 !