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
Provenance
- Commit
dd4ddae- Tree
a28b5dd- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
4983e96
1 file changed+67 added−0 removed
modified:docs/guide.md+67 added
172 unmodified lines173 ### Route Middleware174 175 Routes 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.176 177+Typically async data retrieval might look similar to below, where we take the ":id" parameter, and attempt loading a user. 178+179+ 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+ });185+186+To 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. 187+188+ 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+ }198+199+ app.get('/user/:id', loadUser, function(req, res){200+ res.send('Viewing user ' + req.user.name);201+ });202+203+Multiple 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.204+205+ 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+ });214+215+Keeping 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.216+217+ function andRestrictTo(role) {218+ return function(req, res, next) {219+ req.authenticatedUser.role == role220+ ? next()221+ : next(new Error('Unauthorized'));222+ }223+ }224+225+ app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){226+ res.send('Deleted user ' + req.user.name);227+ });228+229+Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.230+231+ var a = [middleware1, middleware2]232+ , b = [middleware3, middleware4]233+ , all = [a, b];234+235+ app.get('/foo', a, function(){});236+ app.get('/bar', a, function(){});237+238+ app.get('/', a, middleware3, middleware4, function(){});239+ app.get('/', a, b, function(){});240+ app.get('/', all, function(){});241+242+For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.243+244 ### HTTP Methods245 246 We 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