Skip to content
Myr

Added route-middleware example

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 0b5e2f1 · Browse files · 2 files+91 added−1 removed
This commit

State

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

Diff stats

2 files+91 added−1 removed

  • other:+91 added−1 removed

2 files+91 added−1 removed

modified:docs/guide.md+5 added-1 removed
153 unmodified lines
154### Passing Route Control155156We may pass control to the next _matching_ route, by calling the _third_ argument,157the _next()_ function. When a match cannot be made, control is passed back to Connect,158and middleware continue to be invoked.158and middleware continue to be invoked. The same is true for several routes which have the same path defined, they will simply be executed in order until one does _not_ call _next()_.159160 app.get('/users/:id?', function(req, res, next){161 var id = req.params.id;162 if (id) {
6 unmodified lines
169 app.get('/users', function(req, res){170 // do something else171 });172173### 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.176177### HTTP Methods178179We 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.180
666 unmodified lines
added:examples/route-middleware/app.js+86 added
12/**3 * Module dependencies.4 */56var express = require('../../lib/express');78var app = express.createServer();910// Example requests:11// curl http://localhost:3000/user/012// curl http://localhost:3000/user/0/edit13// curl http://localhost:3000/user/114// curl http://localhost:3000/user/1/edit (unauthorized since this is not you)15// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin)1617// Dummy users18var users = [19 { id: 0, name: 'tj', email: 'tj@vision-media.ca', role: 'member' },20 { id: 1, name: 'ciaran', email: 'ciaranj@gmail.com', role: 'member' },21 { id: 2, name: 'aaron', email: 'aaron.heckmann+github@gmail.com', role: 'admin' }22];2324function loadUser(req, res, next) {25 // You would fetch your user from the db26 var user = users[req.params.id];27 if (user) {28 req.user = user;29 next();30 } else {31 next(new Error('Failed to load user ' + req.params.id));32 }33}3435function andRestrictToSelf(req, res, next) {36 // If our authenticated user is the user we are viewing37 // then everything is fine :)38 if (req.authenticatedUser.id == req.user.id) {39 next();40 } else {41 // You may want to implement specific exceptions42 // such as UnauthorizedError or similar so that you43 // can handle these in app.error() specifically44 // (view ./examples/pages for this)45 next(new Error('Unauthorized'));46 }47}4849function andRestrictTo(role) {50 return function(req, res, next) {51 if (req.authenticatedUser.role == role) {52 next();53 } else {54 next(new Error('Unauthorized'));55 }56 }57}5859// Middleware for faux authentication60// you would of course implement something real,61// but this illustrates how an authenticated user62// may interacte with middleware6364app.use(function(req, res, next){65 req.authenticatedUser = users[0];66 next();67});6869app.get('/', function(req, res){70 res.redirect('/user/0');71});7273app.get('/user/:id', loadUser, function(req, res){74 res.send('Viewing user ' + req.user.name);75});7677app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){78 res.send('Editing user ' + req.user.name);79});8081app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){82 res.send('Deleted user ' + req.user.name);83});8485app.listen(3000);86console.log('Express app started on port 3000');