Combine multiple routers in single route in express node
In the express framework of node you need to combine multiple routes in single so make code clear and clean. Here we are explaining the way to do this.
First of all, let us focus on directory structure first to make a clear understanding.
- config
- controllers
- models
- public
- routes
---- index.js
---- user.js
---- post.js
---- comment.js
- app.js
- package.json
Here you can see I have used a "route" directory to put all routes for the whole project.
In ES5:
let us take a look on user.js route:
var express = require('express');
var router = express.Router();
var UserController = require('../controllers/UserController');
router.get('/all', UserController.all);
router.get('/add', UserController.add);
router.get('/edit/:id', UserController.edit);
router.post('/update', UserController.update);
router.post('/saveRecord', UserController.saveRecord);
module.exports = router;
In the same way, we have created post and comment routes.
Now in index.js of route combine all the routes.
var express = require('express');
var rootRouter = express.Router();
var user = require('./user');
var post = require('./post');
var comment = require('./comment');
rootRouter.use('/user', uses);
rootRouter.use('/post', post);
rootRouter.use('/comment', comment);
module.exports = rootRouter;
Now in app.js add route as a middleware.
var express = require('express');
var app = express();
var rootRouter = require('./routes');
// Other middlewares and code
app.use('/', rootRouter);
// Other code here
In ES6:
let us take a look on user.js route:
import { Router } from 'express';
import UserController from '../controllers/UserController';
let router = Router();
router.get('/all', UserController.all);
router.get('/add', UserController.add);
router.get('/edit/:id', UserController.edit);
router.post('/update', UserController.update);
router.post('/saveRecord', UserController.saveRecord);
export default router;
In the same way, we have created post and comment routes.
Now in index.js of route combine all the routes.
import { Router } from 'express';
import user from './user';
import post from './post';
import comment from './comment';
let rootRouter = Router();
rootRouter.use('/user', uses);
rootRouter.use('/post', post);
rootRouter.use('/comment', comment);
export default rootRouter;
Now in app.js add route as a middleware.
import express from 'express';
import rootRouter from './routes';
let app = express();
// Other middlewares and code
app.use('/', rootRouter);
// Other code here