【问题标题】:How to solve 'Access-Control-Allow-Origin' error when trying to access api from localhost尝试从 localhost 访问 api 时如何解决“Access-Control-Allow-Origin”错误
【发布时间】:2019-02-09 18:36:56
【问题描述】:

看到了很多关于这个错误的话题,但是我对js和api很陌生,所以我不能真正理解太多,所以对于noob状态我表示歉意。

我正在尝试从 Sportradar 访问 api。我在一个从 create-react-app 创建并使用 axios 的简单反应项目上对其进行测试。当我 console.log 数据时,我得到这些错误:https://dzwonsemrish7.cloudfront.net/items/372w3g2b3F141t2P0K1G/Image%202018-09-04%20at%2011.33.38%20AM.png

我想我无法从本地主机访问它?这是我的请求功能:

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

【问题讨论】:

    标签: javascript reactjs api xmlhttprequest axios


    【解决方案1】:

    如果后端支持 CORS,您可能需要在请求中添加此标头:

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

    希望这会有所帮助!

    【讨论】:

    • 谢谢@sdn404!好吧,它摆脱了那个错误,但现在它给了我“加载资源失败:预检...”错误。如果有帮助,这是从站点 api 沙箱提供的信息:'请求标头:X-Originating-IP:76.100.29.60 我也在我的代码中添加了该请求标头。同样的错误
    • 这里是沙盒(下至玩家资料)。即使您没有钥匙,它也应该为您提供重要信息developer.sportradar.com/io-docs
    • 所以我与他们的支持团队取得了联系,该 api 并不意味着可以直接访问。您应该使用 curl/ruby/python 自己下载信息并根据需要存储它。不确定这里的协议是什么。我还是应该将您的答案标记为正确,还是直接删除此帖子?
    猜你喜欢
    • 2016-10-22
    • 2017-07-25
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2019-07-25
    • 2014-04-16
    相关资源
    最近更新 更多