-1

We are attempting to extract a JSON Object from a URL through http requesting. However, when we consistently getting the "undefined" when we try to return the text. Is there a problem in the way that we are implementing the http request?

function getUserData(email) {
    var pathURL = "/" + email + "/data"
    var options = {
        host: 'localhost',
        port: 3000,
        path: pathURL,
        method: 'GET',
        headers: {
            accept: 'application/json'
        }
    };

var x = http.request(options, function(res){
    console.log("Connected");
    res.on('data', function(data){
        console.log(data);
    });
});
}

2 Answers2

3

Close the http.request() by using
x.end();
Here a reference to a similar question.
Sending http request in node.js

Try logging error as:

req.on('error', function(err){
  console.log('problem with request:',err.message);
});  

Meanwhile check the documentation of http library as well.

Community
  • 1
  • 1
KeshavDulal
  • 3,060
  • 29
  • 30
  • We are still getting the same error of cannot read of undefined. However, when we added the x.end() line, it prints undefined and "connected" in the console. Not sure where to go from here – Ryan Whitfield Nov 29 '16 at 06:35
  • Try logging the errors. Add it below `res.on();` method. – KeshavDulal Nov 29 '16 at 09:53
0

The response body are data but not returning to x.

var body = []
request.on('data', function(chunk) {
    body.push(chunk)
}).on('end', function() {
    body = Buffer.concat(body).toString()
    // all is done, you can now use body here
})
Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54