2016-06-23 45 views
0

我有4个中间件函数:a,b,c,dExpressJS基于请求参数的分支路由

如果体内含有一种价值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); 

是否有这一个更优雅的方式?有没有使这些路由器更具可读性的方法(或软件包)?

+0

检查每个中间件中的req.body.x并制作唯一路由:app.post('/',a,b,c,d) –

回答

1

我认为你不需要有两条路线。您可以在中间件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);