在Express中跳转到不同的路线链

Ale*_*lls 10 regex node.js express

我在Express中发现了一个非常有用的设备,可以在Express中跳转到一个新的中间件链

说我们有这个:

router.post('/', function(req,res,next){

   next();

}, function(req,res,next){

   next('route');  //calling this will jump us down to the next router.post call

}, function(req,res,next){ //not invoked

   next();  

}, function(err,req,res,next){

      //definitely not invoked
});



router.post('/', function(req,res,next){  //this gets invoked by the above next('route') call

   next();


}, function(err,req,res,next){

});
Run Code Online (Sandbox Code Playgroud)

我可以看到这可能有用,并试图弄清楚它是如何工作的.

我看到的问题是这个解决方案似乎只是让我们能够在路上行驶一下.我想要的是能够调用next('route:a')或next('route:b'),这样我就可以选择按名称调用哪个处理程序,而不仅仅是列表中的下一个处理程序.

举个例子,我有这个:

router.post('/', function (req, res, next) {  //this is invoked first
    console.log(1);
    next('route');
});

router.post('/', function (req, res, next) {  //this is invoked second
    console.log(2);
    next('route');
});

router.use('foo', function (req, res, next) {  //this gets skipped
    console.log(3);
});

router.post('bar', function (req, res, next) {  //this get skipped
    console.log(4);
});

router.post('/', function(req,res,next){  // this gets invoked third
    console.log(5);
 });  
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是一种通过名称调用"foo"和"bar"的方法.Express有没有办法做到这一点?

Ais*_*ngh 5

实际上next('route')去下一个路线,但你的网址/不是foo这样,它跳过那个并转移到下一个路由,直到它找到匹配的路由,这发生在最后一个案例,你进入5控制台

如果你想要你可以改变req.url到类似foo或类似的东西,那么它将进入该路线(并且它不会跳过该路线的中间人)或者你可以做一些像res.redirect那样的呼叫将再次来自客户

router.post('/', function (req, res, next) {  //this is invoked second
    console.log(2);
    req.url="foo";
    next('route');
});
Run Code Online (Sandbox Code Playgroud)

实际上@ zag2art方法很好,在一天结束时你必须保持足够聪明的代码来优雅地处理你的案件.Express不提供任何此类内容以跳至特定路线


zag*_*art 1

为什么你没有这样的东西:

router.post('/', function (req, res, next) {  //this is invoked first
    console.log(1);
    foo(req, res, next);
});

router.post('/', function (req, res, next) {  //this is invoked second
    console.log(2);
    bar(req, res, next);
});

function foo(req, res, next) { 
    console.log(3);
};

function bar(req, res, next) { 
    console.log(4);
};

router.post('/', function(req,res,next){  // this gets invoked third
    console.log(5);
});
Run Code Online (Sandbox Code Playgroud)