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

时间:2016-06-23 14:00:28

标签: node.js express routes

我有4个中间件功能:abcd

如果正文包含值X,我想执行a然后b,否则我想执行c然后执行d

我的代码如下所示:

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

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

这有更优雅的方式吗?有没有一种方法(或包)使这些路由器更具可读性?

1 个答案:

答案 0 :(得分:1)

我认为你不需要有两条路线。您可以在中间件req.body.Xa中查看b

// 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);