在Express中停止执行取消的请求

我正在创build一个应用程序,这个应用程序会向另一个服务器发出大量的HTTP请求,而完成这样的请求可能需要1分钟的时间。 有些用户取消了请求,但我的应用程序仍然执行取消的请求。

这是我的代码:

var app = express(); app.get('/something', function (req, res) { function timeout(i) { setTimeout(function () { // lets assume there is a http request. console.log(i); timeout(++i); }, 100); } req.connection.on('close', function () { console.log('I should do something'); }); timeout(1); }); app.listen(5000); 

基本上,我想要的是停止console.log(i)在客户端closures连接后调用。 另外,如果可能,客户端省略“close- {id}”事件,当后端收到close- {id}事件时,它终止{id}请求。

注意:我使用setTimeout来显示callbackmechanizim。 这不是真正的代码。

感谢您的帮助。

从文档中,“http.request()返回一个http.ClientRequest类的实例。” 你可以调用返回对象的abort()方法。 (警告,未经testing的代码)。

 var http = require('http'); // This needs to go at the top of the file. app.get('/something', function (req, res) { var remote_request = http.request("www.something.com", function(data){ res.writeHeader(200, {"Content-type": "text/plain"}); res.end(data); }); req.on("close", function() { remote_request.abort(); }); }); 

setTimeout分配给var,然后在close处理程序中使用clearTimeout 。 如果可能会根据您的方法结构进行一些巧妙的重组,但是像这样:

 var myTimeout = setTimeout(...) ... req.connection.on('close', function() { clearTimeout(myTimeout); });