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

Stop the execution of a cancelled request in Express

我正在创建一个向另一台服务器发出大量 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) 调用。此外,如果可能,客户端会省略 "close-{id}" 事件,并且当后端收到 close-{id} 事件时,它会终止 {id} 请求。

注意:我使用 setTimeout 来显示回调机制。这不是真正的代码。

感谢您的帮助。

根据文档,"http.request() returns an instance of the http.ClientRequest class."您可以调用返回对象的 abort() 方法。 (警告,未经测试的代码)。

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 分配给一个变量,然后在 close 处理程序中使用 clearTimeout。如果可能会根据您的方法结构进行一些巧妙的重组,例如:

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