当客户端/浏览器取消挂起的 HTTP 请求时,Node with Express 似乎会继续处理该请求。对于密集的请求,CPU 仍然忙于处理不必要的请求。
有没有办法让 Node.js/Express 终止/停止这些请求取消的待处理请求?
鉴于AngularJS 1.5 HTTP请求很容易cancellable,它变得特别有用。通过在 $http
/$resource
对象上调用 $cancelRequest()
。
当公开为自动完成或搜索字段提供结果的 API 方法时,可能会发生这种取消:在要自动完成或预先输入的字段中键入时,可以取消先前的请求。
全局 server.timeout
不能解决问题:1) 它是所有公开 API 方法的先验全局设置 2) 取消请求中正在进行的处理不会被终止。
最佳答案
注入(inject)的req
对象与监听器.on()
一起提供。
监听 close
事件允许在客户端关闭连接时进行处理(请求被 Angular 取消,或者,例如,用户关闭了查询选项卡)。
这里有2个简单的例子,如何使用close
事件来停止请求处理。
示例一:可取消同步块(synchronized block)
var clientCancelledRequest = 'clientCancelledRequest';
function cancellableAPIMethodA(req, res, next) {
var cancelRequest = false;
req.on('close', function (err){
cancelRequest = true;
});
var superLargeArray = [/* ... */];
try {
// Long processing loop
superLargeArray.forEach(function (item) {
if (cancelRequest) {
throw {type: clientCancelledRequest};
}
/* Work on item */
});
// Job done before client cancelled the request, send result to client
res.send(/* results */);
} catch (e) {
// Re-throw (or call next(e)) on non-cancellation exception
if (e.type !== clientCancelledRequest) {
throw e;
}
}
// Job done before client cancelled the request, send result to client
res.send(/* results */);
}
示例 2:带有 promise 的可取消异步 block (类似于 reduce)
function cancellableAPIMethodA(req, res, next) {
var cancelRequest = false;
req.on('close', function (err){
cancelRequest = true;
});
var superLargeArray = [/* ... */];
var promise = Q.when();
superLargeArray.forEach(function (item) {
promise = promise.then(function() {
if (cancelRequest) {
throw {type: clientCancelledRequest};
}
/* Work on item */
});
});
promise.then(function() {
// Job done before client cancelled the request, send result to client
res.send(/* results */);
})
.catch(function(err) {
// Re-throw (or call next(err)) on non-cancellation exception
if (err.type !== clientCancelledRequest) {
throw err;
}
})
.done();
}
关于javascript - 使用 Express/Node.js 和 Angular 处理取消的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35198208/