Node.js http请求结束/关闭事件未触发

时间:2013-08-15 08:51:59

标签: node.js http httprequest

我在节点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();

'end'事件和'close'事件都不会被触发,即使在http.request对象中传递也是如此:

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");});
});

为什么我的活动没有解雇?

1 个答案:

答案 0 :(得分:8)

我怀疑这里的请求实例(实际上这是OutgoingMessage的一个实例)会发出事件" end" /"关闭" 。试着听听“完成”#39;事件

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

没有必要这样说。     req.write(POSTDATA); 由于数据传递了部分选项到http.request方法。它负责编写数据。