Of course your logs return undefined
: you log before the request is done. The problem isn't scope but asynchronicity.
http.request
is asynchronous, that's why it takes a callback as parameter. Do what you have to do in the callback (the one you pass to response.end
):
callback = function(response) {
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(req.data);
console.log(str);
// your code here if you want to use the results !
});
}
var req = http.request(options, callback).end();