简体   繁体   English

基于请求参数的ExpressJS分支路由

[英]ExpressJS branching routes based on request parameters

I have 4 middleware functions: a , b , c , d . 我有4个中间件功能: abcd

If the body contains a value X , I want to execute a then b , else I want to execute c then d . 如果主体包含值X ,我想执行a然后b ,否则我想执行c然后d

My code looks like this: 我的代码如下所示:

app.post('/', (req, res, next) => {
  if (req.body.X) {
    next();
  } else {
    next('route');
    return;
  }
}, a, b);

app.post('/', c, d);

Is there a more elegant way for this? 有没有更优雅的方式呢? Is there a way (or package) that makes these kind of routers more readable? 有没有一种方法(或包装)使这些路由器更具可读性?

I think you don't need to have two routes for this. 我认为您不需要两条路线。 You can check for req.body.X in middlewares a and b . 您可以在中间件ab检查req.body.X

// Middlewares a and b
module.exports = function(req, res, next){
  if(req.body.X){/* Do stuff */} // if is the middleware "a" call next()
                                 // else, is "b" finish with a response i.e. res.send()
  else next();
}

// Middlewares c and d
module.exports = function(){
  // Do whatever, if middleware "c" call next() else finish with a response
}

// Route 
app.post('/', a, b, c, d);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM