6

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!

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
aieyan
  • 123
  • 4
  • 7
  • You can use they have forked the request package and it is being maintained by postman team, having all the features of request package – Jatin Mehrotra Sep 09 '20 at 09:04

2 Answers2

8

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"
    }
  }
);
Gareth Jones
  • 1,241
  • 4
  • 17
  • 38
2

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

});
Jatin Mehrotra
  • 9,286
  • 4
  • 28
  • 67
  • Thanks for the response, but I was more interested finding out how could I achieve this functionality while still using got – aieyan Sep 09 '20 at 09:16
  • 1
    I gave you this way because you mention request package is deprecated but the same functionality even enhanced is being maintained by postman team in their postman-request npm package – Jatin Mehrotra Sep 09 '20 at 13:37
  • Thanks for this. got is so poorly documented that i'm surprised anyone actually uses it. – m12lrpv Jan 27 '22 at 10:24