Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express app.get documentation

Tags:

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.

like image 598
ThomasReggi Avatar asked Oct 04 '12 00:10

ThomasReggi


1 Answers

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.

like image 70
JohnnyHK Avatar answered Jan 30 '23 03:01

JohnnyHK