javascript 反应中的 CORS 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34119050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:16:25  来源:igfitidea点击:

CORS request in react

javascriptajaxreactjsxmlhttprequest

提问by sanjaypoyzer

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

尝试使用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

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

我基本上完全按照react docs 中所说的去做,但替换了相关行:

  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?

我在这里错过了什么?

回答by Dan Prince

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

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

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-Originheader.

而在浏览器中,localhost:3000除非使用适当的Access-Control-Allow-Origin标头为请求的资源提供服务,否则您无法在源之外(在本例中)发出请求。

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.

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

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

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

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-jslibrary.

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

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

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