In our project, we make a call to a REST web service with Node using HTTP request. We can see the result when we log it into the console. But we would like to store it or use it outside of the HTTP request. How can we achieve that?
var http = require('http');
var options = {
host: 'http:\\example.com',
port: 80,
path : '/site/status?tag=A7351&date=09JAN&name=LASTNAME',
method : 'GET'
};
var result;
http.request(options, function(res){
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
result = JSON.parse(body);
console.log(result, "INSIDE"); //Shows the JSON result
});
}).end();
console.log(result, "OUTSIDE"); //Shows Undefined
The result is in this format:
{
error: 0,
statut: 'STATUTTTTT',
origine: 'PLACEEE',
destination: 'PARIS',
onwardDate: null
}
We need to be able to get the result outside of the HTTP call.