[英]ExpressJS branching routes based on request parameters
我有4个中间件功能: a
, b
, c
, d
。
如果主体包含值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);
有没有更优雅的方式呢? 有没有一种方法(或包装)使这些路由器更具可读性?
我认为您不需要两条路线。 您可以在中间件a
和b
检查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.