Reputation: 407
I'm trying to have all my controllers called in a file called index, so I don't just build all express routes in one file.
Therefore my index.js looks like:
//imports and stuff
router.use('/auth', require('./auth'))
router.use('/users', require('./users'))
router.use('/:world_id/villages', require('./villages'))
//export router
Then i have the auth.js and users.js files.
auth.js:
router.route('/register')
.post(function(req, res) {
//register the user
})
users.js:
router.route('/:user_id')
//GET user profile
.get(function(req, res){
// Use the req.params.userId to get the user by Id
})
And this works well for these 2 both. Accessing /api/auth/register
or /api/users/:user_id
works as expected.
But when trying to go for /api/{world_id}/villages
this doesn't go as expected because the world_id
parameter does not get passed to the file processing it which is villages.js
villages.js:
router.route('/')
//GET all villages of the current world (world_id)
.get(function(req, res){
// Use the req.params.world_id to get it... but this is undefined :(
})
How can I have this file structure so my controllers don't get messy and at the same time, pass this parameter to the controller file so that it can use it even if the route is ('/')?
Upvotes: 1
Views: 870
Reputation: 247
The only way to make any parameter visible inside the child router is to define it there. So in you'r example
router.route('/:world_id/villages/')
//GET all villages of the current world (world_id)
.get(function(req, res){
// req.params.world_id is set
})
// ...
app.use('/', router);
Upvotes: 2