Node.js http请求结束/closures事件不会触发
我在节点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();
即使在http.request
对象中传递, 'end'
事件和'close'
事件都不会被触发,如下所示:
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");}); });
为什么我的活动没有开火?
我怀疑这里的请求实例(实际上这是OutgoingMessage的一个实例)发出的事件“结束”/“closures”。 尝试听“完成”事件。
req.on('finish', function(){ console.log('ended'); }); req.on("finish", function(){ console.log("closed"); io.sockets.emit('added', data); });
而且没有必要有这个声明。 req.write(POSTDATA); 当数据传递给http.request方法的部分选项。 它负责写入数据。