0

So I have Problem with Request and NodeJS, is very simple but I am not an Expert.

Code:

logged: function () {
var request = require('request');
test = "nothing!";

request('http://localhost:8080/log', function (error, response, body){
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
test = body;
});


console.log('test', test);

Output:

Starting .../
test: nothing!
error: null
statusCode: 200
body: hi
Felipe
  • 71
  • 1
  • 4

2 Answers2

1

the answer was here: How do I return the response from an asynchronous call? Request is a asynchronous call!

the Solution is not pretty but it's work!

setTimeout(function() { console.log('test', test);}, 3000);
Felipe
  • 71
  • 1
  • 4
0

request is asynchronous so the console.log in the bottom will be executed before test variable is assigned with the body.

So the console.log needs to be inside the request response function.

If you want to use the body later on outside the response function, depends on how you plan to use it.