Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine routes from multiple files in ExpressJS?

What is the best way to combine routes from two files so Express Router will handle them at the same level? I'm thinking of something like this:

Default Routes File
This file would be generated and overwritten every time the generator runs:

var express     = require('express'),
    router      = express.Router(),
    custom      = require('./custom.routes');

router.get('/', function (req, res) {
});
router.post('/', function (req, res) {
});
router.put('/', function (req, res) {
});

router.use('/', custom);

module.exports = router;

Custom Routes File
This file would only be generated the first time and would never be overwritten.

var express = require('express'),
    router  = express.Router();

router.post('/custom-method', function (req, res) {

});

module.exports = router;

Parent Route File
This file is generated and overwritten constantly. It is responsible for providing the top level api route:

var express = require('express'),
    apiRouter  = express.Router();

var widgetRouter = require('./widget.routes');
apiRouter.use('/widgets', widgetRouter);

var sprocketRouter = require('./sprocket.routes');
apiRouter.use('/sprockets', sprocketRouter);

module.exports = apiRouter;

The obvious goal is to allow the developer to customize the routes and know his work will be safe even when the generator is run again.

like image 316
Fred Lackey Avatar asked Sep 24 '15 17:09

Fred Lackey


People also ask

How does Express handle multiple routes?

Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express. js.

Can we use multiple routes in one application?

js Express App. When designing the routing system of the server, you have to make sure you have only one routing handler per path. Duplicating handler will affect the global performance of the server creating latency issues.

Can a request have two same routes?

Short answer is no.

How do I Group A route in node JS?

in express 4 to grouping your routes, you should create some changes : seperate route files in multiple files like admin and front. pass the router to the divided route files in routes/index. js file.


1 Answers

router.use() does not necessarily need to take you deeper in the tree. You could just add the following line before the exports of the first file.

router.use('/', require('./routes.custom.js'));

With this you can also remove the wrapper from the custom file.

like image 181
ahoff Avatar answered Oct 05 '22 07:10

ahoff