I use this request module to make HTTP request in Nodejs
Sample code:
module.exports.getToken = function(){
var token ;
request(validLoginRequest, function(err,resp,body){
var json = JSON.parse(JSON.stringify(body));
console.log("from request(): token=" + json.accesstoken);
token = json.accesstoken;
});
console.log("getToken() returns:" + token);
return token;
}
But the token is always undefined. What did I do wrong?
You've fallen into the classic node asynch trap. The code in the top level function of your module will return before the callback in the inner request function happens. token is not yet defined when you return it.
The simplest solution would be to pass a callback down from the outer function and call it from the callback returned to the request function. If that's not satisfying you could use the $q library to return a promise or find a module that will do synchronous http calls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With