Tell me what I'm doing wrong, why I get an error. I repeat for the teacher, everything works for him. I get an error. Thread threads are the very beginning.

var http = require('http').createServer().listen(8088); http.on('request', function (req, res) { res.writeHead(200); res.write('Start ...'); setTimeout( function () { res.write('Finish.'); //res.end(); - тут комментирую и получаю ошибку }, 3000); req.on('data', function (msg) { console.log(msg); }); req.on('end', function () { res.end(); }); }); $ node stream.js events.js:160 throw er; // Unhandled 'error' event ^ Error: write after end at ServerResponse.OutgoingMessage.write (_http_outgoing.js:426:15) at Timeout._onTimeout (F:\www\Dropbox\apps\git\js\courses\specialist\уровень -5\модуль-3\stream.js:8:13) at tryOnTimeout (timers.js:224:11) at Timer.listOnTimeout (timers.js:198:5) 
  • It seems that res.end () is called earlier than res.write ('Finish.'). Try in req.on ('end', function () {}) to remove the string res.end (); - Kirill Stoianov
  • removed. but the page in the browser is infinitely updated. all the same need end (). But I did not understand what I missed. - spectre_it
  • @stasOk already answered you, uncomment the res.end () line in setTimeout (function () { - Kirill Stoianov

1 answer 1

It seems like everything is simple. In accordance with your code, the request ends, and when the timeout is triggered after three seconds, it is still trying to write something else. An error pops up.

The end of the request should sound only in timeout. And the code should have the following form:

 var http = require('http').createServer().listen(8088); http.on('request', function (req, res) { res.writeHead(200); res.write('Start ...'); setTimeout( function () { res.write('Finish.'); res.end(); }, 3000); req.on('data', function (msg) { console.log(msg); }); });