简体   繁体   中英

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 . 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.

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 . I was unable to find direction to such implementation in the documentation provided by 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" ? Usually in API, the Bearer is in a header called "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

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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