在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){ });
我可以看到这可能是有用的,并试图找出它是如何工作的。
我看到的问题就是这个解决scheme似乎只是在路上稍微踢了一下。 我想要的是能够调用next('route:a')或next('route:b'),以便我可以select由名称调用的处理程序,而不仅仅是列表中的下一个处理程序。
举个例子,我有这个:
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); });
我正在寻找的是一种通过名称来调用“foo”和“bar”的方法。 Express有没有办法做到这一点?
其实next('route')
去下一个路线,但你的url是/
不是foo
所以它跳过,并移动到下一个路线,直到find一个匹配的,这发生在最后一种情况,你得到5
控制台
如果你想要你可以把req.url
foo
或者其他类似的东西,那么它就会进入这个路由(并且不会跳过这个路由的中间值),或者你可以做一些类似res.redirect
事情,然后再次调用客户
router.post('/', function (req, res, next) { //this is invoked second console.log(2); req.url="foo"; next('route'); });
其实@ zag2art的方法是好的,在一天结束的时候,你必须保持你的代码聪明,足以处理你的案例优雅。 Express不提供任何这样的内容来跳转到特定路线
你为什么不这样做呢?
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); });