Jacob Jacob - 4 months ago 32
Javascript Question

Express - Conditional Routing



At my

website.com/v2/bridge/:locationId/process
endpoint, the incoming
req.body
looks like this:

{
choice: 'a',
data: [
{
...
},
...
]
}


I want to access a particular route depending on what the value of
req.body.choice
is. If
req.body.choice === 'a'
then I want to go on to
website.com/v2/bridge/:locationId/process/choiceA
with the same
req
being passed on.

I don't know what middleware I need to use to accomplish that. I don't know if that is even possible.

My extremely simplified routes:

// website.com/v2/bridge
const proc = require('./process');

router.use('/:locationId/process', proc);

module.exports = router;




// website.com/v2/bridge/56/process
router.use(function (req, res, next) {
// ?????????????????????????

next();
});

const choiceA = require('./choice-a');
const choiceB = require('./choice-b');

router.use('/choice-a', choiceA);
router.use('/choice-b', choiceB);

module.exports = router;





// website.com/v2/bridge/56/process/choice-a
router.post('/', function (req, res) {
res.send('I got here.');

return;
});

module.exports = router;


What middleware function do I need to include to conditionally route my request? I am trying to avoid one giant function with if statements that process different things according to the value of
req.body.choice
.

Answer

This will be little trickier for you...give it a try

router.use(function (req, res, next) {
  req.path = "/" + "choice-"+req.body.choice
  req.url = "/" + "choice-"+req.body.choice
  next();
});

now it'will do the request to the end point you want