javascript - Axios 和推特 API

标签 javascript twitter axios

我遇到了 axios 和 twitter API 的问题。

我使用 Postman 发出了成功的请求(设置了授权 header - OAuth 1.0)。现在我正在尝试做同样的事情,但我得到的是:

Failed to load https://api.twitter.com/1.1/lists/statuses.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.

我还在 Network chrome 选项卡中看到,只有 OPTIONS 被发送。

这是我的 axios 配置的样子(更改了凭据;)):

const api = axios.create({
    baseURL: 'https://api.twitter.com/1.1',
    headers: {
      // Authorization was copied from the Postman headers
      Authorization: 'OAuth oauth_consumer_key="consumer_key",oauth_token="token",,oauth_signature_method="H,MAC-SHA1",,oauth_timestamp="1,515677408",,oauth_nonce="nonce",,oauth_version="1,.0",,oauth_signature="signature"',
    },
    withCredentials: true,
  });

  const getListStatuses = (owner_screen_name, slug) => {
    return api.get('/lists/statuses.json', { owner_screen_name, slug });
  };

我错过了什么?

最佳答案

这是一个 CORS问题,浏览器采用的一种安全措施(这解释了为什么你可以通过 Postman 做到这一点)。

基本上,Chrome 会向服务器发送预检请求以了解它的期望,并且服务器不会将您的来源作为可接受的来源返回(Access-Control-Allow-Origin header )。

正如@AndyPiper 在评论中指出的那样,Twitter 的 API 不支持 CORS。这意味着您的请求只有在服务器端而不是浏览器发出时才会起作用。

关于javascript - Axios 和推特 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48208767/

相关文章:

javascript - react GitHub repo API

javascript - d3js 文本转换 I 使用 v3 库的示例

javascript - 无法使用 Angular js 将嵌套数组填充到下拉列表

javascript - 自定义推文给出 "32: Could not authenticate you."错误。知道为什么吗?

html - 如何在 twitter bootstrap 3 中将 'pixel' 媒体查询更改为基于 'em' 的媒体查询

authentication - Next-Auth 凭据不返回 session 并且不通过 prisma 适配器将 session 和帐户存储在数据库中

javascript - 为什么我的 div 有这个神秘的右边距?

javascript - 如何访问(通过javascript) Angular Material 中的当前主题调色板颜色?

Twitter Oauth 2.0 代表其他用户发出请求

javascript - react 状态未正确显示