Skip to content
Myr

Added route middleware docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent 4983e96 · Browse files · 1 file+67 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+67 added−0 removed

  • other:+67 added−0 removed

1 file+67 added−0 removed

modified:docs/guide.md+67 added
172 unmodified lines
173### Route Middleware174175Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.176177Typically async data retrieval might look similar to below, where we take the ":id" parameter, and attempt loading a user. 178179 app.get('/user/:id', function(req, res, next){180 loadUser(req.params.id, function(err, user){181 if (err) return next(err);182 res.send('Viewing user ' + user.name);183 });184 });185186To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time. 187188 function loadUser(req, res, next) {189 // You would fetch your user from the db190 var user = users[req.params.id];191 if (user) {192 req.user = user;193 next();194 } else {195 next(new Error('Failed to load user ' + req.params.id));196 }197 }198199 app.get('/user/:id', loadUser, function(req, res){200 res.send('Viewing user ' + req.user.name);201 });202203Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.204205 function andRestrictToSelf(req, res, next) {206 req.authenticatedUser.id == req.user.id207 ? next()208 : next(new Error('Unauthorized'));209 }210 211 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){212 res.send('Editing user ' + req.user.name);213 });214215Keeping in mind that middleware are simply functions, we can define function that _returns_ the middleware in order to create a more expressive and flexible solution as shown below.216217 function andRestrictTo(role) {218 return function(req, res, next) {219 req.authenticatedUser.role == role220 ? next()221 : next(new Error('Unauthorized'));222 }223 }224225 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){226 res.send('Deleted user ' + req.user.name);227 });228229Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.230231 var a = [middleware1, middleware2]232 , b = [middleware3, middleware4]233 , all = [a, b];234235 app.get('/foo', a, function(){});236 app.get('/bar', a, function(){});237238 app.get('/', a, middleware3, middleware4, function(){});239 app.get('/', a, b, function(){});240 app.get('/', all, function(){});241242For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.243244### HTTP Methods245246We have seen _app.get()_ a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as _app.post()_, _app.del()_, etc.247
666 unmodified lines