Skip to content
Related Articles

Related Articles

Improve Article

Express.js | app.param() Function

  • Last Updated : 18 Jun, 2020

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:

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

Installation of express module:

  1. You can visit the link to Install express module. You can install this package by using this command.
    npm install express
  2. After installing the express module, you can check your express version in command prompt using the command.
    npm version express
  3. 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

Filename: index.js






var express = require('express');
var app = express();
var 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:

  1. The project structure will look like this:
  2. Make sure you have installed express module using the following command:
    npm install express
  3. Run index.js file using below command:
    node index.js

    Output:

    Server listening on Port 3000
    
  4. Open 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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :