guide.1
This file
Path
docs/guide.1
1,659 lines · 34.7 KiB
Last changed by
Regenerated docsTj Holowaychukbefore adoption2a40cec
History of this fileTake it
The walk stopped after 200 commits: lines older than 75661a2 point at it.
Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1–2why, one step back1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.3Route callback signature changedTj Holowaychukbefore adoption75661a2
line 3why, one step back3.HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
line 4why, one step back4.TH "GUIDE" "" "October 2010" "" ""Route callback signature changedTj Holowaychukbefore adoption75661a2
line 5why, one step back5.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 6–8why, one step back6.SH "NAME"7\fBguide\fR8.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 9–79why, one step back9.SS "Installation"10curl:11.12.IP "" 413.14.nf1516$ curl \-# http://expressjs\.com/install\.sh | sh17.18.fi19.20.IP "" 021.22.P23npm:24.25.IP "" 426.27.nf2829$ npm install express30.31.fi32.33.IP "" 034.35.P36git clone, first update the submodules:37.38.IP "" 439.40.nf4142$ git submodule update \-\-init43$ make install44$ make install\-support45.46.fi47.48.IP "" 049.50.SS "Creating An Application"51The \fIexpress\.Server\fR now inherits from \fIhttp\.Server\fR, however follows the same idiom by providing \fIexpress\.createServer()\fR as shown below\. This means that you can utilize Express server\'s transparently with other libraries\.52.53.IP "" 454.55.nf5657var app = require(\'express\')\.createServer();5859app\.get(\'/\', function(req, res){60 res\.send(\'hello world\');61});6263app\.listen(3000);64.65.fi66.67.IP "" 068.69.SS "Configuration"70Express supports arbitrary environments, such as \fIproduction\fR and \fIdevelopment\fR\. Developers can use the \fIconfigure()\fR method to setup needs required by the current environment\. When \fIconfigure()\fR is called without an environment name it will be run in \fIevery\fR environment prior to the environment specific callback\.71.72.P73In the example below we only \fIdumpExceptions\fR, and respond with exception stack traces in \fIdevelopment\fR mode, however for both environments we utilize \fImethodOverride\fR and \fIbodyDecoder\fR\. Note the use of \fIapp\.router\fR, which can (optionally) be used to mount the application routes, otherwise the first call to \fIapp\.{get,put,del,post}()\fR will mount the routes\.74.75.IP "" 476.77.nf7879app\.configure(function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 80–81why, one step back80 app\.use(express\.methodOverride());81 app\.use(express\.bodyDecoder());Route callback signature changedTj Holowaychukbefore adoption75661a2
line 82why, one step back82 app\.use(app\.router);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 83why, one step back83 app\.use(express\.staticProvider(__dirname + \'/public\'));Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 84–86why, one step back84});8586app\.configure(\'development\', function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 87why, one step back87 app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 88–90why, one step back88});8990app\.configure(\'production\', function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 91why, one step back91 app\.use(express\.errorHandler());Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 92–107why, one step back92});93.94.fi95.96.IP "" 097.98.P99For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:100.101.IP "" 4102.103.nf104105app\.configure(function(){106 app\.set(\'views\', __dirname + \'/views\');107 app\.set(\'views\');Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 108why, one step back108 // => "\.\.\. views directory \.\.\."Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 109–121why, one step back109110 app\.enable(\'some feature\');111 // same as app\.set(\'some feature\', true);112113 app\.disable(\'some feature\');114 // same as app\.set(\'some feature\', false);115});116.117.fi118.119.IP "" 0120.121.PRebuilt docsTj Holowaychukbefore adoption2724ce3
line 122why, one step back122To alter the environment we can set the \fINODE_ENV\fR environment variable, for example:Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 123–127why, one step back123.124.IP "" 4125.126.nf127Rebuilt docsTj Holowaychukbefore adoption2724ce3
line 128why, one step back128$ NODE_ENV=production node app\.jsRoute callback signature changedTj Holowaychukbefore adoption75661a2
lines 129–133why, one step back129.130.fi131.132.IP "" 0133.Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 134–136why, one step back134.P135This is \fIvery\fR important, as many caching mechanisms are \fIonly enabled\fR when in production\.136.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 137–151why, one step back137.SS "Settings"138Express supports the following settings out of the box:139.140.IP "\(bu" 4141\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR142.143.IP "\(bu" 4144\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.145.146.IP "\(bu" 4147\fIviews\fR Root views directory defaulting to \fBCWD/views\fR148.149.IP "\(bu" 4150\fIview engine\fR Default view engine name for views rendered without extensions151.Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 152–157why, one step back152.IP "\(bu" 4153\fIview options\fR An object specifying global view options154.155.IP "\(bu" 4156\fIpartials\fR Root view partials directory defaulting to \fIviews\fR/partials\.157.Updated docsTj Holowaychukbefore adoptionf0eab06
lines 158–160why, one step back158.IP "\(bu" 4159\fIstream threshold\fR Bytesize indicating when a file should be streamed for \fIres\.sendfile()\fR using \fIfs\.ReadStream()\fR and \fIsys\.pump()\fR\.160.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 161–163why, one step back161.IP "" 0162.163.SS "Routing"Updated docsTj Holowaychukbefore adoptiond691ecb
line 164why, one step back164Express utilizes the HTTP verbs to provide a meaningful, expressive routing API\. For example we may want to render a user\'s account for the path \fI/user/12\fR, this can be done by defining the route below\. The values associated to the named placeholders are available as \fBreq\.params\fR\.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 165–169why, one step back165.166.IP "" 4167.168.nf169Updated docsTj Holowaychukbefore adoptiond691ecb
lines 170–171why, one step back170app\.get(\'/user/:id\', function(req, res){171 res\.send(\'user \' + req\.params\.id);Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 172–184why, one step back172});173.174.fi175.176.IP "" 0177.178.P179A route is simple a string which is compiled to a \fIRegExp\fR internally\. For example when \fI/user/:id\fR is compiled, a simplified version of the regexp may look similar to:180.181.IP "" 4182.183.nf184Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 185why, one step back185\e/user\e/([^\e/]+)\e/?Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 186–191why, one step back186.187.fi188.189.IP "" 0190.191.PUpdated docsTj Holowaychukbefore adoptiond691ecb
line 192why, one step back192Regular expression literals may also be passed for complex uses\. Since capture groups with literal \fIRegExp\fR\'s are anonymous we can access them directly \fBreq\.params\fR\.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 193–197why, one step back193.194.IP "" 4195.196.nf197Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 198why, one step back198app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){Updated docsTj Holowaychukbefore adoptiond691ecb
line 199why, one step back199 res\.send(req\.params);Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 200–217why, one step back200});201.202.fi203.204.IP "" 0205.206.P207Curl requests against the previously defined route:208.209.IP "" 4210.211.nf212213 $ curl http://dev:3000/user214 [null,null]215 $ curl http://dev:3000/users216 [null,null]217 $ curl http://dev:3000/users/1Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 218why, one step back218 ["1",null]Route callback signature changedTj Holowaychukbefore adoption75661a2
line 219why, one step back219 $ curl http://dev:3000/users/1\.\.15Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 220why, one step back220 ["1","15"]Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 221–232why, one step back221.222.fi223.224.IP "" 0225.226.P227Below are some route examples, and the associated paths that they may consume:228.229.IP "" 4230.231.nf232Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 233why, one step back233 "/user/:id"Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 234–235why, one step back234 /user/12235Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 236why, one step back236 "/users/:id?"Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 237–239why, one step back237 /users/5238 /users239Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 240why, one step back240 "/files/*"Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 241–243why, one step back241 /files/jquery\.js242 /files/javascripts/jquery\.js243Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 244why, one step back244 "/file/*\.*"Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 245–247why, one step back245 /files/jquery\.js246 /files/javascripts/jquery\.js247Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 248why, one step back248 "/user/:id/:operation?"Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 249–251why, one step back249 /user/1250 /user/1/edit251Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 252why, one step back252 "/products\.:format"Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 253–255why, one step back253 /products\.json254 /products\.xml255Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 256why, one step back256 "/products\.:format?"Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 257–265why, one step back257 /products\.json258 /products\.xml259 /products260.261.fi262.263.IP "" 0264.265.SS "Passing Route Control"Regenerated docsTj Holowaychukbefore adoption334a18a
line 266why, one step back266We may pass control to the next \fImatching\fR route, by calling the \fIthird\fR argument, the \fInext()\fR function\. When a match cannot be made, control is passed back to Connect, 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 \fInot\fR call \fInext()\fR\.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 267–271why, one step back267.268.IP "" 4269.270.nf271Updated docsTj Holowaychukbefore adoptionb819366
line 272why, one step back272app\.get(\'/users/:id?\', function(req, res, next){Updated docsTj Holowaychukbefore adoptiond691ecb
lines 273–274why, one step back273 var id = req\.params\.id;274 if (id) {Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 275–280why, one step back275 // do something276 } else {277 next();278 }279});280Updated docsTj Holowaychukbefore adoptiond691ecb
line 281why, one step back281app\.get(\'/users\', function(req, res){Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 282–287why, one step back282 // do something else283});284.285.fi286.287.IP "" 0Regenerated docsTj Holowaychukbefore adoption334a18a
line 288why, one step back288.Regenerated docsTj Holowaychukbefore adoption090debe
lines 289–346why, one step back289.SS "Middleware"290Middleware via Connect \fIhttp://github\.com/senchalabs/connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:291.292.IP "" 4293.294.nf295296 var express = require(\'express\');297298var app = express\.createServer(299 express\.logger(),300 express\.bodyDecoder()301 );302.303.fi304.305.IP "" 0306.307.P308Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:309.310.IP "" 4311.312.nf313314app\.use(express\.logger({ format: \':method :uri\' }));315.316.fi317.318.IP "" 0319.320.P321Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:322.323.IP "" 4324.325.nf326327var connect = require(\'connect\');328app\.use(connect\.logger());329.330.fi331.332.IP "" 0333.334.P335This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:336.337.IP "" 4338.339.nf340341app\.use(express\.logger());342.343.fi344.345.IP "" 0346.Regenerated docsTj Holowaychukbefore adoption334a18a
lines 347–350why, one step back347.SS "Route Middleware"348Routes 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\.349.350.PRegenerated docsTj Holowaychukbefore adoption0faac20
line 351why, one step back351Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.Regenerated docsTj Holowaychukbefore adoption334a18a
lines 352–356why, one step back352.353.IP "" 4354.355.nf356Regenerated docsTj Holowaychukbefore adoption0faac20
lines 357–358why, one step back357app\.get(\'/user/:id\', function(req, res, next){358 loadUser(req\.params\.id, function(err, user){Regenerated guideTj Holowaychukbefore adoptionab3337d
lines 359–360why, one step back359 if (err) return next(err);360 res\.send(\'Viewing user \' + user\.name);Regenerated docsTj Holowaychukbefore adoption0faac20
lines 361–362why, one step back361 });362});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 363–374why, one step back363.364.fi365.366.IP "" 0367.368.P369To 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\.370.371.IP "" 4372.373.nf374Regenerated docsTj Holowaychukbefore adoption0faac20
lines 375–383why, one step back375function loadUser(req, res, next) {376 // You would fetch your user from the db377 var user = users[req\.params\.id];378 if (user) {379 req\.user = user;380 next();381 } else {382 next(new Error(\'Failed to load user \' + req\.params\.id));383 }Regenerated docsTj Holowaychukbefore adoption334a18a
line 384why, one step back384}Regenerated docsTj Holowaychukbefore adoption0faac20
line 385why, one step back385Regenerated docsTj Holowaychukbefore adoption334a18a
line 386why, one step back386app\.get(\'/user/:id\', loadUser, function(req, res){Regenerated docsTj Holowaychukbefore adoption0faac20
lines 387–388why, one step back387 res\.send(\'Viewing user \' + req\.user\.name);388});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 389–400why, one step back389.390.fi391.392.IP "" 0393.394.P395Multiple 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\.396.397.IP "" 4398.399.nf400Regenerated docsTj Holowaychukbefore adoption0faac20
lines 401–402why, one step back401function andRestrictToSelf(req, res, next) {402 req\.authenticatedUser\.id == req\.user\.idRegenerated guideTj Holowaychukbefore adoptionab3337d
lines 403–404why, one step back403 ? next()404 : next(new Error(\'Unauthorized\'));Regenerated docsTj Holowaychukbefore adoption334a18a
line 405why, one step back405}Regenerated docsTj Holowaychukbefore adoption0faac20
line 406why, one step back406Regenerated docsTj Holowaychukbefore adoption334a18a
line 407why, one step back407app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){Regenerated docsTj Holowaychukbefore adoption0faac20
lines 408–409why, one step back408 res\.send(\'Editing user \' + req\.user\.name);409});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 410–421why, one step back410.411.fi412.413.IP "" 0414.415.P416Keeping in mind that middleware are simply functions, we can define function that \fIreturns\fR the middleware in order to create a more expressive and flexible solution as shown below\.417.418.IP "" 4419.420.nf421Regenerated docsTj Holowaychukbefore adoption0faac20
lines 422–424why, one step back422function andRestrictTo(role) {423 return function(req, res, next) {424 req\.authenticatedUser\.role == roleRegenerated guideTj Holowaychukbefore adoptionab3337d
lines 425–426why, one step back425 ? next()426 : next(new Error(\'Unauthorized\'));Regenerated docsTj Holowaychukbefore adoption0faac20
line 427why, one step back427 }Regenerated docsTj Holowaychukbefore adoption334a18a
line 428why, one step back428}Regenerated docsTj Holowaychukbefore adoption0faac20
line 429why, one step back429Regenerated docsTj Holowaychukbefore adoption334a18a
line 430why, one step back430app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){Regenerated docsTj Holowaychukbefore adoption0faac20
lines 431–432why, one step back431 res\.send(\'Deleted user \' + req\.user\.name);432});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 433–444why, one step back433.434.fi435.436.IP "" 0437.438.P439Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.440.441.IP "" 4442.443.nf444Regenerated docsTj Holowaychukbefore adoption0faac20
lines 445–454why, one step back445var a = [middleware1, middleware2]446 , b = [middleware3, middleware4]447 , all = [a, b];448449app\.get(\'/foo\', a, function(){});450app\.get(\'/bar\', a, function(){});451452app\.get(\'/\', a, middleware3, middleware4, function(){});453app\.get(\'/\', a, b, function(){});454app\.get(\'/\', all, function(){});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 455–461why, one step back455.456.fi457.458.IP "" 0459.460.P461For this example in full, view the route middleware example \fIhttp://github\.com/visionmedia/express/blob/master/examples/route\-middleware/app\.js\fR in the repository\.Route callback signature changedTj Holowaychukbefore adoption75661a2
line 462why, one step back462.HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 463–472why, one step back463.SS "HTTP Methods"464We have seen \fIapp\.get()\fR a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as \fIapp\.post()\fR, \fIapp\.del()\fR, etc\.465.466.P467A common example for \fIPOST\fR usage, is when "submitting" a form\. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it\.468.469.IP "" 4470.471.nf472Regenerated guideTj Holowaychukbefore adoptionab3337d
lines 473–477why, one step back473 <form method="post" action="/">474 <input type="text" name="user[name]" />475 <input type="text" name="user[email]" />476 <input type="submit" value="Submit" />477 </form>HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 478–543why, one step back478.479.fi480.481.IP "" 0482.483.P484By default Express does not know what to do with this request body, so we should add the \fIbodyDecoder\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:485.486.IP "" 4487.488.nf489490app\.use(express\.bodyDecoder());491.492.fi493.494.IP "" 0495.496.P497Our route below will now have access to the \fIreq\.body\.user\fR object which will contain the \fIname\fR and \fIemail\fR properties when defined\.498.499.IP "" 4500.501.nf502503app\.post(\'/\', function(req, res){504 console\.log(req\.body\.user);505 res\.redirect(\'back\');506});507.508.fi509.510.IP "" 0511.512.P513When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyDecoder\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.514.515.IP "" 4516.517.nf518519app\.use(express\.bodyDecoder());520app\.use(express\.methodOverride());521.522.fi523.524.IP "" 0525.526.P527The reason that these are not always defaults, is simply because these are not required for Express to be fully functional\. Depending on the needs of your application, you may not need these at all, your methods such as \fIPUT\fR and \fIDELETE\fR can still be accessed by clients which can use them directly, although \fImethodOverride\fR provides a great solution for forms\. Below shows what the usage of \fIPUT\fR might look like:528.529.IP "" 4530.531.nf532533<form method="post" action="/">534 <input type="hidden" name="_method" value="put" />535 <input type="text" name="user[name]" />536 <input type="text" name="user[email]" />537 <input type="submit" value="Submit" />538</form>539540app\.put(\'/\', function(){541 console\.log(req\.body\.user);542 res\.redirect(\'back\');543});Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 544–548why, one step back544.545.fi546.547.IP "" 0548.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 549–578why, one step back549.SS "Error Handling"550Express provides the \fIapp\.error()\fR method which receives exceptions thrown within a route, or passed to \fInext(err)\fR\. Below is an example which serves different pages based on our ad\-hoc \fINotFound\fR exception:551.552.IP "" 4553.554.nf555556function NotFound(msg){557 this\.name = \'NotFound\';558 Error\.call(this, msg);559 Error\.captureStackTrace(this, arguments\.callee);560}561562sys\.inherits(NotFound, Error);563564app\.get(\'/404\', function(req, res){565 throw new NotFound;566});567568app\.get(\'/500\', function(req, res){569 throw new Error(\'keyboard cat!\');570});571.572.fi573.574.IP "" 0575.576.P577We can call \fIapp\.error()\fR several times as shown below\. Here we check for an instanceof \fINotFound\fR and show the 404 page, or we pass on to the next error handler\.578.Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 579–581why, one step back579.P580Note that these handlers can be defined anywhere, as they will be placed below the route handlers on \fIlisten()\fR\. This allows for definition within \fIconfigure()\fR blocks so we can handle exceptions in different ways based on the environment\.581.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 582–617why, one step back582.IP "" 4583.584.nf585586app\.error(function(err, req, res, next){587 if (err instanceof NotFound) {588 res\.render(\'404\.jade\');589 } else {590 next(err);591 }592});593.594.fi595.596.IP "" 0597.598.P599Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like600.601.IP "" 4602.603.nf604605app\.error(function(err, req, res){606 res\.render(\'500\.jade\', {607 locals: {608 error: err609 }610 });611});612.613.fi614.615.IP "" 0616.617.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 618why, one step back618Our apps could also utilize the Connect \fIerrorHandler\fR middleware to report on exceptions\. For example if we wish to output exceptions in "development" mode to \fIstderr\fR we can use:Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 619–623why, one step back619.620.IP "" 4621.622.nf623Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 624why, one step back624app\.use(express\.errorHandler({ dumpExceptions: true }));Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 625–636why, one step back625.626.fi627.628.IP "" 0629.630.P631Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:632.633.IP "" 4634.635.nf636Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 637why, one step back637app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 638–646why, one step back638.639.fi640.641.IP "" 0642.643.P644The \fIerrorHandler\fR middleware also responds with \fIjson\fR if \fIAccept: application/json\fR is present, which is useful for developing apps that rely heavily on client\-side JavaScript\.645.646.SS "View Rendering"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 647why, one step back647View filenames take the form \fINAME\fR\.\fIENGINE\fR, where \fIENGINE\fR is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.render(str, options)\fR to comply with Express, however \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by jade\.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 648–717why, one step back648.649.P650Below is an example using Haml\.js \fIhttp://github\.com/visionmedia/haml\.js\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.html\fR will be passed as the \fIbody\fR local variable in \fIlayout\.haml\fR\.651.652.IP "" 4653.654.nf655656app\.get(\'/\', function(req, res){657 res\.render(\'index\.haml\', {658 locals: { title: \'My Site\' }659 });660});661.662.fi663.664.IP "" 0665.666.P667The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using Jade \fIhttp://github\.com/visionmedia/jade\fR we could set:668.669.IP "" 4670.671.nf672673app\.set(\'view engine\', \'jade\');674.675.fi676.677.IP "" 0678.679.P680Allowing us to render with:681.682.IP "" 4683.684.nf685686res\.render(\'index\');687.688.fi689.690.IP "" 0691.692.P693vs:694.695.IP "" 4696.697.nf698699res\.render(\'index\.jade\');700.701.fi702.703.IP "" 0704.705.P706When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:707.708.IP "" 4709.710.nf711712res\.render(\'another\-page\.ejs\');713.714.fi715.716.IP "" 0717.Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 718–746why, one step back718.P719Express also provides the \fIview options\fR setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:720.721.IP "" 4722.723.nf724725app\.set(\'view options\', {726 layout: false727});728.729.fi730.731.IP "" 0732.733.P734Which can then be overridden within the \fBres\.render()\fR call if need be:735.736.IP "" 4737.738.nf739740res\.render(\'myview\.ejs\', { layout: true });741.742.fi743.744.IP "" 0745.746.PRebuilt docsTj Holowaychukbefore adoption2724ce3
lines 747–785why, one step back747When an alternate layout is required, we may also specify a path\. For example if we have \fIview engine\fR set to \fIjade\fR and a file named \fI\./views/mylayout\.jade\fR we can simply pass:748.749.IP "" 4750.751.nf752753res\.render(\'page\', { layout: \'mylayout\' });754.755.fi756.757.IP "" 0758.759.P760Otherwise we must specify the extension:761.762.IP "" 4763.764.nf765766res\.render(\'page\', { layout: \'mylayout\.jade\' });767.768.fi769.770.IP "" 0771.772.P773These paths may also be absolute:774.775.IP "" 4776.777.nf778779res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });780.781.fi782.783.IP "" 0784.785.PAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 786–800why, one step back786A good example of this is specifying custom \fIejs\fR opening and closing tags:787.788.IP "" 4789.790.nf791792app\.set(\'view options\', {793 open: \'{{\',794 close: \'}}\'795});796.797.fi798.799.IP "" 0800.Route callback signature changedTj Holowaychukbefore adoption75661a2
line 801why, one step back801.SS "View Partials"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 802why, one step back802The Express view system has built\-in support for partials and collections, which are sort of "mini" views representing a document fragment\. For example rather than iterating in a view to display comments, we would use a partial with collection support:Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 803–833why, one step back803.804.IP "" 4805.806.nf807808partial(\'comment\.haml\', { collection: comments });809.810.fi811.812.IP "" 0813.814.P815To make things even less verbose we can assume the extension as \fI\.haml\fR when omitted, however if we wished we could use an ejs partial, within a haml view for example\.816.817.IP "" 4818.819.nf820821partial(\'comment\', { collection: comments });822.823.fi824.825.IP "" 0826.827.P828And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:829.830.IP "" 4831.832.nf833Regenerated docsTj Holowaychukbefore adoption2a40cec
line 834why, one step back834partial(\'comment\', comments);Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 835–840why, one step back835.836.fi837.838.IP "" 0839.840.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 841why, one step back841When using the partial collection support a few "magic" variables are provided for free:Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 842–849why, one step back842.843.IP "\(bu" 4844\fIfirstInCollection\fR True if this is the first object845.846.IP "\(bu" 4847\fIindexInCollection\fR Index of the object in the collection848.849.IP "\(bu" 4Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 850why, one step back850\fIlastInCollection\fR True if this is the last objectRoute callback signature changedTj Holowaychukbefore adoption75661a2
line 851why, one step back851.Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 852–854why, one step back852.IP "\(bu" 4853\fIcollectionLength\fR Length of the collection854.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 855–856why, one step back855.IP "" 0856.Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 857–859why, one step back857.P858For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.859.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 860–863why, one step back860.SS "Template Engines"861Below are a few template engines commonly used with Express:862.863.IP "\(bu" 4Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 864why, one step back864Jade \fIhttp://jade\-lang\.com\fR haml\.js successorRoute callback signature changedTj Holowaychukbefore adoption75661a2
lines 865–866why, one step back865.866.IP "\(bu" 4Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 867why, one step back867Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templatesRoute callback signature changedTj Holowaychukbefore adoption75661a2
lines 868–870why, one step back868.869.IP "\(bu" 4870EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScriptRebuilt docsTj Holowaychukbefore adoption2724ce3
line 871why, one step back871.Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 872–874why, one step back872.IP "\(bu" 4873CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating874.Rebuilt docsTj Holowaychukbefore adoption2724ce3
lines 875–902why, one step back875.IP "" 0876.877.SS "Session Support"878Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieDecoder\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.879.880.IP "" 4881.882.nf883884app\.use(express\.cookieDecoder());885app\.use(express\.session());886.887.fi888.889.IP "" 0890.891.P892By default the \fIsession\fR middleware uses the memory store bundled with Connect, however many implementations exist\. For example connect\-redis \fIhttp://github\.com/visionmedia/connect\-redis\fR supplies a Redis \fIhttp://code\.google\.com/p/redis/\fR session store and can be used as shown below:893.894.IP "" 4895.896.nf897898var RedisStore = require(\'connect\-redis\');899app\.use(express\.cookieDecoder());900app\.use(express\.session({ store: new RedisStore }));901.902.fiRoute callback signature changedTj Holowaychukbefore adoption75661a2
lines 903–905why, one step back903.904.IP "" 0905.Regenerated guideTj Holowaychukbefore adoptionf179979
lines 906–942why, one step back906.P907Now the \fIreq\.session\fR and \fIreq\.sessionStore\fR properties will be accessible to all routes and subsequent middleware\. Properties on \fIreq\.session\fR are automatically saved on a response, so for example if we wish to shopping cart data:908.909.IP "" 4910.911.nf912913var RedisStore = require(\'connect\-redis\');914app\.use(express\.cookieDecoder());915app\.use(express\.session({ store: new RedisStore }));916app\.use(express\.bodyDecoder());917918app\.post(\'/add\-to\-cart\', function(req, res){919 // Perhaps we posted several items with a form920 // (use the bodyDecoder() middleware for this)921 var items = req\.body\.items;922 req\.session\.items = items;923 res\.redirect(\'back\');924});925926app\.get(\'/add\-to\-cart\', function(req, res){927 // When redirected back to GET /add\-to\-cart928 // we could check req\.session\.items && req\.session\.items\.length929 // to print out a message930 if (req\.session\.items && req\.session\.items\.length) {931 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);932 }933 res\.render(\'shopping\-cart\');934});935.936.fi937.938.IP "" 0939.940.P941The \fIreq\.session\fR object also has methods such as \fISession#touch()\fR, \fISession#destroy()\fR, \fISession#regenerate()\fR among others to maintain and manipulate sessions\. For more information view the Connect Session \fIhttp://senchalabs\.github\.com/connect/session\.html\fR documentation\.942.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 943–961why, one step back943.SS "req\.header(key[, defaultValue])"944Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:945.946.IP "" 4947.948.nf949950req\.header(\'Host\');951req\.header(\'host\');952req\.header(\'Accept\', \'*/*\');953.954.fi955.956.IP "" 0957.958.SS "req\.accepts(type)"959Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.960.961.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 962why, one step back962When the \fIAccept\fR header is not present \fItrue\fR is returned\. Otherwise the given \fItype\fR is matched by an exact match, and then subtypes\. You may pass the subtype such as "html" which is then converted internally to "text/html" using the mime lookup table\.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 963–990why, one step back963.964.IP "" 4965.966.nf967968// Accept: text/html969req\.accepts(\'html\');970// => true971972// Accept: text/*; application/json973req\.accepts(\'html\');974req\.accepts(\'text/html\');975req\.accepts(\'text/plain\');976req\.accepts(\'application/json\');977// => true978979req\.accepts(\'image/png\');980req\.accepts(\'png\');981// => false982.983.fi984.985.IP "" 0986.987.SS "req\.param(name)"988Return the value of param \fIname\fR when present\.989.990.IP "\(bu" 4Updated docsTj Holowaychukbefore adoptiond691ecb
line 991why, one step back991Checks route placeholders (\fIreq\.params\fR), ex: /user/:idRoute callback signature changedTj Holowaychukbefore adoption75661a2
lines 992–993why, one step back992.993.IP "\(bu" 4Updated docsTj Holowaychukbefore adoptiond691ecb
line 994why, one step back994Checks query string params (\fIreq\.query\fR), ex: ?id=12Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 995–996why, one step back995.996.IP "\(bu" 4Updated docsTj Holowaychukbefore adoptiond691ecb
line 997why, one step back997Checks urlencoded body params (\fIreq\.body\fR), ex: id=12Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 998–1001why, one step back998.999.IP "" 01000.1001.PAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
line 1002why, one step back1002To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1003–1028why, one step back1003.1004.SS "req\.flash(type[, msg])"1005Queue flash \fImsg\fR of the given \fItype\fR\.1006.1007.IP "" 41008.1009.nf10101011req\.flash(\'info\', \'email sent\');1012req\.flash(\'error\', \'email delivery failed\');1013req\.flash(\'info\', \'email re\-sent\');1014// => 210151016req\.flash(\'info\');1017// => [\'email sent\', \'email re\-sent\']10181019req\.flash(\'info\');1020// => []10211022req\.flash();1023// => { error: [\'email delivery failed\'], info: [] }1024.1025.fi1026.1027.IP "" 01028.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1029–1041why, one step back1029.P1030Flash notification message may also utilize formatters, by default only the %s string formatter is available:1031.1032.IP "" 41033.1034.nf10351036req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1037.1038.fi1039.1040.IP "" 01041.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1042–1084why, one step back1042.SS "req\.isXMLHttpRequest"1043Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1044.1045.IP "" 41046.1047.nf10481049req\.xhr1050req\.isXMLHttpRequest1051.1052.fi1053.1054.IP "" 01055.1056.SS "res\.header(key[, val])"1057Get or set the response header \fIkey\fR\.1058.1059.IP "" 41060.1061.nf10621063res\.header(\'Content\-Length\');1064// => undefined10651066res\.header(\'Content\-Length\', 123);1067// => 12310681069res\.header(\'Content\-Length\');1070// => 1231071.1072.fi1073.1074.IP "" 01075.1076.SS "res\.contentType(type)"1077Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1078.1079.IP "" 41080.1081.nf10821083 var filename = \'path/to/image\.png\';1084 res\.contentType(filename);Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1085why, one step back1085 // res\.headers[\'Content\-Type\'] is now "image/png"Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1086–1091why, one step back1086.1087.fi1088.1089.IP "" 01090.1091.SS "res\.attachment([filename])"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1092why, one step back1092Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1093–1117why, one step back1093.1094.IP "" 41095.1096.nf10971098 res\.attachment(\'path/to/my/image\.png\');1099.1100.fi1101.1102.IP "" 01103.1104.SS "res\.sendfile(path)"1105Used by \fBres\.download()\fR to transfer an arbitrary file\.1106.1107.IP "" 41108.1109.nf11101111res\.sendfile(\'path/to/my\.file\');1112.1113.fi1114.1115.IP "" 01116.1117.PUpdated docsTj Holowaychukbefore adoptionf0eab06
lines 1118–1137why, one step back1118This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed\. When a callback is not given, and the file has \fBnot\fR been streamed, \fInext(err)\fR will be called on an exception\.1119.1120.IP "" 41121.1122.nf11231124res\.sendfile(path, function(err, path){1125 if (err) {1126 // handle the error1127 } else {1128 console\.log(\'transferred %s\', path);1129 }1130});1131.1132.fi1133.1134.IP "" 01135.1136.P1137When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1138–1173why, one step back1138.1139.SS "res\.download(file[, filename])"1140Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1141.1142.IP "" 41143.1144.nf11451146res\.download(\'path/to/image\.png\');1147res\.download(\'path/to/image\.png\', \'foo\.png\');1148.1149.fi1150.1151.IP "" 01152.1153.P1154This is equivalent to:1155.1156.IP "" 41157.1158.nf11591160res\.attachment(file);1161res\.sendfile(file);1162.1163.fi1164.1165.IP "" 01166.1167.SS "res\.send(body|status[, headers|status[, status]])"1168The \fBres\.send()\fR method is a high level response utility allowing you to pass objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status code based responses\. The following are all valid uses:1169.1170.IP "" 41171.1172.nf1173Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1174why, one step back1174 res\.send(); // 204Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1175–1206why, one step back1175 res\.send(new Buffer(\'wahoo\'));1176 res\.send({ some: \'json\' });1177 res\.send(\'<p>some html</p>\');1178 res\.send(\'Sorry, cant find that\', 404);1179 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1180 res\.send(404);1181.1182.fi1183.1184.IP "" 01185.1186.P1187By default the \fIContent\-Type\fR response header is set, however if explicitly assigned through \fBres\.send()\fR or previously with \fBres\.header()\fR or \fBres\.contentType()\fR it will not be set again\.1188.1189.SS "res\.redirect(url[, status])"1190Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1191.1192.IP "" 41193.1194.nf11951196res\.redirect(\'/\', 301);1197res\.redirect(\'/account\');1198res\.redirect(\'http://google\.com\');1199res\.redirect(\'home\');1200res\.redirect(\'back\');1201.1202.fi1203.1204.IP "" 01205.1206.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1207why, one step back1207Express supports "redirect mapping", which by default provides \fIhome\fR, and \fIback\fR\. The \fIback\fR map checks the \fIReferrer\fR and \fIReferer\fR headers, while \fIhome\fR utilizes the "home" setting and defaults to "/"\.Route callback signature changedTj Holowaychukbefore adoption75661a2
line 1208why, one step back1208.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1209–1252why, one step back1209.SS "res\.cookie(name, val[, options])"1210Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1211.1212.IP "" 41213.1214.nf12151216// "Remember me" for 15 minutes1217res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1218.1219.fi1220.1221.IP "" 01222.1223.P1224To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1225.1226.IP "" 41227.1228.nf12291230app\.use(express\.cookieDecoder());12311232app\.get(\'/\', function(req, res){1233 // use req\.cookies\.rememberme1234});1235.1236.fi1237.1238.IP "" 01239.1240.SS "res\.clearCookie(name)"1241Clear cookie \fIname\fR by setting "expires" far in the past\.1242.1243.IP "" 41244.1245.nf12461247res\.clearCookie(\'rememberme\');1248.1249.fi1250.1251.IP "" 01252.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1253–1259why, one step back1253.SS "res\.render(view[, options[, fn]])"1254Render \fIview\fR with the given \fIoptions\fR and optional callback \fIfn\fR\. When a callback function is given a response will \fInot\fR be made automatically, however otherwise a response of \fI200\fR and \fItext/html\fR is given\.1255.1256.P1257Most engines accept one or more of the following options, both haml \fIhttp://github\.com/visionmedia/haml\.js\fR and jade \fIhttp://github\.com/visionmedia/jade\fR accept all:1258.1259.IP "\(bu" 4HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
line 1260why, one step back1260\fIscope\fR Template evaluation context (value of \fIthis\fR)Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1261–1267why, one step back1261.1262.IP "\(bu" 41263\fIlocals\fR Object containing local variables1264.1265.IP "\(bu" 41266\fIdebug\fR Output debugging information1267.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1268–1273why, one step back1268.IP "\(bu" 41269\fIstatus\fR Response status code, defaults to 2001270.1271.IP "\(bu" 41272\fIheaders\fR Response headers object1273.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1274–1305why, one step back1274.IP "" 01275.1276.SS "res\.partial(view[, options])"1277Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1278.1279.IP "\(bu" 41280\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.1281.1282.IP "\(bu" 41283as: \'something\' will add the \fIsomething\fR local variable1284.1285.IP "\(bu" 41286as: this will use the collection value as the template context1287.1288.IP "\(bu" 41289as: global will merge the collection value\'s properties with \fIlocals\fR1290.1291.IP "" 012921293.1294.IP "\(bu" 41295\fIcollection\fR Array of objects, the name is derived from the view name itself\. For example \fIvideo\.html\fR will have a object \fIvideo\fR available to it\.1296.1297.IP "" 01298.1299.P1300The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1301.1302.IP "" 41303.1304.nf1305Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 1306–1307why, one step back1306partial(\'theatre/movie\.jade\', { collection: movies });1307partial(\'theatre/movie\.jade\', movies);Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1308–1317why, one step back1308partial(\'movie\.jade\', { collection: movies });1309partial(\'movie\.jade\', movies);1310partial(\'movie\', movies);1311// In view: movie\.director1312.1313.fi1314.1315.IP "" 01316.1317.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1318why, one step back1318To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1319–1345why, one step back1319.1320.IP "" 41321.1322.nf13231324partial(\'movie\', { collection: movies, as: \'video\' });1325// In view: video\.director1326.1327.fi1328.1329.IP "" 01330.1331.P1332Also we can make our movie the value of \fIthis\fR within our view so that instead of \fImovie\.director\fR we could use \fIthis\.director\fR\.1333.1334.IP "" 41335.1336.nf13371338partial(\'movie\', { collection: movies, as: this });1339// In view: this\.director1340.1341.fi1342.1343.IP "" 01344.1345.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1346why, one step back1346Another alternative is to "explode" the properties of the collection item into pseudo globals (local variables) by using \fIas: global\fR, which again is syntactic sugar:Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1347–1365why, one step back1347.1348.IP "" 41349.1350.nf13511352partials(\'movie\', { collection: movies, as: global });1353// In view: director1354.1355.fi1356.1357.IP "" 01358.1359.SS "app\.set(name[, val])"1360Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1361.1362.IP "" 41363.1364.nf1365Updated docsTj Holowaychukbefore adoption3234329
lines 1366–1368why, one step back1366app\.set(\'views\', __dirname + \'/views\');1367app\.set(\'views\');1368// => \.\.\.path\.\.\.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1369–1448why, one step back1369.1370.fi1371.1372.IP "" 01373.1374.SS "app\.enable(name)"1375Enable the given setting \fIname\fR:1376.1377.IP "" 41378.1379.nf13801381app\.enable(\'some arbitrary setting\');1382app\.set(\'some arbitrary setting\');1383// => true1384.1385.fi1386.1387.IP "" 01388.1389.SS "app\.disable(name)"1390Disable the given setting \fIname\fR:1391.1392.IP "" 41393.1394.nf13951396app\.disable(\'some setting\');1397app\.set(\'some setting\');1398// => false1399.1400.fi1401.1402.IP "" 01403.1404.SS "app\.configure(env|function[, function])"1405Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1406.1407.IP "" 41408.1409.nf14101411app\.configure(function(){1412 // executed for each env1413});14141415app\.configure(\'development\', function(){1416 // executed for \'development\' only1417});1418.1419.fi1420.1421.IP "" 01422.1423.SS "app\.redirect(name, val)"1424For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1425.1426.IP "" 41427.1428.nf14291430app\.redirect(\'google\', \'http://google\.com\');1431.1432.fi1433.1434.IP "" 01435.1436.P1437Now in a route we may call:1438.1439.P1440res\.redirect(\'google\');1441.1442.P1443We may also map dynamic redirects:1444.1445.IP "" 41446.1447.nf1448Updated docsTj Holowaychukbefore adoptiond691ecb
lines 1449–1450why, one step back1449app\.redirect(\'comments\', function(req, res){1450 return \'/post/\' + req\.params\.id + \'/comments\';Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1451–1517why, one step back1451});1452.1453.fi1454.1455.IP "" 01456.1457.P1458So now we may do the following, and the redirect will dynamically adjust to the context of the request\. If we called this route with \fIGET /post/12\fR our redirect \fILocation\fR would be \fI/post/12/comments\fR\.1459.1460.IP "" 41461.1462.nf14631464app\.get(\'/post/:id\', function(req, res){1465 res\.redirect(\'comments\');1466});1467.1468.fi1469.1470.IP "" 01471.1472.SS "app\.error(function)"1473Adds an error handler \fIfunction\fR which will receive the exception as the first parameter as shown below\. Note that we may set several error handlers by making several calls to this method, however the handler should call \fInext(err)\fR if it does not wish to deal with the exception:1474.1475.IP "" 41476.1477.nf14781479app\.error(function(err, req, res, next){1480 res\.send(err\.message, 500);1481});1482.1483.fi1484.1485.IP "" 01486.1487.SS "app\.helpers(obj)"1488Registers static view helpers\.1489.1490.IP "" 41491.1492.nf14931494app\.helpers({1495 name: function(first, last){ return first + \', \' + last },1496 firstName: \'tj\',1497 lastName: \'holowaychuk\'1498});1499.1500.fi1501.1502.IP "" 01503.1504.P1505Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1506.1507.IP "" 41508.1509.nf15101511<%= name(firstName, lastName) %>1512.1513.fi1514.1515.IP "" 01516.1517.SS "app\.dynamicHelpers(obj)"Updated docsTj Holowaychukbefore adoptiond691ecb
line 1518why, one step back1518Registers dynamic view helpers\. Dynamic view helpers are simply functions which accept \fIreq\fR, \fIres\fR, and are evaluated against the \fIServer\fR instance before a view is rendered\. The \fIreturn value\fR of this function becomes the local variable it is associated with\.Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1519–1524why, one step back1519.1520.IP "" 41521.1522.nf15231524app\.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 1525why, one step back1525 session: function(req, res){Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1526–1558why, one step back1526 return req\.session;1527 }1528});1529.1530.fi1531.1532.IP "" 01533.1534.P1535All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1536.1537.IP "" 41538.1539.nf15401541<%= session\.name %>1542.1543.fi1544.1545.IP "" 01546.1547.SS "app\.mounted(fn)"1548Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1549.1550.IP "" 41551.1552.nf15531554var app = express\.createServer(),1555 blog = express\.createServer();15561557blog\.mounted(function(parent){1558 // parent is appMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1559why, one step back1559 // "this" is blogRoute callback signature changedTj Holowaychukbefore adoption75661a2
lines 1560–1562why, one step back1560});15611562app\.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1563–1568why, one step back1563.1564.fi1565.1566.IP "" 01567.1568.SS "app\.register(ext, exports)"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1569why, one step back1569Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1570–1581why, one step back1570.1571.IP "" 41572.1573.nf15741575 app\.register(\'\.html\', require(\'jade\'));1576.1577.fi1578.1579.IP "" 01580.1581.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1582why, one step back1582This is also useful for libraries that may not match extensions correctly\. For example my haml\.js library is installed from npm as "hamljs" so instead of layout\.hamljs, we can register the engine as "\.haml":Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1583–1603why, one step back1583.1584.IP "" 41585.1586.nf15871588 app\.register(\'\.haml\', require(\'haml\-js\'));1589.1590.fi1591.1592.IP "" 01593.1594.P1595For engines that do not comply with the Express specification, we can also wrap their api this way\.1596.1597.IP "" 41598.1599.nf16001601 app\.register(\'\.foo\', {1602 render: function(str, options) {1603 // perhaps their api isRegenerated docsTj Holowaychukbefore adoption5152823
line 1604why, one step back1604 // return foo\.toHTML(str, options);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1605–1606why, one step back1605 }1606 });Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1607–1659why, one step back1607.1608.fi1609.1610.IP "" 01611.1612.SS "app\.listen([port[, host]])"1613Bind the app server to the given \fIport\fR, which defaults to 3000\. When \fIhost\fR is omitted all connections will be accepted via \fIINADDR_ANY\fR\.1614.1615.IP "" 41616.1617.nf16181619app\.listen();1620app\.listen(3000);1621app\.listen(3000, \'n\.n\.n\.n\');1622.1623.fi1624.1625.IP "" 01626.1627.P1628The \fIport\fR argument may also be a string representing the path to a unix domain socket:1629.1630.IP "" 41631.1632.nf16331634app\.listen(\'/tmp/express\.sock\');1635.1636.fi1637.1638.IP "" 01639.1640.P1641Then try it out:1642.1643.IP "" 41644.1645.nf16461647$ telnet /tmp/express\.sock1648GET / HTTP/1\.116491650HTTP/1\.1 200 OK1651Content\-Type: text/plain1652Content\-Length: 1116531654Hello World1655.1656.fi1657.1658.IP "" 01659