ExpressJS Tips: Cleaner Routes
When our application become larger, it's becoming harder to maintain a huge list of routing in one file. I found that it's easier to split the routes into each own section.
Here's how i do that
Example Directory Layoutapp.js
controllers
routes
--- index.js
--- posts.js
--- users.js
Example Code
/routes/index.jsconst router = require('express').Router();
router.use('/posts',require('./posts.route'));
router.use('/users',require('./users.route'));
module.exports = router
/routes/users.route.jsconst router = require("express").Router();
const UsersController = require("../controllers/user.controller");
router.get("/", UserController.index);
module.exports = router;
app.js//import all routes
app.use("/api/v1", require("./src/routes/index"));
Example Endpoint ResultsGET /api/v1/users
GET /api/v1/posts
That's all!
Comments