Params from root route not showing

Hi all,

So i have a file called commands.routes.js and inside i use the express router to create a get route on the ‘/’ path. So then i add the routes in my express config, like so: app.use('/panel/server/:id/commands', commands); however, when i output req.params in my route, its empty and the ‘:id’ param is not there. Is this purposeful or is it a mistake?

Thanks
Rushmead

Author: Fantashit

1 thought on “Params from root route not showing

  1. @Rushmead if you really do need to declare your params in the main file, you can use the mergeParams option when creating your sub router (https://expressjs.com/en/4x/api.html#express.router) to preserve the req.params from the parent router:

    'use strict';
    const express = require('express');
    const app = express();
    const commands = express.Router({ mergeParams: true });
    commands.get('/', function (req, res, next) {
        res.send(req.params.id);
    });
    app.use('/panel/server/:id/commands', commands);
    app.listen(3000);

    By default, routing is generally isolated between routers, and the parameters of a route is considered routing and can conflict with routes in sub routers, so by default, req.params is not preserved between routers. The mergeParams constructor option of a router allows you to explicitly say it’s OK to see the parameters from the parent route 🙂

Comments are closed.