Reputation: 2113
I am trying to separate parts of my routes in different files
I have a /houses/
route and a /houses/:houseid/bookings
route
I have /houses/ in a routesHouses.js file and I want to put part of the bookings routes in a routesBookings.js file, but it doesn't work as I can't get the :houseid parameter.
The params object is empty
I am setting the route with
app.use('/profile/houses/:hid/bookings', bookingRoutes)
And in routeBookings.js
router.get('/', auth, (req, res) => {
database('sh_bookings').select('*').where('b_house_id', req.params.hid).then((bookings) => {
res.render('profile/bookings/bookings.ejs', {
bookings: bookings,
moment: moment
})
}).catch(() => {
res.status(500).send('An error occured')
})
})
It just hits the catch right away as req.params.hid
is empty
If I move the route into the routesHouses with
router.get('/:hid/bookings')
it works, but I want to have it separated.
Upvotes: 2
Views: 970
Reputation: 126
I don't believe you can use the express router like that. The booking Routes router does not have access to the other routers param's because booking Routes only has access to anything after the 'parent' routers URL.
If you really feel the need to do it like that here is a little sample code to get around it. But id say try and restructure your API routes cause i'm not sure how good this is to do.
Sorry for so many edits. Decided it would be better to extract that logic into a middleware function
const bindHid = (req, res, next) => {
req.hid = req.params.hid;
next();
}
app.use('/homes/:hid/bookings', bindHid, bookingRoutes)
bookingRoutes.use('/', (req, res, next) => {
res.send(req.hid)
})
Upvotes: 5