Open In App

Express.js | app.param() Function

Last Updated : 20 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The app.param() function is used to add the callback triggers to route parameters. It is commonly used to check for the existence of the data requested related to the route parameter. 

Syntax:

app.param([name], callback)

Parameters:

  • name: It is the name of the parameter or an array of them.
  • callback: It is a function that is passed as a parameter.

Installation of the express module:

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:

Filename: index.js 

javascript




const express = require('express');
const app = express();
const PORT = 3000;
 
app.param('id', function (req, res, next, id) {
    console.log('CALLED ONLY ONCE');
    next();
});
 
app.get('/user/:id', function (req, res, next) {
    console.log('Greetings from geeksforgeeks');
    next();
});
 
app.get('/user/:id', function (req, res) {
    console.log('Once again greetings from geeksforgeeks');
    res.end();
});
 
app.listen(PORT, function (err) {
    if (err) console.log("Error in server setup");
    console.log("Server listening on Port", PORT);
});


Steps to run the program:

Make sure you have installed the express module using the following command:

npm install express

Run the index.js file using the below command:

node index.js

Output:

Console Output:

Server listening on Port 3000

Browser Output:

Open the browser and go to http://localhost:3000/user/42. Now check your console, following will be the output:

Server listening on Port 3000
CALLED ONLY ONCE
Greetings from geeksforgeeks
Once again greetings from geeksforgeeks

So this is how you can use the express app.param() function to add callback triggers to route parameters.


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

Similar Reads