Node.js http request end / close event not firing

烈酒焚心 提交于 2019-12-24 02:23:28

问题


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.



来源:https://stackoverflow.com/questions/18249292/node-js-http-request-end-close-event-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!