Ahmed Reza
Ahmed Reza

Reputation: 23

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.

Upvotes: 2

Views: 6097

Answers (2)

Swarup Bam
Swarup Bam

Reputation: 199

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

Upvotes: 3

Nazır Dogan
Nazır Dogan

Reputation: 1588

JS working asynchronous. you are trying to get value before its assigned.check this example. you are making request. it takes time but your program will not stop. so you cannot get value outside of function https://repl.it/repls/OutgoingFreshOutput

Upvotes: 2

Related Questions