Router in Express Js

  • Certainly! In Express.js, a Router is a middleware that allows you to modularize your application's routes and handlers. It enables you to separate different parts of your application logic into distinct files, making your code more organized and maintainable. Let's explore the concepts of routers in Express.js from basic to advanced.
Basic Usage:
  • Creating a Router: In a separate file (e.g., `routes.js`), create a router using `express.Router()`:


    // routes.js
    const express = require('express');
    const router = express.Router();

    router.get('/', (req, res) => {
        res.send('Home Page');
    });

    router.get('/about', (req, res) => {
        res.send('About Page');
    });

    module.exports = router;

  • Using the Router in the Main App: In your main application file (e.g., `app.js`), import the router and use it:


    // app.js
    const express = require('express');
    const app = express();

    const mainRouter = require('./routes'); // Import the router

    app.use('/', mainRouter); // Use the router for paths starting with '/'

    app.listen(3000, () => {
        console.log('Server is running on port 3000');
    });

  • Route Parameters: You can use route parameters with routers in the same way you do with the main app:

    // routes.js
    const express = require('express');
    const router = express.Router();

    router.get('/users/:id', (req, res) => {
        const userId = req.params.id;
        res.send(`User ID: ${userId}`);
    });

    module.exports = router;

  • Sub-Routers: You can create sub-routers for specific routes:

    // adminRouter.js
    const express = require('express');
    const router = express.Router();

    router.get('/', (req, res) => {
        res.send('Admin Home Page');
    });

    router.get('/dashboard', (req, res) => {
        res.send('Admin Dashboard');
    });

    module.exports = router;

  • Then, in your main app:

    // app.js
    const express = require('express');
    const app = express();

    const mainRouter = require('./routes');
    const adminRouter = require('./adminRouter');

    app.use('/', mainRouter);
    app.use('/admin', adminRouter); // Mount the adminRouter under the '/admin' path

    app.listen(3000, () => {
        console.log('Server is running on port 3000');
    });

  • Middleware in Routers: You can use middleware in routers just like in the main app:

    // middleware.js
    const express = require('express');
    const router = express.Router();

    const customMiddleware = (req, res, next) => {
        console.log('Custom Middleware in Router');
        next();
    };

    router.use(customMiddleware);

    router.get('/example', (req, res) => {
        res.send('Example Route');
    });

    module.exports = router;

  • Router-Level Middleware: You can use middleware at the router level:

    // adminRouter.js
    const express = require('express');
    const router = express.Router();

    const adminMiddleware = (req, res, next) => {
        console.log('Admin Middleware');
        next();
    };

    router.use(adminMiddleware);

    router.get('/dashboard', (req, res) => {
        res.send('Admin Dashboard');
    });

    module.exports = router;


Advanced Concepts:

  • Error Handling: Routers can handle errors using a special middleware with four parameters:

    // routes.js
    const express = require('express');
    const router = express.Router();

    router.get('/error', (req, res, next) => {
        const err = new Error('Custom Error');
        next(err);
    });

    router.use((err, req, res, next) => {
        console.error(err.message);
        res.status(500).send('Internal Server Error');
    });

    module.exports = router;

  • This error-handling middleware will be triggered when an error occurs.
  • Nested Routers: You can nest routers for even more modularization:

    // routes.js
    const express = require('express');
    const router = express.Router();

    const subRouter = require('./subRouter');

    router.use('/sub', subRouter); // Nest the subRouter under '/sub'

    module.exports = router;

  • Summary: Express.js routers are a powerful way to organize and modularize your application. They allow you to encapsulate routes, middleware, and even error handling, making your code more maintainable and scalable.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...