Params registered on app available in routers used by app
- Dominant language
- JavaScript
- Stars
- 69.5k
- Forks
- 25k
- Avg merge
- 4d 20h
- Merged PRs (30d)
- 9
Description
I discovered today that it seems params registered on `app` are not respected in routes registered via a router (`express.Router()`). Perhaps I'm just missing something though!
While sectioning an application's routes via routers is super handy, having to re-register shared params on each of them is not.
A use case to consider: an application that has a page which renders user details in which the view needs the user data, and in addition the app exposes an API to get the raw JSON response for use by a client-side app, mobile app, or third party.
``` javascript
var express = require('express');
var app = express();
// Shared Params
app.param('user', function (req, res, next, id) {
req.user = { id: id, name: 'Fred' };
next();
});
// Website
app.get('/users/:user', function (req, res) {
res.render('user', req.user);
});
// Application API (JSON Responses)
var APIRouter = express.Router();
router.get('/users/:user', function (req, res) {
res.json(req.user); // req.user is undefined!
});
app.use('/api', APIRouter);
// App Start
app.listen(8000);
```
Seems that shared params across application "sections" when using routers would be a very common scenario.
---
Maybe this is going too far, but it'd make sense that any param registered on a parent router applied to its children, but possibly not visa-versa:
``` javascript
var parent = express.Router();
var child = express.Router();
parent.param('foo', function (req, res, next) {
req.foo = { ... };
next();
});
child.param('bar', function (req, res, next) {
req.bar = { ... };
next();
});
parent.get('/:foo/:bar', function (req, res) {
res.json({
foo: req.foo, // OK!
bar: req.bar // undefined
});
});
child.get('/:foo/:bar', function (req, res) {
res.json({
foo: req.foo, // OK!
bar: req.bar // OK!
});
});
parent.use(child);
```
Thoughts/advice appreciated!
Contributor guide
Assessment
This issue has not been assessed yet.