I try to get the response of the http-request to my variable "temperature" but it doesnt work, i already tried it with callbacks but im not really familiar with it so i cant solve my problem right now. Maybe someone has an idea?
thanks and best regards :-)
var temperature = '';
http.get(url, function(res) {
//console.log("Got response: " + res.statusCode);
var bodyarr = [];
res.on('data', function(chunk){
bodyarr.push(chunk);
});
res.on('end', function(){
//console.log(*/bodyarr.join('').toString());
temperature = bodyarr;
});
enter code here
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
console.log(temperature);
The issue is about asynchronicity here; the temperature object is undefined at that point since the log method is called before the request is done. Use the http.request
as it's asynchronous; it takes a callback as parameter which you pass to response.end if you want to have the complete response:
//The url for example is 'www.random.org/temperatures/?min=1&max=100'
var options = {
host: 'www.random.org',
path: '/temperatures/?min=1&max=100'
};
var temperature = '';
var http = require('http');
callback = function(res) {
var bodyarr = [];
res.on('data', function (chunk) {
bodyarr.push(chunk);
});
res.on('end', function () {
console.log(req.data);
console.log(bodyarr);
temperature = bodyarr.join();
});
}
var req = http.request(options, callback).end();