Saturday, 2 March 2019

Express: app.param([name], callback): Add callbacks to the route parameters


app.param([name], callback)
We can add callback triggers to the route parameters. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order.

index.js
var express = require('express')

var app = express()

app.param('userId', function (req, res, next, id, routeParamName) {
  console.log('Called for route parameter ' + routeParamName + ' and the value for ' + routeParamName + " is " + id);
  next();
});

app.get('/users/:userId/movieTickets/:bookingId', function (req, res) {
  res.send(req.params);
});


var listener = app.listen(3000, () => {console.log('Application started on port ' + listener.address().port);});


Run index.js and hit the url ‘http://localhost:3000/users/krishna123/movieTickets/booking789’.



You can see below message in console.
Called for route parameter userId and the value for userId is krishna123

You can even register multiple route parameters to same callback function.

app.param(['userId', 'bookingId'], function (req, res, next, id, routeParamName) {
  console.log('Called for route parameter ' + routeParamName + ' and the value for ' + routeParamName + " is " + id);
  next();
});

Above snippet registers the callback for the routing parameters userId, bookingId. The callbacks will trigger for the route parameters in the order they declared in the array/

index.js
var express = require('express')

var app = express()

app.param(['userId', 'bookingId'], function (req, res, next, id, routeParamName) {
  console.log('Called for route parameter ' + routeParamName + ' and the value for ' + routeParamName + " is " + id);
  next();
});

app.get('/users/:userId/movieTickets/:bookingId', function (req, res) {
  res.send(req.params);
});


var listener = app.listen(3000, () => {console.log('Application started on port ' + listener.address().port);});

Run index.js and open browser and hit the url ‘http://localhost:3000/users/krishna123/movieTickets/booking789’, you can see below messages in the console.

Called for route parameter userId and the value for userId is krishna123

Called for route parameter bookingId and the value for bookingId is booking789



Previous                                                 Next                                                 Home

No comments:

Post a Comment