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
Hi @Rushmead ,
when you attach router sub application to express you have to handle the params as if your main app was that you just attached.
'use strict';
const express = require('express');
const app = express();
const mySubApp = express.Router();
mySubApp.get('/myRoute/:myParam', function (req, res, next) {
res.send(req.params.myParam);
});
app.use('/my-app', mySubApp);
app.listen(3000);
So when you execute a get request like this:
GET /my-app/myRoute/123456
you access to param called myParam and in the example above ou get it in response.
For more explanation take a look to this documentation
Hope this help you
Nick
Hi @NickNaso
Thanks for the reply, not sure i quite understand what your saying. I have to add the params in the sub app instead of the main app?
Thanks
Rushmead
Hi @Rushmead
Yes, you're right this is the point, add the params in the sub app instead of the main app.
Nick
@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 :)
Most helpful comment
@Rushmead if you really do need to declare your params in the main file, you can use the
mergeParamsoption when creating your sub router (https://expressjs.com/en/4x/api.html#express.router) to preserve thereq.paramsfrom the parent router: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.paramsis not preserved between routers. ThemergeParamsconstructor option of a router allows you to explicitly say it's OK to see the parameters from the parent route :)