I'm still new to Node.JS and I'm trying to call a REST API using GET method. I use 'request' package from this link. The call actually works but when I try to return the response body from other .JS file, I get 'undefined'.
Here is my 'first.js'
var request = require('request');
var first = function (){
};
first.prototype.getValue = function (value){
var thpath = somePath + value;
var postheaders = {
'Content-Type': 'x-www-form-urlencoded'
};
var options = {
url : 'https://' + thpath,
method : 'GET',
headers : postheaders,
};
var data_rec = "";
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
data_rec = JSON.parse(body);
console.info(data_rec);
return data_rec;
} else return "failed to get";
});
};
module.exports = first;
Here is my 'second.js'
var first = require('./first');
var instance = new first();
var val1 = instance.getValue(someValue);
console.info(val1);
The 'console.info(data_rec)' from 'first.js' returns a JSON (which means that the call is working). However, 'console.info(val1)' from 'second.js' returns 'undefined'. Can anybody find the solution?
Update: I am able to get the solution by using sync-request package.