javascript - 使用twitter api获取token

标签 javascript twitter ecmascript-6 twitter-oauth

我正在尝试使用 twitter api,但需要获得身份验证。有 2 种类型,我只需要仅应用程序身份验证,也称为仅应用程序。这是应用程序代表自己发出 API 请求的身份验证类型。

文档解释说要使用此方法,您需要使用不记名 token 。您可以通过 POST oauth2/token 端点传递您的消费者 key 和 secret 来生成不记名 token 。

这是link to docs explaining this endpoint 。甚至有一个示例请求,但我仍然不太清楚需要做什么。

我有 API key 和 API key ,但收到以下错误:

body: ‘{“errors”:[{“code”:170,“message”:“Missing required parameter: grant_type”,“label”:“forbidden_missing_parameter”}]}’ }

我的服务器端代码如下所示

var request = require('request');
var btoa = require('btoa');

const KEY = encodeURIComponent('1234');
const SECRET = encodeURIComponent('5678');

request({
    headers: {
      'Authorization': 'Basic ' + btoa(`${KEY}:${SECRET}`),
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    uri: 'https://api.twitter.com/oauth2/token',
    method: 'POST',
    body:  JSON.stringify({
      'grant_type': 'client_credentials' // I am passing the grant_type here
    })
  }, function (err, res, body) {
    console.log('res', res)
  });

文档中的 CURL 请求如下所示:

POST /oauth2/token HTTP/1.1
Host: api.twitter.com
User-Agent: My Twitter App v1.0.23
Authorization: Basic eHZ6MWV2R ... o4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip

grant_type=client_credentials

最佳答案

为此,有几件事。首先,请求需要在服务器端发出。您需要从 npm 安装 btoa 来提供 key 和 secret key 的编码。 KEY 和 SECRET 需要用冒号分隔。请求正文需要是一个字符串

'grant_type=client_credentials'

请参阅下面的完整代码示例。

const btoa = require('btoa');

request({
    headers: {
      'Authorization': 'Basic ' + btoa(`${KEY}:${SECRET}`),
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    uri: 'https://api.twitter.com/oauth2/token',
    method: 'POST',
    body: 'grant_type=client_credentials'
  }, (error, response, body) => {
    const token = JSON.parse(body).access_token;
  });

关于javascript - 使用twitter api获取token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52924844/

相关文章:

javascript - 为什么这总是评估为假?

javascript - 反向HTML标签,理解赋值

python - Pep8 E501 : line too long error

angularjs - Ionic 框架 Twitter 集成

java - 推特4J - 404 :The URI requested is invalid or the resource requested - code - 34

javascript - ES2015 `import` 替代 `require()()` ?

javascript - 如何在 Javascript 的 foreach 循环中合并多个数组

javascript - 带有管理部分的 Reactjs 网站

javascript - PHP 在 JavaScript 中使用 CryptoJS openssl_encrypt

javascript - es6 类可以具有公共(public)属性和功能吗?