suryanaga
suryanaga

Reputation: 4022

CORS request in react

Getting this error when trying to get stuff from the Twitter API using simple-twitter:

XMLHttpRequest cannot load https://api.twitter.com/1.1/statuses/user_timeline.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400

I'm basically doing exactly what it says in the react docs, but with the relevant line replaced:

  componentDidMount: function() {
    twitter.get('statuses/user_timeline', function(error, data) {
      if(this.isMounted()){
        this.setState({tweets: data})
        console.dir('callback')
      }
    }.bind(this));
  }

The callback function seems to never fire, which I assume is due to the request not completing.

What am I missing here?

Upvotes: 2

Views: 12639

Answers (1)

Dan Prince
Dan Prince

Reputation: 30009

The issue here is the module you're using is written for Node, not the browser.

Whilst in the browser, you can't make requests outside of your origin (in this case localhost:3000) unless the requested resource is served with the appropriate Access-Control-Allow-Origin header.

In this case the browser makes a preflight (OPTIONS) request to the same resource to see whether the CORS checks pass and it can safely respond. In this case it can't because Twitter's API doesn't allow your origin.

You can avoid these limitations if the API supports JSONP, but as of V1.1 of the Twitter API, only OAuth is supported.

This means that to access the Twitter API from the client, you'll need to authenticate inside your session, in order to generate an OAuth token that you can use to make requests. Take a look at the codebird-js library.

Alternatively, you can use the simple-twitter module from a server and forward requests from your browser on to the Twitter API.

Upvotes: 8

Related Questions