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


here's modified example express.js's routing guide:

var express = require('express'); var router = express.router();  router.get('/', 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 visit both /birds/about , /fish/about.

how pass parameter or router so, in controller functions, can tell 2 different routes apart?

for example, i'd see "birds can fly" when visiting /birds/about , "fish can swim" when visiting /fish/about.

ideally, i'd able pass "configuration object" mini-app not need know possible routes may mounted @ (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 i've come with: pass "mini-app configuration" assigning 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 in route 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 mount "mini-app" @ location providing different configuration, without modifying code of app:

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

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -