是否可以在node express中跳过路由中间件? [英] Is it possible to skip route middleware in node express?

查看:267
本文介绍了是否可以在node express中跳过路由中间件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以快递方式执行以下POST功能. (我使用的是Express 3.5.1)

Take the following POST function in express. (I am using express 3.5.1)

app.post('/example', someFunctionOne, someFunctionTwo, function(req, res){
    if(!req.someVar){
        return res.send(400, { message: 'error'});
    } else{
        return res.json(200, { message: 'ok'}); 
    }
});

如果我从someFunctionOne得到了一些结果,这意味着someFunctionTwo是多余的,是否可以跳过someFunctionTwo并转到最后一个未命名的函数,该函数将发送响应?

If I get some result from someFunctionOne which means someFunctionTwo is redundant, is there a way to skip someFunctionTwo and go to the last unnamed function which will send the response?

所以我想以同样的方式存在"next()"函数,"last()"函数在哪里?如果不可能,为什么不呢?在我看来,这似乎是一种疏忽,但是有充分的理由吗?

So I guess in the same way there is the "next()" function where is the "last()" function? If this is not possible why not? It seems like an oversight to me but is there a good reason?

推荐答案

您可以执行next('route'),该操作将完全转到下一条路线.在这种情况下,这并不是您真正需要的,但是如果您将代码分成2条单独的路由,则可以使用.

You can do next('route') which will go to the next route entirely. This is not exactly what you need in this case, but it would work if you broke your code up into 2 separate routes.

但是,我认为通常有两种方法可以处理这种条件逻辑:

However, I think there are generally 2 approaches to this kind of conditional logic:

  • make someFunctionOne在得到特殊结果时在req实例上放置一些状态,并使someFunctionTwo足够聪明以进行检查,并在找到时调用next()并绕过自身.这是最惯用的表达方式,也是大多数中间件检测到在同一请求上多次调用它们时避免再次重做其工作的方式.
  • someFunctionOne中,当发生特殊情况时,只需直接调用lastFunction.记住,中间件抽象不是圣杯.如果您的中间件如此紧密地耦合在一起,也许它们应该是一个中间件和一些辅助功能.还有许多其他组织代码的方式可能会更自然.
  • make someFunctionOne put some state on the req instance when it gets the special result and make someFunctionTwo smart enough to check for that and when found call next() and bypass itself. This is the most idiomatic express thing to do, and it's how most middleware detect when they have been called more than once on the same request and avoid redoing their work again.
  • In someFunctionOne, when the special case happens, just invoke lastFunction directly. Remember the middleware abstraction isn't the holy grail. If your middleware are so tightly coupled, maybe they should be one middleware and some helper functions. There are lots of other ways to organize code that might feel more natural.

这篇关于是否可以在node express中跳过路由中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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