简体   繁体   English

有 npm 模块:如何将不记名令牌添加到 POST 请求

[英]Got npm module: How to add bearer token to POST request

I recently found out that request is no longer maintained, so the best alternative I found is got .我最近发现request不再被维护,所以我找到的最好的替代方法是got I am trying to make an external API call to a REST Server but I am unsure as to how I can add a Bearer token in the authorization header of the POST request.我正在尝试对 REST 服务器进行外部 API 调用,但我不确定如何在 POST 请求的授权标头中添加不记名令牌。

This is my code:这是我的代码:

const response = await got.post(
  "https://${SERVER}/${SOME_ID}/conversations/${CONVERSATION_ID}/messages",
  {
    json: [
      {
        text: req.body.message,
        type: "SystemMessage",
      }
    ],
    responseType: "json",
    headers: {
        token: "Bearer pXw4BpO95OOsZiDQS7mQvOjs"
    }
  }
);

This results in a 401 Unauthorized .这会导致401 Unauthorized I was unable to find direction to such implementation in the documentation provided by GOT.我无法在 GOT 提供的文档中找到此类实现的方向。 And since there are not a lot of queries regarding this package, I was unsuccessful in finding anything on Google as well.而且由于关于这个包的查询并不多,我也没有在谷歌上找到任何东西。 If anyone can help me out in this regard, that would be very helpful!如果有人可以在这方面帮助我,那将非常有帮助!

Are you sure that the header name is "token" ?您确定标题名称是 "token" 吗? Usually in API, the Bearer is in a header called "Authorization"通常在 API 中,Bearer 位于名为“Authorization”的标头中

const response = await got.post(
  "https://${SERVER}/${SOME_ID}/conversations/${CONVERSATION_ID}/messages",
  {
    json: [
      {
        text: req.body.message,
        type: "SystemMessage",
      }
    ],
    responseType: "json",
    headers: {
      "Authorization": "Bearer pXw4BpO95OOsZiDQS7mQvOjs"
    }
  }
);

Here is the code这是代码

npm i postman-request link for npm package npm i postman-request npm包的链接

const request = require('postman-request');

request({
  url: 'your url',
  headers: {
     'Authorization': 'Bearer 71D50F9987529'
  },
  rejectUnauthorized: false
}, function(err, res) {
      if(err) {
        console.error(err);
      } else {
        console.log(res.body);
      }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM