简体   繁体   中英

ExpressJS: require multiple files with app.use()?

Routing :

app.use('/cms/', require('./routes/index.js'));
app.use('/cms/schools/', require('./routes/schools.js'));

Routes :

/cms/
/cms/schools/
/cms/schools/:schoolId/classes/:classId

Goal : I'd like to split ./routes/schools.js into two files: schools.js and schools_classes.js , to keep a better overview.

Problem : I'd like to keep the prefixed path /cms/schools/ , but don't know how to split it correctly.

How can I structure the files to reach the desired goal? Thanks in advance!

Edit 1 : I tried the following, which is not working (duplicated route prefix):

app.use('/cms/', require('./routes/index.js'));
app.use('/cms/schools/', require('./routes/schools.js'));
app.use('/cms/schools/', require('./routes/schools_classes.js'));

You can do It using the express router:

Routes:

const schoolsRouter = require('./routes/schools');
app.use('/cms/schools', schoolsRouter)

./routes/schools/index.js:

const express = require('express');
const router = express.Router();

router.use('/',require('./schools _controller.js'));
router.use('/:schoolId/classes/:classId', require ('./schools_classes_controller.js'));

module.exports = router;

You can check the entire router docs here: http://expressjs.com/en/4x/api.html#router

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM