![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements