6

For the code below:

router.use('/campaigns/:campaign_uid', cache.node_cache, api_dynamic_campaign.router);

I have a router route to another router which looks like this:

router.get('/data.json', campaigns);

The handler looks like this:

function campaigns(request, response){
    var campaign = api.get_campaign_from_request(request) || request.params.campaign_uid;
    api.route_handler(request, response, {"campaign":campaign});
}

My issue is the handler does not have access to campaign_uid in the request.params. How do I access/pass the campaign_uid to the handler?

Brian Yeh
  • 3,119
  • 3
  • 26
  • 40
  • 3
    Your middleware can add properties to the `req` object and those properties will be accessible to other route handlers down the chain. That's what lots of middleware handlers already do for things like cookies and query parameters, etc... – jfriend00 Mar 03 '16 at 22:49
  • I believe that this is what app.param or router.param is meant for. – Molda Mar 04 '16 at 09:20
  • 2
    Possible duplicate of [Rest with Express.js nested router](https://stackoverflow.com/questions/25260818/rest-with-express-js-nested-router) – mitchken Jun 07 '17 at 08:48

1 Answers1

3
router.get('/data.json', campaigns).Router({ mergeParams: true })

https://cedric.tech/blog/expressjs-accessing-req-params-from-child-routers

Trieu
  • 31
  • 2
  • Please take some time in actually explaining the content of your answer. Sometimes it can be helpful to post external references, but that's only a good top up to an already very exhaustive answer – BiOS Feb 28 '21 at 09:09