Your Page Title
🔍

    ROUTING IN NODE.JS

    In Node.js, routing refers to the mechanism by which an HTTP server determines how to handle different incoming requests based on the request’s URL and method.

    When a client sends a request (e.g., GET /home or POST /login), the server evaluates this information and “routes” it to the appropriate function or handler. This process ensures that each endpoint (URL path + HTTP method) triggers the correct logic whether that’s serving a webpage, processing form data, or querying a database.

    Routing allows you to organize your application into logical segments: for example, handling user-related routes like /users separately from product-related ones like /products. In raw Node.js, you’d use conditionals to match paths and methods manually.

    EXAMPLE-

    const express = require(‘express’);
    const app = express();

    app.get(‘/home’, (req, res) => {
    res.send(‘Welcome to the homepage’);
    });

    app.post(‘/login’, (req, res) => {
    // process login data
    });

    TYPES OF ROUTING-

    1. Static Routing– Static routes refer to fixed URL paths that always invoke the same logic. These are explicitly defined and typically used for rendering static pages or responding to endpoints that don’t vary by user or input.

    • Example- /about, /contact, /home
    • Best suited for public information pages or simple request handlers.

    EXAMPLE CODE-

    app.get(‘/about’, (req, res) => res.send(‘About Page’));

    2. Dynamic Routing– Dynamic routes contain parameters or segments that vary based on user input, enabling more flexible interactions with resources.

    • Example: /user/:id, /post/:slug
    • Useful for user profiles, product details, etc., where the route depends on context.

    EXAMPLE CODE-

    app.get(‘/user/:id’, (req, res) => {
    const userId = req.params.id;
    res.send(User ID: ${userId});
    });

    3. Nested Routing– Nested routing organizes endpoints hierarchically, improving modularity in large applications. Each module or sub-router handles related sub-paths.

    • Example: /admin/users, /admin/products
    • Ideal for grouping functionalities like admin panels, user dashboards, etc.

    EXAMPLE CODE-

    const userRouter = express.Router();
    userRouter.get(‘/profile’, …);
    app.use(‘/admin’, userRouter);

    4. RESTful Routing– Follows REST principles where each HTTP method represents a CRUD operation on a resource.

    • Example Routes:
      • GET /posts– fetch all posts
      • POST /posts– create a new post
      • PUT /posts/:id– update a post
      • DELETE /posts/:id– remove a post
    • Promotes clear, standardized API design.

    5. Middleware-Based Routing– Middleware functions intercept requests to perform operations before reaching the route handler like authentication, validation, or logging. Enhances reusability and separation of concerns.

    EXAMPLE CODE-

    app.use(‘/secure’, authMiddleware, secureRoutes);

    6. Method-Specific Routing– Different route handlers are defined for the same URL path but with distinct HTTP methods. This provides a clean way to distinguish between fetch (GET), create (POST), update (PUT), and delete (DELETE) operations.

    EXAMPLE CODE-

    app.get(‘/data’, (req, res) => { … });
    app.post(‘/data’, (req, res) => { … });

    MANUAL ROUTING WITH CONDITIONAL STATEMENT

    Using conditional statements, without relying on frameworks like Express. This approach uses the built-in http module to check both the request URL and HTTP method, then directs the request to the appropriate handler accordingly.

    EXAMPLE CODE-

    const http = require(‘http’);

    const server = http.createServer((req, res) => {
    const { url, method } = req;

    // Set common response headers
    res.setHeader(‘Content-Type’, ‘text/plain’);

    if (url === ‘/’ && method === ‘GET’) {
    res.statusCode = 200;
    res.end(‘Welcome to the homepage’);
    }

    else if (url === ‘/about’ && method === ‘GET’) {
    res.statusCode = 200;
    res.end(‘About us section’);
    }

    else if (url === ‘/contact’ && method === ‘POST’) {
    res.statusCode = 200;
    res.end(‘Contact form submitted’);
    }

    else {
    res.statusCode = 404;
    res.end(‘404 Not Found’);
    }
    });

    server.listen(3000, () => {
    console.log(‘Server running on http://localhost:3000’);
    });

    Share the Post:

    Entry Level Jobs