Skip to content
Myr

guide.md

This file

Path

docs/guide.md

68 lines · 1.6 KiB · Markdown

Last changed by

Route passing docsTj Holowaychukbefore adoption0ace97c

History of this file

Take it

Started guideTj Holowaychukbefore adoption9e3a0c6

lines 1–5why, one step back
1
2### Routing34Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.5For example we may want to render a user's account for the path _/user/12_, this

Route passing docsTj Holowaychukbefore adoption0ace97c

lines 6–7why, one step back
6can be done by defining the route below. The values associated to the named placeholders,
7are passed as the _third_ argument, which here we name _params_.

Started guideTj Holowaychukbefore adoption9e3a0c6

lines 8–51why, one step back
8
9 app.get('/user/:id', function(req, res, params){10 res.send('user ' + params.id);11 });1213A route is simple a string which is compiled to a _RegExp_ internally. For example14when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:1516 \/user\/([^\/]+)\/?1718Literal regular expressions may also be passed for complex uses:1920 app.get(/^\/foo(bar)?$/, function(){});2122Below are some route examples, and the associated paths that they23may consume:2425 "/user/:id"26 /user/122728 "/users/:id?"29 /users/530 /users3132 "/files/*"33 /files/jquery.js34 /files/javascripts/jquery.js3536 "/file/*.*"37 /files/jquery.js38 /files/javascripts/jquery.js39 40 "/user/:id/:operation?"41 /user/142 /user/1/edit43 44 "/products.:format"45 /products.json46 /products.xml4748 "/products.:format?"49 /products.json50 /products.xml51 /products

Route passing docsTj Holowaychukbefore adoption0ace97c

lines 52–68why, one step back
52
53### Passing Route Control5455We may pass control to the next _matching_ route, by calling the _fourth_ parameter,56the _next()_ function. When a match cannot be made, control is passed back to Connect.5758 app.get('/users/:id?', function(req, res, params){59 if (params.id) {60 // do something61 } else {62 next();63 }64 });65 66 app.get('/users', function(req, res, params){67 // do something else68 });