javascript - Empty params object in express.js middleware -


const app = express(); var router = require('express').router({mergeparams: true}); const payloadmiddleware = (req, resp, next) => {   console.log('a:',req.params);   const {params, query} = req;   const payload = req.body;   req.my_params = { params, query, payload };   next(); };  router.use(payloadmiddleware);  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(bodyparser.json()); app.use('/', router); server = app.listen(port); 

get /inventory/abc/price?a=1&b=2 yields

a: {} # unclear why empty b: { params: {},      query: { a: '1', b: '2' },      payload: {} }  c: {itemid: 'abc'}  

so i'm confused: expect middleware find params in req, construct new object, , assign req my_params, pass inventory handler. , partially happening, in querystring being parsed , assigned in middleware. why req.params === {} in middleware function, req.params = {itemid: 'abc'}in handler itself?

there no other routes same pattern, no other middleware...

also no change observed when remove options object second line, i.e. var router = require('express').router();

payloadmiddleware generic middleware isn't declared specific url pattern containing parameters (it matches any request).

express doesn't know requests passed middleware end in handler /inventory/:itemid/price.

if want middleware receive parameters, have use against routes match pattern:

app.use('/inventory/:itemid/price', payloadmiddleware); 

or part of route handler:

router.get('/inventory/:itemid/price', payloadmiddleware, async function ...); 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -