Node.js HTTP request end / close event does not work

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

The 'end' event or the 'close' event does not fire, even if they are passed in the http.request object as follows:

 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 my events do not work?

+2
source share
1 answer

I doubt that the request instance here (actually it's an OutgoingMessage instance) emits "end" / "close" events. Try listening to the 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 data is transferred, part of the parameters of the http.request method. He takes care of writing data.

+6
source

Source: https://habr.com/ru/post/1239547/


All Articles