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
Provenance
- Commit
4983e96- Tree
31096d5- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
0b5e2f1
2 files changed+91 added−1 removed
modified:docs/guide.md+5 added-1 removed
153 unmodified lines154 ### Passing Route Control155 156 We may pass control to the next _matching_ route, by calling the _third_ argument,157 the _next()_ function. When a match cannot be made, control is passed back to Connect,158-and middleware continue to be invoked.158+and 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()_.159 160 app.get('/users/:id?', function(req, res, next){161 var id = req.params.id;162 if (id) {6 unmodified lines169 app.get('/users', function(req, res){170 // do something else171 });172 173+### 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 ### HTTP Methods178 179 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.180 666 unmodified linesadded:examples/route-middleware/app.js+86 added
1+2+/**3+ * Module dependencies.4+ */5+6+var express = require('../../lib/express');7+8+var app = express.createServer();9+10+// 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)16+17+// Dummy users18+var 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+];23+24+function 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+}34+35+function 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+}48+49+function 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+}58+59+// Middleware for faux authentication60+// you would of course implement something real,61+// but this illustrates how an authenticated user62+// may interacte with middleware63+64+app.use(function(req, res, next){65+ req.authenticatedUser = users[0];66+ next();67+});68+69+app.get('/', function(req, res){70+ res.redirect('/user/0');71+});72+73+app.get('/user/:id', loadUser, function(req, res){74+ res.send('Viewing user ' + req.user.name);75+});76+77+app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){78+ res.send('Editing user ' + req.user.name);79+});80+81+app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){82+ res.send('Deleted user ' + req.user.name);83+});84+85+app.listen(3000);86+console.log('Express app started on port 3000');