How do I pass a parameter to express.js Router?

Here’s a modified example from Express.js’s routing guide:

var express = require('express');
var router = express.Router();

router.get("https://stackoverflow.com/", function(req, res) {
  res.send('Birds home page');
});

router.get('/about', function(req, res) {
  res.send('About birds');
});

...
app.use('/birds', router);
app.use('/fish', router);

This prints “About birds” when I visit both /birds/about and /fish/about.

How do I pass a parameter or something to the router so, in the controller functions, it can tell those two different routes apart?

For example, I’d like to see “Birds can fly” when visiting /birds/about and “Fish can swim” when visiting /fish/about.

Ideally, I’d like to be able to pass some “configuration object” so the mini-app does not need to know about all possible routes it may be mounted at (in pseudocode):

    router.get('/about', function(req, res) {
      res.send(magic_configuration.about_text);
    });
   ....
   magically_set_config(router, {about_text: "Bears eat fish"})
   app.use('/bears', router);

Here’s what I’ve come up with: I pass the “mini-app configuration” by assigning it to req:

app.use('/birds', function (req, res, next) {
    req.animal_config = {
        name: 'Bird',
        says: 'chirp'
    };
    next();
}, animal_router);

app.use('/cats', function (req, res, next) {
    req.animal_config = {
        name: 'Cat',
        says: 'meow'
    }
    next();        
}, animal_router);

and then in my route I can access them:

var express = require('express');
var router = express.Router();

...

router.get('/about', function(req, res) {
  var animal = req.animal_config;
  res.send(animal.name + ' says ' + animal.says);
});

This approach allows to easily mount the “mini-app” at another location providing different configuration, without modifying the code of the app:

app.use('/bears', function (req, res, next) {
    req.animal_config = {
        name: 'Bear',
        says: 'rawr'
    };
    next();
}, animal_router);

You’re basically talking about injecting configuration to a router.

I have faced with similar problem and figured out that in theory you can export not a router itself, but rather function that accepts configuration and returns created and configured router.

Read More:   How do I resize a Google Map with JavaScript after it has loaded?

So in your case calling code will look like:

var animal_router = require('./animal_router')

app.use('/birds', animal_router({
    name: 'Bird',
    says: 'chirp'
}));

app.use('/cats', animal_router({
    name: 'Cat',
    says: 'meow'
}));

While ./animal_router.js might look following:

var express = require('express');

// Create wrapper function that will adjust router based on provided configuration
var wrapper = function (animal_config) {
    var router = express.Router();
    
    router.get('/about', function(req, res) {
        var animal = animal_config;
        res.send(animal.name + ' says ' + animal.says);
    });

    return router;
}

module.exports = wrapper;

So, if you want to serve changes by url, then you can inject params like this:

router.get('/:animal/about', function(req, res) {
    // here we have bird or fish in req.params.animal
    if(req.params.animal == 'bird') {
        res.send('Birds can fly');
    } else if(req.params.animal == 'fish') {
        res.send('Fish can swim');
    } else {
        res.send('Unknown animal');
    }
});
app.use("https://stackoverflow.com/", router);

You can use req.baseUrl to figure that out.

You can add route params like so:

router.get('/about/:param1/:param2', function(req, res) {
 //then you can call this handler  through /about/1/sometext get these params from request object:
  console.log(req.params.param1, req.params.param2); // 1, 'sometext'
  res.send('About birds');
});

Or you can send parameters through query params:

router.get('/about', function(req, res) {
 //then you can call this handler  through /about?param1=1&param2=sometext get these params from request object as well:
  console.log(req.query.param1, req.query.param2); // 1, 'sometext'
  res.send('About birds');
});


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts