In this section, we will discuss how to set up and use routers in an Express application. Routers are an essential part of structuring a Node.js application, especially when it comes to managing different endpoints and organizing code.

Process

  1. Creating a Router:

    const router = require('express').Router();
    

    This initializes a new router object which can be used to define route handlers.

  2. Importing Module Routers:

    const UserRouter = require('../modules/users/users.router');
    const ModuleRouter = require('../modules/<module_name>/module.router');
    

    Imports the router for our module. Replace <module_name> with the actual module name you are using.

  3. Defining Routes:

    router.use("/user", UserRouter);
    router.use("/Module", ModuleRouter);
    

    Mounts the module router on the /Module path. This modular approach helps in keeping the code organized and maintainable.

  4. Exporting the Router:

    module.exports = router;
    

    Exports the configured router so it can be used in the main Express application.

Code Overview

Here is the code snippet for the Express configuration:

const router = require('express').Router();

const UserRouter = require('../modules/users/users.router');
const ModuleRouter = require('../modules/<module_name>/module.router');

router.use("/user", UserRouter);
router.use("/Module", ModuleRouter);

module.exports = router;

Add modules as per your project requirements and moduleRoute according to exports of you project router.js

Conclusion

This Express configuration sets up essential middleware for request parsing, routing, and error handling. It ensures that your application can correctly interpret incoming requests, manage routes, and gracefully handle errors, providing meaningful responses to the client. This configuration forms the backbone of a well-structured Express application, ready to handle various web application needs.

Reference

Express Tutorial Part 4: Routes and controllers - Learn web development | MDN

Understanding Routing In Express.js As Simple As Possible