Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move routes into files in Express.js

Say I have some routes (I have a lot more, but this should explain):

router.post('/post');
router.get('/post/:id');
router.get('/posts/:page?');
router.get('/search');

For the /post ones I know I could do something like

app.use('/post', postRoutes)

Where postRoutes is the actual post routes in another file. However, I'd like to group all post related routes into a postRoutes component (so /post and /posts), search into a search component and so on. Is there a way to do something like

router.use(postRoutes); // includes routes 1-3 above
router.use(searchRoutes); // only the 4th route above

And so on? That would let me keep the top level file much cleaner.

like image 463
Oscar Godson Avatar asked Jan 27 '26 08:01

Oscar Godson


1 Answers

Yes it is simple. You can even make more nesting levels. I think it is good to separate routes, especially when you have dozens of routes. in your first file (server.js)

app.use(require("./allpost"));
app.use(require("./allqueries"));

in allpost.js

var express = require('express');
var router = new express.Router();
router.post('/post', function (req, res) {
   //your code 
});
router.get('/post/:id', function (req, res) {
   //your code 
});
router.get('/posts/:page?', function (req, res) {
   //your code 
});

when you want more nesting

router.use(require("./deeper"));

or when you want use path part

router.use("/post2/", require("./messages/private"));
module.exports = router;
like image 167
Krzysztof Sztompka Avatar answered Jan 28 '26 23:01

Krzysztof Sztompka