dynamic routing based on request parameter in express.js Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of dynamic routing based on request parameter in express.js without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am building a RESTful API using expressJS, In my controller I have several functions like Chall_1, Chall_2,…

exports.validateChall_1 = function(res) {
//logic
  res.json(1);
};
exports.validateChall_2 = function(res) {
    res.json(2);
};
exports.validateChall_3 = function(res) {
    res.json(3);
};

in my router.js I want to route the URL to a specific function based on challId which is a parameter in url

'use strict';
module.exports = function(app) {
  var jsvalidator = require('../controllers/jsvalidatorController');
  app.route('/chall/:challId')
    .get(/*jsvalidator.validateChall_ + req.params.challId*/);
};

Is it possible to route directly to a specific function based on challId parameter?

Answer

you could do something like

app.route('/chall/:challId')
  .get(function (req, res, next) {
      switch (req.params.challId) {
        case 1:
         ctrl.validate_chall1(req, res, next);
         break;
        case 2:
         ctrl.validate_chall2();
         break;
        default:
         next() //it should continue to 404 route
         break;
  }
});

but I think doing this is better to keep the routes clean

app.route('/chall/challId/validate')
   .get(ctrl.validate)

//in ctrl 
function validate(req, res, next){
  if(req.params.challId === 1)
    validate_ctrl1()
  //etc
}
We are here to answer your question about dynamic routing based on request parameter in express.js - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji