Node.js http request end / close event not firing

2019-07-23 12:14发布

问题:

I have the following in node 0.10

var postData = querystring.stringify(data)
    var options = {
        host: 'localhost',
        port: 80,
        path: '/rest/messages/participant?format=json',
        method: 'POST',
        json: true,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': postData.length
        }
    };
    var req = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
           // console.log("body: " + chunk);
        });


    });
    req.on('end', function(){
            console.log('ended');
    });
    req.on("close", function(){
        console.log("closed");

        io.sockets.emit('added', data);
    });
    req.write(postData);
    req.end();

Neither the 'end' event nor the 'close' event are fired , even when passed in the http.request object like so:

var req = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
           // console.log("body: " + chunk);
        });
        res.on("end",function(){ console.log("end");});
        res.on("close",function(){ console.log("close");});
});

Why are my events not firing?

回答1:

I doubt the request instance here (actually this is an instance of OutgoingMessage) emits the events "end" / "close" . Try to listen on 'finish' event.

req.on('finish', function(){
        console.log('ended');
});
req.on("finish", function(){
    console.log("closed");
    io.sockets.emit('added', data);
}); 

And there is no need to have this statement. req.write(postData); As the data is passed part of the options to http.request method. It takes care of writing data.