2

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?

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

5 Comments

So a public API like the Twitter one woudn't had allowed all domains to access it? Do you really think they have to whitelist one by one domains on request?
They can use a wildcard * to allow for more general rules, but yeah, if the asker wanted to be able to make a request from his local dev environment to Twitter's API, then he would need to be whitelisted in a one domain request basis (which they would almost certainly wouldn't do).
Hum I think they uses a wildcard rule, but I might be wrong.
It's easy to find out. Make a request and see what comes back in the headers.
I never said it was difficult ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.