Skip to content
Related Articles

Related Articles

Express.js router.param() function
  • Last Updated : 16 Jul, 2020
GeeksforGeeks - Summer Carnival Banner

The parameters of router.param() are name and a function. Where name is the actual name of parameter and function is the callback function. Basically router.param() function triggers the callback function whenever user routes to the parameter. This callback function will be called for only single time in request response cycle, even if user routes to the parameter multiple times.

Syntax:

router.param(name, function)

Parameters of callback function are: 

  1. req – the request object
  2. res – the response object
  3. next – the next middleware function
  4. id – the value of name parameter

First you need to install express node module into your node js application.

Installations of express js is as follows:



npm init 
npm install express 

Create a file names app.js and paste the following code in the file.




//
const express = require("express");
const app = express();
  
//import router module from route.js file
const userRoutes = require("./route");
  
app.use("/", userRoutes);
  
//PORT
const port = process.env.PORT || 8000;
  
//Starting a server
app.listen(port, () => {
  console.log(`app is running at ${port}`);
});

We have to create another file named route.js in the same directory

Code for route.js file




const express = require("express");
const router = express.Router();
  
router.param("userId", (req, res, next, id) => {
    console.log("This function will be called first");
    next();
});
  
router.get("/user/:userId", (req, res) => {
    console.log("Then this function will be called");
    res.end();
});
// Export router 
module.exports = router;

Start the server by entering the following command

node app.js

Enter the following address into the browser

http://localhost:8000/user/343

You will see the following output in your terminal

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :