微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则表达式 – 跳转到Express中的不同路由链

我发现Express中相当有用的设备可以跳转到Express中的一个新的中间件链

说我们有这个:

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

   next();

},next){

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

},next){ //not invoked

   next();  

},function(err,req,next){

      //definitely not invoked
});



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

   next();


},next){

});

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

我看到的这个问题就是这个解决方案似乎只能让路可以踢了一下.我想要的是能够调用next(‘route:a’)或next(‘route:b’),所以我可以通过名字来选择要调用的处理程序,而不仅仅是列表中的下一个.

例如,我有这个:

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

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

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

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

router.post('/',next){  // this gets invoked third
    console.log(5);
 });

我正在寻找的是一种通过名称调用“foo”和“bar”的方法.有没有办法用Express?

实际上下一个(‘route’)去下一个路由,但是你的url是/不是foo,所以它跳过并移动到下一个路由,直到找到一个匹配的路由,这在最后一个情况发生,你在控制台中得到5

如果你希望你可以把req.url改成foo或者其他的东西,那么它会进入这个路由(不会跳过中间路由),或者你可以像res.redirect这样做,那么call会再来一次客户

router.post('/',next) {  //this is invoked second
    console.log(2);
    req.url="foo";
    next('route');
});

实际上@ zag2art的方法是好的,最后一天你必须保持ur代码足够聪明地处理你的案例. Express不提供任何东西,以跳过一个特别的路线

原文地址:https://www.jb51.cc/regex/356682.html

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

相关推荐