【发布时间】: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 效果很好。