反应中的CORS请求

时间:2015-12-06 15:23:16

标签: javascript ajax reactjs xmlhttprequest

尝试使用simple-twitter从Twitter API获取内容时出现此错误:

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

我基本上完全按照react docs中的说法行事,但更换了相关的行:

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

回调函数似乎永远不会触发,我认为这是由于请求未完成。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:7)

这里的问题是你正在使用的模块是为Node编写的,而不是浏览器。

虽然在浏览器中,您无法在您的来源之外发出请求(在这种情况下为<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div id="doc"></div>),除非所请求的资源是使用相应的localhost:3000标头提供的。

在这种情况下,浏览器向同一资源发出preflight (OPTIONS)请求,以查看CORS检查是否通过,并且可以安全地响应。在这种情况下,它不能,因为Twitter的API不允许你的来源。

如果API支持JSONP,则可以避免这些限制,但是从Twitter API的V1.1开始,only OAuth is supported

这意味着要从客户端访问Twitter API,您需要在会话内进行身份验证,以便生成可用于发出请求的OAuth令牌。看一下codebird-js库。

或者,您可以使用服务器中的simple-twitter模块并将浏览器的请求转发到Twitter API。