Cors issue with React

2019-07-29 04:37发布

问题:

I am calling a 3rd party API on which CORS access is I think already provided. When i am calling it via a simple node app with axios it works fine and provide the data.

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

But when i call it in a React App with axios also, it gives me CORS error:

Failed to load http://data.nba.net/v2015/json/mobile_teams/nba/2017/scores/00_todays_scores.json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access.

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

I read many responses in SO, but nothing solve the issue. I have no control on the API. The React app will be hosted in AWS S3 as a static web site (no server management), so I don't think the answers with proxy solutions will help. Thank you.

回答1:

You will need to use a service that appends the proper CORS header. dhaval mentioned one in his comment there. Another is crossorigin.me



回答2:

If you are going to serve a static website with no backend, you have no choice but to use a third party proxy server. CORS is initiated by the client's browser, you have no way around that. The whole point of CORS is to prevent cross site scripting attacks or session hijacking.