【问题标题】:Cors issue with ReactReact 的 Cors 问题
【发布时间】:2018-04-04 14:20:33
【问题描述】:

我正在调用我认为已经提供 CORS 访问权限的第 3 方 API。当我通过带有 axios 的简单节点应用程序调用它时,它可以正常工作并提供数据。

const axios= require('axios');

let games = [];
let getTodayGames = () => {axios.get('http://data.nba.net/v2015/json/mobile_teams/nba/2017/scores/00_todays_scores.json')
    .then(function (response) {
        let result = response.data;
        console.log(result);
        games = result.gs.g;
        console.log(games[0].v.tn);
    })
    .catch(function (error) {
        console.log(error);
    });
};

getTodayGames();

但是当我也用 axios 在 React App 中调用它时,它给了我 CORS 错误:

无法加载http://data.nba.net/v2015/json/mobile_teams/nba/2017/scores/00_todays_scores.json:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://127.0.0.1:8080' 因此不允许访问。

class Games extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        games: []
    };
}

componentDidMount() {
    let url='http://data.nba.net/v2015/json/mobile_teams/nba/2017/scores/00_todays_scores.json';
    axios.get(url)
        .then(res => {
            const games = res.data;
            this.setState({ games });
        });
}
....

我在 SO 中阅读了许多回复,但没有解决问题。我无法控制 API。 React 应用程序将作为静态网站托管在 AWS S3 中(无服务器管理),因此我认为代理解决方案的答案不会有帮助。 谢谢。

【问题讨论】:

  • 查看我的答案here
  • https://cors-anywhere.herokuapp.com/ + Your API URL :希望它会工作:)
  • 谢谢达瓦尔。将此服务附加到 API 效果很好。

标签: reactjs api cors axios


【解决方案1】:

您将需要使用附加正确 CORS 标头的服务。 dhaval 在他的评论中提到了一个。另一个是 crossorigin.me

【讨论】:

  • 谢谢archae0pteryx。我使用 Dhaval 提供的服务 cors-anywhere 并且它可以工作。我也会尝试使用 crossorigin.me
【解决方案2】:

如果您要为没有后端的静态网站提供服务,您别无选择,只能使用第三方代理服务器。 CORS 是由客户端的浏览器启动的,您无法解决。 CORS 的全部意义在于防止跨站点脚本攻击或会话劫持。

【讨论】:

    猜你喜欢
    • 2020-08-19
    • 2021-07-25
    • 2021-02-04
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2021-05-30
    相关资源
    最近更新 更多