Basically, I want to avoid a situation where my main app file is flooded with a list of routes. I'm wondering whether it's possible to organize the routes for, say, users, clients, locations each to its own router file, and then have a sort of master router pull all of these files into my application's entry point (eg, index.js/server.js/app.js).
I'm shooting for something that resembles this, if possible:
app.js
const app = require('express')();
const mainRouter = require('app/routes/main');
app.use(mainRouter);
main.js
const mainRouter = require('express').Router();
const usersRouter = require('./users');
const locationsRouter = require('./locations');
mainRouter.use('/users', usersRouter);
mainRouter.use('/locations', locationsRouter);
module.exports = mainRouter;
You can split your routes up into logical groups using express.Router
objects. Each set of routes would be stored in the /routes
directory with a name that reflects what types of routes its associated with, for example clients.js
.
/routes/clients.js
const express = require('express')
const router = express.Router()
router.get('/', (req, res, next) => {
res.render('clients/index', { clients: [] })
})
module.exports = router
These routes would then be imported into your app.js
and registered with the app using the app.use()
method. This method also allows you to assign a base URL that each group of imported routes will be nested under. Which is why you don't need to specify the full path in each of your routes (eg: /details
instead of /clients/details
).
app.js
const express = require('express')
const app = express()
app.use('/clients', require('./routes/clients'))
Browse to http://localhost/clients/
and it will return views/clients/index.html
back to you. You'll notice that you can group your views in a similar structure.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.