21

I am looking for some documentation on the app.get function of express.js.

app.get(
    '/path', 
    middleware(),
    function(req, res) {
        res.redirect('/');
    }
);

The example above takes three parameters. The normal docs only show two. I'm interested in what this middle param does and how to use it.

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

1 Answers1

26

The docs for that are part of the app.METHOD documentation, where get is one of the supported HTTP methods.

The second, optional parameter, is called middleware (and you can pass an array of middleware functions). This is a function that's called before the third parameter callback (the actual route handler) and the responsibility of a middleware function is to allow your code to follow the DRY (don't repeat yourself) principle.

Example of middleware functions are permissions checks, access validations, validation of sessions (if user is not in logged in, take him to a log in page), and such.

Since several routes might desire the same behavior, you use a middleware so that you don't have to write the same code several times.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • I want to make some middleware functions but I really can't find the doc's on how they work and what params they take. I found one example code that has a function that takes `req, res, next` as arguments but I'm not sure how to use it. – ThomasReggi Oct 04 '12 at 03:54
  • 1
    The middleware functions here always take those three parameters: the `request` object, the `response` object, and the `next` callback to call when the middleware is complete. Pass `next` an Error object on error, or no parameters to pass control to the next callback. – JohnnyHK Oct 04 '12 at 04:02
  • Do you know of an example of middleware of another method, that node / express uses to delegate params under a path. For example route `/login?age=23` from `/login?name=thomas`? I could really use an example of this. I know I could just use a conditional if `req.query.age` and `req.query.name` based on if they are `undefined` or not, but this doesn't seam really sophisticated. Is middleware the solution? – ThomasReggi Oct 04 '12 at 17:52