带有承载令牌的Node.js Axios HTTP请求返回未定义

时间:2020-07-20 15:47:45

标签: node.js axios token undefined

我在Stack上看到了很多贴子,这些贴子很接近我所需要的,但是并没有完全回答我的问题(Node非常绿色)。我正在通过Node.js / Axios将Twitch / Tiltify捐赠活动与Raspberry Pi连接起来。我希望Pi定期检查是否有新捐赠,然后激活物理电路(电磁阀等),以便在直播中实时查看。到目前为止,这是我的代码:

const axios = require('axios');

axios.get('URL_GOES_HERE', {
  headers: {
    'Authorization' : 'Bearer MY_TILTIFY_ACCESS_TOKEN'
  }
})
  .then(response => {
    console.log(response.data.url);
    console.log(response.data.explanation);
  })
  .catch(error => {
    console.log(error);
  });

我假设MY_TILTIFY_ACCESS_TOKEN是我在Tiltify帐户中生成的访问令牌。但是,我对要放在URL_GOES_HERE中的值上感到困惑。稀疏的Tiltify API docs给出了两个可能的URL:https://tiltify.com/oauth/authorizehttps://tiltify.com/oauth/token。还是应该将承载凭证直接放入有用的请求的网址中,例如https://tiltify.com/api/v3/user?我已经尝试了所有三个,但是我刚在控制台中得到undefined undefined

赞赏朝着正确方向前进!谢谢您的时间。

2 个答案:

答案 0 :(得分:1)

@benstepp on Github最终回答了我的问题。这是他提供的代码:

const axios = require('axios');

axios.get('https://tiltify.com/api/v3/campaigns/MY_CAMPAIGN_ID/rewards', {
  headers: {
    'Authorization' : 'Bearer MY_API_TOKEN'
  }
})
  .then(response => {                       // this is an axios response object (https://github.com/axios/axios#response-schema)
    //console.log(response.data);           // this is the response body from tiltify (https://tiltify.github.io/api/endpoints/campaigns-id-donations.html)
    //console.log(response.data.data);      // this is the .data property of our responses

    response.data.data.map((reward) => {
      // the name/amount of the recent donations
      console.log(`${reward.name}`)
    })
  })
  .catch(error => {
    console.log(error);
  });

答案 1 :(得分:0)

/authorize端点用于Web服务器OAuth身份验证流和用户代理OAuth身份验证流。

/token端点用于用户名-密码OAuth身份验证流程和OAuth刷新令牌过程。

因此,首先您需要获得授权才能使用Tiltify api。为此,您需要使用任何一种流程

https://tiltify.com/oauth/authorize

https://tiltify.com/oauth/token

假设您使用了token路线,您将得到如下响应:

{ "access_token":"token", "token_type":"bearer", "refresh_token":"refresh_token" }

然后使用您从响应中获得的access_token来调用api路由,因此在URL GOES HERE中将是您的api路由,例如

/campaigns/:id causes/:id

您将在标题中使用Authorization: Bearer <access_token>

相关问题