javascript – 使用Express / Node.js和Angular处理已取消的请求

当客户端/浏览器取消挂起的HTTP请求时,似乎Node with Express继续处理请求.对于密集请求,cpu仍然忙于处理不必要的请求.

有没有办法要求Node.js / Express杀死/停止请求取消的这些待处理请求?

由于AngularJS 1.5 HTTP请求很容易通过在$http / $resource对象上调用$cancelRequest()来实现,因此它变得特别有用.

当暴露提供自动完成或搜索字段的结果的API方法时,可能会发生此类取消:在要自动填充的字段中键入或者键入aheaded时,可以取消先前的请求.

全局server.timeout无法解决问题:1)它是所有公开的API方法的全局设置2)已取消的请求中的持续处理未被终止.

解决方法:

注入的reqobject随监听器.on()一起提供.

收听关闭事件允许处理客户端何时关闭连接(请求由Angular取消,或者例如,用户关闭查询选项卡).

以下是2个简单示例,说明如何使用closeevent来停止请求处理.

示例1:可取消的同步块

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的可取消异步块(类似于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();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。