Express.js – router.param() Method


router.param(name, callback) adds a callback to the route parameters where name defines the name of the parameter and callback is the callback function.

Following are the parameters of the callback function −

  • req – the request object

  • res – the response object

  • next -- the next middleware

  • name – value of the name parameter

Syntax

router.param( name, callback )

Example

Create a file with the name "routerParam.js" and copy the following code snippet. After creating the file, use the command "node routerParam.js" to run this code as shown in the example below −

// router.param() Method Demo Example

// Importing the express module
var express = require('express');

// Importing the route module
const userRoutes = require("./router");

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Defining the route
app.use("/", userRoutes);

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

router.js

// Importing the express module
const express = require("express");
const router = express.Router();

// Defining the router param with its value
router.param("userId", (req, res, next, id) => {
   console.log("I am called first");
   next();
});

router.get("/user/:userId", (req, res) => {
   console.log("I am called next");
   res.end();
});

// Export router as a module
module.exports = router;

Hit the following Endpoint with a GET request −

http://localhost:3000/user/21

Output

C:\home
ode>> node routerParam.js Server listening on PORT 3000 I am called first I am called next

Updated on: 28-Mar-2022

921 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements