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

aie*_*yan 6 node.js npm node.js-got

我最近发现request不再维护,所以我找到的最好的替代方案是got。我正在尝试对 REST 服务器进行外部 API 调用,但我不确定如何在 POST 请求的授权标头中添加不记名令牌。

这是我的代码:

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"
    }
  }
);
Run Code Online (Sandbox Code Playgroud)

这会产生一个401 Unauthorized. 我无法在 GOT 提供的文档中找到此类实现的方向。由于关于这个包的查询并不多,所以我在谷歌上也没有成功找到任何东西。如果有人可以在这方面帮助我,那将非常有帮助!

小智 8

您确定标头名称是“token”吗?通常在 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"
    }
  }
);
Run Code Online (Sandbox Code Playgroud)


Jat*_*tra 2

这是代码

npm i postman-requestnpm包的链接

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);
      }

});
Run Code Online (Sandbox Code Playgroud)