Jacob Jacob - 1 year ago 171
Javascript Question

Express - Conditional Routing

At my

endpoint, the incoming
looks like this:

choice: 'a',
data: [

I want to access a particular route depending on what the value of
is. If
req.body.choice === 'a'
then I want to go on to
with the same
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) {
// ?????????????????????????


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.');


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

Answer Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download