简体   繁体   中英

ExpressJS branching routes based on request parameters

I have 4 middleware functions: a , b , c , d .

If the body contains a value X , I want to execute a then b , else I want to execute c then 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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