I am trying to figure out how to split the routes in my routes.js file into multiple files. My current routes.js file looks like this:
const pullController = require('./controllers/pullController');
const userController = require('./controllers/userController');
const routes = require('express').Router();
routes.get('/openpullinfo', pullController.getOpenPullRequestInfo);
.
.
.
routes.post('/user', userController.createUser);
module.exports = routes;
I want to have a different routes file (i.e. userRoutes.js
) for each controller because there are just too many routes in my single routes.js file and it's becoming unmanageable.
You can create a set of routes file (userRoutes.js
, pullRoutes.js
...). In these files, you can use the express.Router class to create modular, mountable route handlers. Then in the main file, you mount all your routers in your Express application.
const express = require('express');
const router = express.Router();
router.get('/', function (req, res) {
res.send('Get users controller');
});
router.post('/', function (req, res) {
res.send('Post user controller');
});
module.exports = router;
const express = require("express");
const app = express();
app.use(express.urlencoded())
app.use(express.json())
const userRoutes = require('./userRoutes');
app.use('/users', userRoutes);
app.listen(80);
In the browser, http://localhost/users
gives me the text Get users controller