Question
Are there naming conventions on router files?
Answer
Nothing required, like many other things in Express, route files are flexible, but in terms of community, there has been a certain agreement on naming conventions, to pair the file name with the route, and some places do ask to write the word route as part of the name. ie monsterRoutes.js
but again, most commonly we can see simply monsters.js
related to the /monsters
route. Another thing to have in mind is that having a router.js
file that handles all the route connections is also common, for example the following file map:
mainApplicationDirectory/
|
|
|
__ app.js
__ router.js
|
|
__ routes/
|
|
__ monsters.js
__ animals.js
__ fruits.js
We can see that now we could also have a directory of routes where each route handler file exists and are connected to our app through a main router.js
file. This sort of system is commonly seen when there is a hight complexity in our routes that is better to have a middleware to handle routes instead of implementing app.use('/route', routeHandler)
inside of app.
7 Likes
Could you give us an example code of router.js
? Would it be something like:
const express = require('express');
const router = express.Router();
const monsters = require('./routes/monsters.js');
const animals = require('./routes/animals.js');
const fruits = require('./routes/fruits.js');
router.use('/routes', monsters, animals, fruits);
module.exports = router;
and then in app.js
,
const router = require('./router.js');
app.use('/', router);
Am I correct?
I also spent some time on this question, but then I find out this example Example on the next page, so I think the correct answer should be.
router.js
const exampleRouter = require('express').Router();
const monstersRoute = require('./routes/monsters.js');
const animalsRoute = require('./routes/animals.js');
const fruitsRoute = require('./routes/fruits.js');
exampleRouter.use('/monsters', monstersRoute);
exampleRouter.use('/animals', animalsRoute);
exampleRouter.use('/fruits', fruitsRoute);
and the app.js should be
const express = require('express');
const app = express();
const appRouter = require('./router.js');
app.use('/routers', appRouter);
and if there is any get post put delete related to router, you can also write them inside the router.js
I am not very sure about this but this is my thought.
1 Like
In the following example from the exercise, would an export default statement (export default expressions;) work instead of module.exports? If not, why?
// monsters.js
const express = require(‘express’);
const monstersRouter = express.Router();
const monsters = {
‘1’: {
name: ‘godzilla’,
age: 250000000
},
‘2’: {
Name: ‘manticore’,
age: 21
}
}
monstersRouter.get(’/:id’, (req, res, next) => {
const monster = monsters[req.params.id];
if (monster) {
res.send(monster);
} else {
res.status(404).send();
}
});
module.exports = monstersRouter;