ExpressJS:如何知道请求何时完成?
在NodeJS之上设置的ExpressJS中,我有一些这样的代码:
app.get('/keys/readresults/:keyname', basic_auth, function(req,res){ res.writeHead(200, {'content-type': 'text/json'}); setInterval( go_to_database_and_get('stuff', function (database_replies) { res.write(database_replies) }) ,5000); });
为了简单起见,代码就是这样写的(如果有人想要真正的代码,我很乐意将它发布到一些pastebin中)。
当我curl -u username:password http://localhost:4000/keys/readresults/key
正好是我想要发生的事情时会发生什么:我得到一个200状态头,它检查数据库中的任何结果,我想要写然后等待5秒钟,然后在数据库中search新的结果,并再次写入响应,等等,每隔5秒钟。
问题是,当我退出curl,循环不断进行。 一旦请求 结束,我如何告诉express或nodejs它应该结束该循环 (我猜是 clearInterval) ?
req.on("close")
所以简单
app.get('/keys/readresults/:keyname', basic_auth, function(req,res){ res.writeHead(200, {'content-type': 'text/json'}); var no = setInterval( go_to_database_and_get('stuff', function (database_replies) { res.write(database_replies) }); ,5000); req.on("close", function() { clearInterval(no); }); });
req.on('close', ...)
不再适用于Express 4.使用on-finished
中间件。