Open In App

How to dynamically call router function in Node.js ?

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Node.js provides a powerful routing system through the Express framework. One of the features of this routing system is the ability to dynamically call router functions based on incoming requests.

Dynamically calling a router function means that the function is selected at runtime based on the request parameters, instead of being explicitly defined in the code. This can be useful when you want to handle a large number of similar requests without having to define a separate function for each one.

In Express, you can use the app.METHOD() function to dynamically call a router function, where METHOD is the HTTP method of the request (e.g. GET, POST, PUT, DELETE, etc.). This allows you to handle requests dynamically without explicitly creating a router object.

 

Syntax:

app.METHOD(path, [callback1], [callback2], ...)

where METHOD is the HTTP method of the request, path is the path for the route, and callback is the function that will handle the request.

Installation: You can visit the link to Install the express module. You can install this package by using this command.

npm install express

After installing the express module, you can check your express version in the command prompt using the command.

npm version express

After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.

node index.js

Project Structure:

 

Here’s an example of dynamically calling router functions in Node.js:

Example 1: Filename: index.js 

In this example, we define object routes that contain different paths and their corresponding handler functions. We use a for…in loop to iterate over the routes object and dynamically call the corresponding function for each path using the app.get() method. 

Javascript




const express = require('express');
const app = express();
const PORT = 3000;
  
// Define routes as key-value pairs
const routes = {
    '/users/:id': function (req, res) {
        const { id } = req.params;
        res.send(`User ID is ${id}`);
    },
    '/products/:id': function (req, res) {
        const { id } = req.params;
        res.send(`Product ID is ${id}`);
    }
};
  
// Loop through the routes and register
// them with Express
for (let route in routes) {
    app.get(route, routes[route]);
}
  
// Start the server
app.listen(PORT, function (err) {
    if (err) console.log(err);
    console.log(`Server listening on PORT ${PORT}`);
});


Steps to run the program: Run the index.js file using the below command:

node index.js

Console Output:

Server listening on PORT 3000

Browser Output: Now, open your web browser and navigate to http://localhost:3000/users/123. You should see the following output:

User ID is 123

If you navigate to http://localhost:3000/products/456. You should see the following output:

Product ID is 456

Example 2: Filename: index.js 

Let’s say we have an e-commerce website and we want to dynamically route to different product categories and products based on the user’s request.

We can create a new router object and define routes for each product category and product.

Javascript




const express = require("express");
const app = express();
const PORT = 3000;
  
// Define product category routes
app.get("/electronics", function (req, res) {
    res.send("This is the electronics category");
});
  
app.get("/books", function (req, res) {
    res.send("This is the books category");
});
  
app.get("/clothing", function (req, res) {
    res.send("This is the clothing category");
});
  
// Define product routes
app.get("/electronics/:productId", function (req, res) {
    const { productId } = req.params;
    res.send(`This is the product page 
        for electronics product ${productId}`);
});
  
app.get("/books/:productId", function (req, res) {
    const { productId } = req.params;
    res.send(`This is the product page for book ${productId}`);
});
  
app.get("/clothing/:productId", function (req, res) {
    const { productId } = req.params;
    res.send(`This is the product page 
        for clothing product ${productId}`);
});
  
// Dynamically call router functions
app.use("/:category/:productId", function (req, res, next) {
    const { category, productId } = req.params;
  
    if (
        app._router.stack.some(
            (r) => r.route && r.route.path 
                === `/${category}/:productId`
        )
    ) {
        app(req, res, next);
    } else {
        next();
    }
});
  
app.listen(PORT, function (err) {
    if (err) console.log(err);
    console.log(`Server listening on PORT ${PORT}`);
});


Steps to run the program: Run the index.js file using the below command:

node index.js

Console Output:

Server listening on PORT 3000

Browser Output:

Now open your web browser and go to http://localhost:3000/electronics/123. You should see the following output:

This is the product page for electronics product 123

Similarly, you can test the other routes by changing the URL to http://localhost:3000/books/456 or http://localhost:3000/clothing/789. You should see the appropriate output based on the category and product ID specified in the URL.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads