Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Express middleware: app.param vs app.use

In the chain of calls inside Express middleware, do the app.param methods always get called before app.use?

like image 871
Alexander Mills Avatar asked Nov 21 '14 03:11

Alexander Mills


People also ask

What is the difference between app use and app get in express JS?

app. get is called when the HTTP method is set to GET , whereas app. use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.

What is app use () in Express?

The app. use() method mounts or puts the specified middleware functions at the specified path. This middleware function will be executed only when the base of the requested path matches the defined path.

What is app Param in Express?

The app. param() method is basically used for adding the callback triggers to the route parameters, where name represents the name of the parameter or an array of them and callback represents the callback function.

How many parameters you should pass in the middleware function?

Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function.


1 Answers

I tested with this program changing the order of app.use vs app.param with express 4.10.2. The param always runs first, which makes sense because the route handler expects to be able to do req.params.foo and in order for that to work the param handlers need to have run.

var express = require('express');
var app = express();

app.use("/:file", function (req, res) {
  console.log("@bug route", req.params.file);
  res.send();
});

app.param("file", function (req, res, next, val) {
  console.log("@bug param", val);
  next();
});



app.listen(3003);

Run this and test with curl localhost:3003/foo and you get the output:

@bug param foo
@bug route foo
like image 78
Peter Lyons Avatar answered Oct 04 '22 11:10

Peter Lyons