javascriptnode.jsunirest

How to get response from unirest nodejs POST call?


I have used the following code sample to call a API which returns a access token.

var responsedata = '';

unirest.post('http://sandbox.com/api/getToken')
  .headers({'Content-Type': 'application/x-www-form-urlencoded'})
  .send('apiKey=xewsdw232')
  .send('username=theuser')
  .end(function (response) {

    console.log(response.body);
    responsedata = response.body;
    
    
  });

console.log(responsedata);

Response

{ data: { token: 'JhbGciOiJIUzI1NiJ9',transID:'00582',errorCode: '00',errorMessage: '' } }

I do get response which gets logged into the console but unable to assign it to a variable to that I can work with it outside the call function. I am struggling with understanding how callbacks work in javascript.


Solution

  • HTTP requests are asynchronous in nature. You do not get the response instantly which means javascript doesn't wait for the response instead execution is continued and whenever a response is returned, the callback gets called.

    If you want to return this response, encapsulate this code in the function and return a resolved promise.

    function getToken() {
      return new Promise((resolve, reject) => {
        unirest.post('http://sandbox.com/api/getToken')
          .headers({
            'Content-Type': 'application/x-www-form-urlencoded'
          })
          .send('apiKey=xewsdw232')
          .send('username=theuser')
          .end(function (response) {
            if (response.error) {
              return reject(response.error)
            }
            return resolve(response.body);
          });
      })
    }
    getToken().then((body) => console.log("success", body)).catch((error) => 
    console.log("error", error))