本文介绍了Node.js http请求结束/关闭事件未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在节点0.10中有以下内容

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();

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

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?

推荐答案

我怀疑这里的请求实例(实际上这是OutgoingMessage的一个实例)会发出事件end/close。尝试听'完成'事件。

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

并且不需要此声明。
req.write(postData);
当数据传递给http.request方法的部分选项时。它负责编写数据。

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.

这篇关于Node.js http请求结束/关闭事件未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:07