Ben Ben - 1 year ago 134
Node.js Question

Empty params object in express.js middleware

const app = express();
var router = require('express').Router({mergeParams: true});
const payloadMiddleware = (req, resp, next) => {
const {params, query} = req;
const payload = req.body;
req.my_params = { params, query, payload };


router.get('/inventory/:itemID/price', async function GetPrice(req, res, next) {
console.log('B', req.my_params);
console.log('C', req.params);

app.use(bodyParser.urlencoded({extended: true}));
app.use('/', router);
server = app.listen(port);

GET /inventory/abc/price?a=1&b=2

A: {} # unclear why this is empty
B: { params: {},
query: { a: '1', b: '2' },
payload: {} }
C: {itemID: 'abc'}

So I'm confused: I expect my middleware to find
, construct the new object, and assign it to
, then pass that to the inventory handler. And this is partially happening, in that the querystring is being parsed and then assigned in my middleware. Why is
req.params === {}
in my middleware function, but
req.params = {itemID: 'abc'}
in the GET handler itself?

There are no other routes with the same pattern, no other middleware...

Also no change is observed when I remove the options object from the second line, i.e.
var router = require('express').Router();

Answer Source

payloadMiddleware is a generic middleware that isn't declared for any specific URL pattern containing parameters (it matches any request).

Express also doesn't know that requests passed to the middleware will eventually end up in the handler for /inventory/:itemID/price.

If you want the middleware to receive the parameters, you have to specifically use it against routes that match a pattern:

app.use('/inventory/:itemID/price', payloadMiddleware);

Or as part of the route handler:

router.get('/inventory/:itemID/price', payloadMiddleware, async function ...);