从express / nodejs中的路由特定中间件链中退出 [英] exit from chain of route specific middleware in express/ nodejs

查看:146
本文介绍了从express / nodejs中的路由特定中间件链中退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条路由特定中间件链接,如下所示:

I have a chain of "route specific middleware" for this route, like so:

    var express = require('express');
    var server = express();
    var mw1 = function(req, resp, next) {
        //do stuff
        if (success) {
            next();
        } else {
            req.connection.destroy(); //without calling next()
        }
    };
    var mw2 = function(req, resp, next) {
        //do stuff
        if (success) {
            next();
        } else {
            req.connection.destroy(); //without calling next()
        }
    };
    server.post('/some/path', [mw1, mw2], function(req, resp) {
        //write response
    });

[mw1,mw2] 是中间件特定于路线 / some / path

[mw1, mw2] are the middleware specific to the route /some/path.

这与这样的服务器范围的中间件不同: p>

This is different from server-wide middleware like this:

    server.use(mw1);
    server.use(mw2);

适用于所有定义的路线。

Where it applies to all routes defined.

现在我的问题是我想退出链条。即如果 success mw1 中为false,我不希望 mw2 被调用。如果 success mw2 中为false,我不需要调用路由功能。目前, mw1 mw2 似乎被调用,无论 next()被调用 - 我不知道为什么。

Now my issue is that I want to exit from the chain. I.e. if success is false in mw1, I do not wish for mw2 to be called. If success is false in mw2, I do not without for the route function to be called. Presently, both mw1 and mw2 appear to be getting called whether or not next() is called - and I do not know why.

我该怎么做?

推荐答案

一点点修补得出答案:

var express = require('express');
var server = express();
var mw1 = function(req, resp, next) {
  //do stuff
  if (success) {
    next();
  } else {
    resp.send(406, 'Invalid because of this');
    req.connection.destroy(); //without calling next()
  }
};
var mw2 = function(req, resp, next) {
  //do stuff
  if (success) {
    next();
  } else {
    resp.send(406, 'Invalid because of that');
    req.connection.destroy(); //without calling next()
  }
};
server.post('/some/path', [mw1, mw2], function(req, resp) {
  //write response
});

诀窍是发送回复: resp.send(406,'Invalid因为这个');

在破坏连接之前: req.connection.destroy();

实际上并没有破坏连接,我发现在一般情况下也可以工作。

In fact not destroying the connection, I found to also work, in the general case.

(但是在我的具体情况下是需要的,超出了这个问题的范围)。

(But was required in my specific case, and is out of the scope of this question.)

如果响应已经发送,那么express不会自动调用 next(),因为它似乎以其他方式。

If the response has already been sent, then express does not automatically call next() for you, as it appeared to do otherwise.

这篇关于从express / nodejs中的路由特定中间件链中退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆