javascript - 带有用于 Twitch 身份验证的请求 promise 的 NodeJS 发布请求

标签 javascript node.js oauth-2.0 twitch request-promise

我正在尝试通过 Twitch 登录对我的应用程序上的用户进行身份验证。我似乎无法获得正确的 request.post()(使用请求 promise )。我尝试了许多不同的变体,但通常会在服务器日志中收到“未处理的拒绝”。 Twitch API 指南是 here . POST 响应应该是 JSON。这是我的最新版本:

const twitchATParams =
'?client_id=' + twitchAppClientId +
'&client_secret=' + twitchClientSecret +
'&code=' + code +
'&grant_type=authorization_code' +
'&redirect_uri=' + twitchAppRedirect;

request.post(twitchATRequestUrl + twitchATParams)
.then((accessTokenResponse) => {
    const accessToken = accessTokenResponse.access_token;
    console.log('Got an access token: ' + accessToken);
    res.status(200).send('Got an access token: ' + accessToken);
  })
  .catch((error) => {
    res.status(error.statusCode).send(error.error.error_description);
  });

我也试过这个:

request.post({
url:     twitchATRequestUrl,
form:    { client_id: twitchAppClientId,
           client_secret: twitchClientSecret,
           code: code,
           grant_type: "authorization_code",
           redirect_uri:  twitchAppRedirect}
}, function(error, accessTokenResponse, body){
  const accessToken = accessTokenResponse.access_token;
  console.log('Got an access token: ' + accessToken);
  res.status(200).send('Got an access token: ' + accessToken);
});

这就是 Twitch API 指南所说的我需要做的,我想我在将其翻译成 JavaScript 时遇到了问题:

POST https://id.twitch.tv/oauth2/token
  ?client_id=<your client ID>
  &client_secret=<your client secret>
  &code=<authorization code received above>
  &grant_type=authorization_code
  &redirect_uri=<your registered redirect URI>

更新: 该应用程序使用 Cloud Functions 托管在 Firebase 上。也许这会影响我的请求?

更新 2: 根据这个:Deployed Firebase Function Cannot Execute HTTP GET to external API?我只能在 Firebase 付费计划中发出外部 API 请求。我假设这是我的问题。我将升级到现收现付计划(实际上免费提供大量数据)并再次尝试并在此处发布我的结果。

最佳答案

我不知道你用的是什么库,但最后一个例子与这个版本非常相似:https://www.npmjs.com/package/request .

如果是那个版本,问题是你没有正确映射你的回调参数。 accessTokenResponse var 是响应对象,而不是您想要的 JSON。您必须像这样解析 body 参数。

function(error, response, body){
    console.log(JSON.parse(body));
}

关于javascript - 带有用于 Twitch 身份验证的请求 promise 的 NodeJS 发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52789076/

相关文章:

javascript - 我可以在 mongoDB 中根据填充条件查找文档吗?

node.js - Twitter API 1.1 OAuth 获取使用数据

ios - 带有 iOS 的 Google App Engine 上的 Facebook OAuth

php - 使用 HybridAuth 时了解 base_url 参数

javascript - 解析服务器查询objectId

javascript - SQLite 错误代码号 1 : Syntax Error

javascript - 为什么我无法打印我的对象数据?

javascript - react native : How to properly disable touchable feedback when performing swiping gestures?

javascript - 创建一个基本的银行系统,javascript中的关键字 'this'

javascript - 有关使用客户端凭据 One Drive 访问 MS Graph 的问题吗?