KarateKid
KarateKid

Reputation: 3436

React fetch redirect: CORS error

I have a react app served using express+passport server with twitter authentication.

Now in express server I have the following the code, for the twitter login:

app.get('/login/twitter', passport.authenticate('twitter'));

In the react app i.e. App.js if I use the following code then it works fine and I redirected to Twitter page for authentication and after authentication I am returned back:

 <a href="/login/twitter"> Simple href: Login with Twitter </a>

However, if I use a button that fetches the requested url, instead of simple a href="/login/twitter", then it throws a CORS erros, for example:

class LoginControl extends React.Component {

constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    var url = "/login/twitter";

    fetch(url, {   crossDomain:true, method: 'GET', redirect: 'follow'})
    .then(response => {
      response.json()
    })
    .then(jsondata => console.log(jsondata))
    .catch(function(err) {
        console.info(err + " url: " + url);
    });
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

  render() {
    let button = !!this.state.isLoggedIn ? (<LogoutButton onClick={this.handleLogoutClick} />) : ( <LoginButton onClick={this.handleLoginClick} />);

    return (
      <div>
        {button}
      </div>
    );
  }
}


class App extends Component {
  render() {
    return (
     <div className="App">
     <a href="/login/twitter"> Simple href: Login with Twitter </a>
     <LoginControl />
    );
  }
}
export default App;

So the question is why does a href="/login/twitter" works as expected but the LoginControl component throws the following error:

Failed to load https://api.twitter.com/oauth/authenticate?oauth_token=xxxxxxxxxxxxxxxxx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Also how to fix it and use a Login button that stores the state instead of a href?

Upvotes: 2

Views: 2485

Answers (1)

Rafael Motta
Rafael Motta

Reputation: 2527

You can't use redirects in your server side when you make a AJAX request. With the href is just a default request, in the other hand, with fetch you make an async call.

Upvotes: 1

Related Questions