Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js HTTP request not returning full response

I'm making a HTTP request using Node's http module, but on data, the chunk returned doesn't seem to content the full request response. Here's my code:

var req = http.request(httpOptions, function(res) {
    res.setEncoding('utf8');
});

req.on('response', function (response) {
    response.on('data', function (chunk) {
        console.log(chunk);
        callback(null, JSON.parse(chunk));
    });
});

req.on('error', function(e) {
    callback(e);
    //callback(e.message);
});

req.end();

Is there a way to wait for the full output before ending the request? Am I doing something wrong? Thanks!

like image 429
jpmonette Avatar asked Mar 30 '13 03:03

jpmonette


1 Answers

you should also listen for the 'end' event

req.on('response', function (response) {

    var data = "";

    response.on('data', function (chunk) {
        console.log(chunk);
        data += chunk;
    });

    response.on('end', function(){
        callback(data);
    })

});
like image 175
Andbdrew Avatar answered Nov 19 '22 16:11

Andbdrew