Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,662 lines · 34.8 KiB

Last changed by

Started apps sectionTj Holowaychukbefore adoptiond3f139c

History of this file

Take it

The walk stopped after 200 commits: lines older than 018abcf point at it.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1–2why, one step back
1.\" generated with Ronn/v0.7.3
2.\" http://github.com/rtomayko/ronn/tree/0.7.3

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

line 3why, one step back
3.

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

line 4why, one step back
4.TH "GUIDE" "" "October 2010" "" ""

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

line 5why, one step back
5.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 6–8why, one step back
6.SH "NAME"
7\fBguide\fR8.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 9–79why, one step back
9.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 back
80 app\.use(express\.methodOverride());
81 app\.use(express\.bodyDecoder());

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

line 82why, one step back
82 app\.use(app\.router);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 83why, one step back
83 app\.use(express\.staticProvider(__dirname + \'/public\'));

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 84–86why, one step back
84});
8586app\.configure(\'development\', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 87why, one step back
87 app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 88–90why, one step back
88});
8990app\.configure(\'production\', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 91why, one step back
91 app\.use(express\.errorHandler());

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 92–107why, one step back
92});
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 back
108 // => "\.\.\. views directory \.\.\."

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 109–121why, one step back
109
110 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.P

Rebuilt docsTj Holowaychukbefore adoption2724ce3

line 122why, one step back
122To alter the environment we can set the \fINODE_ENV\fR environment variable, for example:

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 123–127why, one step back
123.
124.IP "" 4125.126.nf127

Rebuilt docsTj Holowaychukbefore adoption2724ce3

line 128why, one step back
128$ NODE_ENV=production node app\.js

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 129–133why, one step back
129.
130.fi131.132.IP "" 0133.

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 134–136why, one step back
134.P
135This is \fIvery\fR important, as many caching mechanisms are \fIonly enabled\fR when in production\.136.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 137–151why, one step back
137.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 back
152.IP "\(bu" 4
153\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 back
158.IP "\(bu" 4
159\fIstream threshold\fR Bytesize indicating when a file should be streamed for \fIres\.sendfile()\fR using \fIfs\.ReadStream()\fR and \fIsys\.pump()\fR\.160.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 161–184why, one step back
161.IP "" 0
162.163.SS "Routing"164Express 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\.165.166.IP "" 4167.168.nf169170app\.get(\'/user/:id\', function(req, res){171 res\.send(\'user \' + req\.params\.id);172});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.nf184

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 185why, one step back
185\e/user\e/([^\e/]+)\e/?

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 186–197why, one step back
186.
187.fi188.189.IP "" 0190.191.P192Regular 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\.193.194.IP "" 4195.196.nf197

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 198why, one step back
198app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 199–217why, one step back
199 res\.send(req\.params);
200});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/1

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 218why, one step back
218 ["1",null]

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

line 219why, one step back
219 $ curl http://dev:3000/users/1\.\.15

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 220why, one step back
220 ["1","15"]

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 221–232why, one step back
221.
222.fi223.224.IP "" 0225.226.P227Below are some route examples, and the associated paths that they may consume:228.229.IP "" 4230.231.nf232

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 233why, one step back
233 "/user/:id"

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 234–235why, one step back
234 /user/12
235

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 236why, one step back
236 "/users/:id?"

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 237–239why, one step back
237 /users/5
238 /users239

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 240why, one step back
240 "/files/*"

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 241–243why, one step back
241 /files/jquery\.js
242 /files/javascripts/jquery\.js243

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 244why, one step back
244 "/file/*\.*"

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 245–247why, one step back
245 /files/jquery\.js
246 /files/javascripts/jquery\.js247

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 248why, one step back
248 "/user/:id/:operation?"

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 249–251why, one step back
249 /user/1
250 /user/1/edit251

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 252why, one step back
252 "/products\.:format"

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 253–255why, one step back
253 /products\.json
254 /products\.xml255

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 256why, one step back
256 "/products\.:format?"

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 257–265why, one step back
257 /products\.json
258 /products\.xml259 /products260.261.fi262.263.IP "" 0264.265.SS "Passing Route Control"

Regenerated docsTj Holowaychukbefore adoption334a18a

line 266why, one step back
266We 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\.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 267–271why, one step back
267.
268.IP "" 4269.270.nf271

Updated docsTj Holowaychukbefore adoptionb819366

line 272why, one step back
272app\.get(\'/users/:id?\', function(req, res, next){

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 273–287why, one step back
273 var id = req\.params\.id;
274 if (id) {275 // do something276 } else {277 next();278 }279});280281app\.get(\'/users\', function(req, res){282 // do something else283});284.285.fi286.287.IP "" 0

Regenerated docsTj Holowaychukbefore adoption334a18a

line 288why, one step back
288.

Regenerated docsTj Holowaychukbefore adoption090debe

lines 289–346why, one step back
289.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 back
347.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.P

Regenerated docsTj Holowaychukbefore adoption0faac20

line 351why, one step back
351Typically 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 back
352.
353.IP "" 4354.355.nf356

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 357–358why, one step back
357app\.get(\'/user/:id\', function(req, res, next){
358 loadUser(req\.params\.id, function(err, user){

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 359–360why, one step back
359 if (err) return next(err);
360 res\.send(\'Viewing user \' + user\.name);

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 361–362why, one step back
361 });
362});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 363–374why, one step back
363.
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.nf374

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 375–383why, one step back
375function 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 back
384}

Regenerated docsTj Holowaychukbefore adoption0faac20

line 385why, one step back
385

Regenerated docsTj Holowaychukbefore adoption334a18a

line 386why, one step back
386app\.get(\'/user/:id\', loadUser, function(req, res){

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 387–388why, one step back
387 res\.send(\'Viewing user \' + req\.user\.name);
388});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 389–400why, one step back
389.
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.nf400

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 401–402why, one step back
401function andRestrictToSelf(req, res, next) {
402 req\.authenticatedUser\.id == req\.user\.id

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 403–404why, one step back
403 ? next()
404 : next(new Error(\'Unauthorized\'));

Regenerated docsTj Holowaychukbefore adoption334a18a

line 405why, one step back
405}

Regenerated docsTj Holowaychukbefore adoption0faac20

line 406why, one step back
406

Regenerated docsTj Holowaychukbefore adoption334a18a

line 407why, one step back
407app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 408–409why, one step back
408 res\.send(\'Editing user \' + req\.user\.name);
409});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 410–421why, one step back
410.
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.nf421

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 422–424why, one step back
422function andRestrictTo(role) {
423 return function(req, res, next) {424 req\.authenticatedUser\.role == role

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 425–426why, one step back
425 ? next()
426 : next(new Error(\'Unauthorized\'));

Regenerated docsTj Holowaychukbefore adoption0faac20

line 427why, one step back
427 }

Regenerated docsTj Holowaychukbefore adoption334a18a

line 428why, one step back
428}

Regenerated docsTj Holowaychukbefore adoption0faac20

line 429why, one step back
429

Regenerated docsTj Holowaychukbefore adoption334a18a

line 430why, one step back
430app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 431–432why, one step back
431 res\.send(\'Deleted user \' + req\.user\.name);
432});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 433–444why, one step back
433.
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.nf444

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 445–454why, one step back
445var 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 back
455.
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\.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

line 462why, one step back
462.

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 463–472why, one step back
463.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.nf472

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 473–477why, one step back
473 <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 back
478.
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 back
544.
545.fi546.547.IP "" 0548.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 549–578why, one step back
549.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 back
579.P
580Note 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.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 582–617why, one step back
582.IP "" 4
583.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.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 618why, one step back
618Our 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:

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 619–623why, one step back
619.
620.IP "" 4621.622.nf623

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 624why, one step back
624app\.use(express\.errorHandler({ dumpExceptions: true }));

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 625–636why, one step back
625.
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.nf636

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 637why, one step back
637app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 638–646why, one step back
638.
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 back
647View 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\.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 648–717why, one step back
648.
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 back
718.P
719Express 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.P

Rebuilt docsTj Holowaychukbefore adoption2724ce3

lines 747–785why, one step back
747When 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.P

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 786–800why, one step back
786A 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.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

line 801why, one step back
801.SS "View Partials"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 802why, one step back
802The 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:

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 803–833why, one step back
803.
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.nf833

Regenerated docsTj Holowaychukbefore adoption2a40cec

line 834why, one step back
834partial(\'comment\', comments);

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 835–840why, one step back
835.
836.fi837.838.IP "" 0839.840.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 841why, one step back
841When using the partial collection support a few "magic" variables are provided for free:

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 842–849why, one step back
842.
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" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

line 850why, one step back
850\fIlastInCollection\fR True if this is the last object

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

line 851why, one step back
851.

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 852–854why, one step back
852.IP "\(bu" 4
853\fIcollectionLength\fR Length of the collection854.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 855–856why, one step back
855.IP "" 0
856.

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 857–859why, one step back
857.P
858For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.859.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 860–863why, one step back
860.SS "Template Engines"
861Below are a few template engines commonly used with Express:862.863.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

line 864why, one step back
864Jade \fIhttp://jade\-lang\.com\fR haml\.js successor

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 865–866why, one step back
865.
866.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

line 867why, one step back
867Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 868–870why, one step back
868.
869.IP "\(bu" 4870EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript

Rebuilt docsTj Holowaychukbefore adoption2724ce3

line 871why, one step back
871.

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 872–874why, one step back
872.IP "\(bu" 4
873CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating874.

Rebuilt docsTj Holowaychukbefore adoption2724ce3

lines 875–902why, one step back
875.IP "" 0
876.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.fi

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 903–905why, one step back
903.
904.IP "" 0905.

Regenerated guideTj Holowaychukbefore adoptionf179979

lines 906–913why, one step back
906.P
907Now 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\');

Regenerated docsTj Holowaychukbefore adoption1c9831a

line 914why, one step back
914app\.use(express\.bodyDecoder());

Regenerated guideTj Holowaychukbefore adoptionf179979

lines 915–942why, one step back
915app\.use(express\.cookieDecoder());
916app\.use(express\.session({ store: new RedisStore }));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.

Started apps sectionTj Holowaychukbefore adoptiond3f139c

lines 943–945why, one step back
943.SS "Migration Guide"
944Pre\-beta Express developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.945.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 946–964why, one step back
946.SS "req\.header(key[, defaultValue])"
947Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:948.949.IP "" 4950.951.nf952953req\.header(\'Host\');954req\.header(\'host\');955req\.header(\'Accept\', \'*/*\');956.957.fi958.959.IP "" 0960.961.SS "req\.accepts(type)"962Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.963.964.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 965why, one step back
965When 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\.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 966–1004why, one step back
966.
967.IP "" 4968.969.nf970971// Accept: text/html972req\.accepts(\'html\');973// => true974975// Accept: text/*; application/json976req\.accepts(\'html\');977req\.accepts(\'text/html\');978req\.accepts(\'text/plain\');979req\.accepts(\'application/json\');980// => true981982req\.accepts(\'image/png\');983req\.accepts(\'png\');984// => false985.986.fi987.988.IP "" 0989.990.SS "req\.param(name)"991Return the value of param \fIname\fR when present\.992.993.IP "\(bu" 4994Checks route placeholders (\fIreq\.params\fR), ex: /user/:id995.996.IP "\(bu" 4997Checks query string params (\fIreq\.query\fR), ex: ?id=12998.999.IP "\(bu" 41000Checks urlencoded body params (\fIreq\.body\fR), ex: id=121001.1002.IP "" 01003.1004.P

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 1005why, one step back
1005To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1006–1031why, one step back
1006.
1007.SS "req\.flash(type[, msg])"1008Queue flash \fImsg\fR of the given \fItype\fR\.1009.1010.IP "" 41011.1012.nf10131014req\.flash(\'info\', \'email sent\');1015req\.flash(\'error\', \'email delivery failed\');1016req\.flash(\'info\', \'email re\-sent\');1017// => 210181019req\.flash(\'info\');1020// => [\'email sent\', \'email re\-sent\']10211022req\.flash(\'info\');1023// => []10241025req\.flash();1026// => { error: [\'email delivery failed\'], info: [] }1027.1028.fi1029.1030.IP "" 01031.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1032–1044why, one step back
1032.P
1033Flash notification message may also utilize formatters, by default only the %s string formatter is available:1034.1035.IP "" 41036.1037.nf10381039req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1040.1041.fi1042.1043.IP "" 01044.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1045–1087why, one step back
1045.SS "req\.isXMLHttpRequest"
1046Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1047.1048.IP "" 41049.1050.nf10511052req\.xhr1053req\.isXMLHttpRequest1054.1055.fi1056.1057.IP "" 01058.1059.SS "res\.header(key[, val])"1060Get or set the response header \fIkey\fR\.1061.1062.IP "" 41063.1064.nf10651066res\.header(\'Content\-Length\');1067// => undefined10681069res\.header(\'Content\-Length\', 123);1070// => 12310711072res\.header(\'Content\-Length\');1073// => 1231074.1075.fi1076.1077.IP "" 01078.1079.SS "res\.contentType(type)"1080Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1081.1082.IP "" 41083.1084.nf10851086 var filename = \'path/to/image\.png\';1087 res\.contentType(filename);

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1088why, one step back
1088 // res\.headers[\'Content\-Type\'] is now "image/png"

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1089–1094why, one step back
1089.
1090.fi1091.1092.IP "" 01093.1094.SS "res\.attachment([filename])"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1095why, one step back
1095Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1096–1120why, one step back
1096.
1097.IP "" 41098.1099.nf11001101 res\.attachment(\'path/to/my/image\.png\');1102.1103.fi1104.1105.IP "" 01106.1107.SS "res\.sendfile(path)"1108Used by \fBres\.download()\fR to transfer an arbitrary file\.1109.1110.IP "" 41111.1112.nf11131114res\.sendfile(\'path/to/my\.file\');1115.1116.fi1117.1118.IP "" 01119.1120.P

Updated docsTj Holowaychukbefore adoptionf0eab06

lines 1121–1140why, one step back
1121This 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\.
1122.1123.IP "" 41124.1125.nf11261127res\.sendfile(path, function(err, path){1128 if (err) {1129 // handle the error1130 } else {1131 console\.log(\'transferred %s\', path);1132 }1133});1134.1135.fi1136.1137.IP "" 01138.1139.P1140When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1141–1176why, one step back
1141.
1142.SS "res\.download(file[, filename])"1143Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1144.1145.IP "" 41146.1147.nf11481149res\.download(\'path/to/image\.png\');1150res\.download(\'path/to/image\.png\', \'foo\.png\');1151.1152.fi1153.1154.IP "" 01155.1156.P1157This is equivalent to:1158.1159.IP "" 41160.1161.nf11621163res\.attachment(file);1164res\.sendfile(file);1165.1166.fi1167.1168.IP "" 01169.1170.SS "res\.send(body|status[, headers|status[, status]])"1171The \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:1172.1173.IP "" 41174.1175.nf1176

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1177why, one step back
1177 res\.send(); // 204

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1178–1209why, one step back
1178 res\.send(new Buffer(\'wahoo\'));
1179 res\.send({ some: \'json\' });1180 res\.send(\'<p>some html</p>\');1181 res\.send(\'Sorry, cant find that\', 404);1182 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1183 res\.send(404);1184.1185.fi1186.1187.IP "" 01188.1189.P1190By 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\.1191.1192.SS "res\.redirect(url[, status])"1193Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1194.1195.IP "" 41196.1197.nf11981199res\.redirect(\'/\', 301);1200res\.redirect(\'/account\');1201res\.redirect(\'http://google\.com\');1202res\.redirect(\'home\');1203res\.redirect(\'back\');1204.1205.fi1206.1207.IP "" 01208.1209.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1210why, one step back
1210Express 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 "/"\.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

line 1211why, one step back
1211.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1212–1255why, one step back
1212.SS "res\.cookie(name, val[, options])"
1213Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1214.1215.IP "" 41216.1217.nf12181219// "Remember me" for 15 minutes1220res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1221.1222.fi1223.1224.IP "" 01225.1226.P1227To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1228.1229.IP "" 41230.1231.nf12321233app\.use(express\.cookieDecoder());12341235app\.get(\'/\', function(req, res){1236 // use req\.cookies\.rememberme1237});1238.1239.fi1240.1241.IP "" 01242.1243.SS "res\.clearCookie(name)"1244Clear cookie \fIname\fR by setting "expires" far in the past\.1245.1246.IP "" 41247.1248.nf12491250res\.clearCookie(\'rememberme\');1251.1252.fi1253.1254.IP "" 01255.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1256–1262why, one step back
1256.SS "res\.render(view[, options[, fn]])"
1257Render \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\.1258.1259.P1260Most 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:1261.1262.IP "\(bu" 4

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

line 1263why, one step back
1263\fIscope\fR Template evaluation context (value of \fIthis\fR)

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1264–1270why, one step back
1264.
1265.IP "\(bu" 41266\fIlocals\fR Object containing local variables1267.1268.IP "\(bu" 41269\fIdebug\fR Output debugging information1270.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1271–1276why, one step back
1271.IP "\(bu" 4
1272\fIstatus\fR Response status code, defaults to 2001273.1274.IP "\(bu" 41275\fIheaders\fR Response headers object1276.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1277–1308why, one step back
1277.IP "" 0
1278.1279.SS "res\.partial(view[, options])"1280Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1281.1282.IP "\(bu" 41283\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.1284.1285.IP "\(bu" 41286as: \'something\' will add the \fIsomething\fR local variable1287.1288.IP "\(bu" 41289as: this will use the collection value as the template context1290.1291.IP "\(bu" 41292as: global will merge the collection value\'s properties with \fIlocals\fR1293.1294.IP "" 012951296.1297.IP "\(bu" 41298\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\.1299.1300.IP "" 01301.1302.P1303The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1304.1305.IP "" 41306.1307.nf1308

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 1309–1310why, one step back
1309partial(\'theatre/movie\.jade\', { collection: movies });
1310partial(\'theatre/movie\.jade\', movies);

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1311–1320why, one step back
1311partial(\'movie\.jade\', { collection: movies });
1312partial(\'movie\.jade\', movies);1313partial(\'movie\', movies);1314// In view: movie\.director1315.1316.fi1317.1318.IP "" 01319.1320.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1321why, one step back
1321To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1322–1348why, one step back
1322.
1323.IP "" 41324.1325.nf13261327partial(\'movie\', { collection: movies, as: \'video\' });1328// In view: video\.director1329.1330.fi1331.1332.IP "" 01333.1334.P1335Also 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\.1336.1337.IP "" 41338.1339.nf13401341partial(\'movie\', { collection: movies, as: this });1342// In view: this\.director1343.1344.fi1345.1346.IP "" 01347.1348.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1349why, one step back
1349Another 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:

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1350–1368why, one step back
1350.
1351.IP "" 41352.1353.nf13541355partials(\'movie\', { collection: movies, as: global });1356// In view: director1357.1358.fi1359.1360.IP "" 01361.1362.SS "app\.set(name[, val])"1363Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1364.1365.IP "" 41366.1367.nf1368

Updated docsTj Holowaychukbefore adoption3234329

lines 1369–1371why, one step back
1369app\.set(\'views\', __dirname + \'/views\');
1370app\.set(\'views\');1371// => \.\.\.path\.\.\.

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1372–1561why, one step back
1372.
1373.fi1374.1375.IP "" 01376.1377.SS "app\.enable(name)"1378Enable the given setting \fIname\fR:1379.1380.IP "" 41381.1382.nf13831384app\.enable(\'some arbitrary setting\');1385app\.set(\'some arbitrary setting\');1386// => true1387.1388.fi1389.1390.IP "" 01391.1392.SS "app\.disable(name)"1393Disable the given setting \fIname\fR:1394.1395.IP "" 41396.1397.nf13981399app\.disable(\'some setting\');1400app\.set(\'some setting\');1401// => false1402.1403.fi1404.1405.IP "" 01406.1407.SS "app\.configure(env|function[, function])"1408Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1409.1410.IP "" 41411.1412.nf14131414app\.configure(function(){1415 // executed for each env1416});14171418app\.configure(\'development\', function(){1419 // executed for \'development\' only1420});1421.1422.fi1423.1424.IP "" 01425.1426.SS "app\.redirect(name, val)"1427For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1428.1429.IP "" 41430.1431.nf14321433app\.redirect(\'google\', \'http://google\.com\');1434.1435.fi1436.1437.IP "" 01438.1439.P1440Now in a route we may call:1441.1442.P1443res\.redirect(\'google\');1444.1445.P1446We may also map dynamic redirects:1447.1448.IP "" 41449.1450.nf14511452app\.redirect(\'comments\', function(req, res){1453 return \'/post/\' + req\.params\.id + \'/comments\';1454});1455.1456.fi1457.1458.IP "" 01459.1460.P1461So 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\.1462.1463.IP "" 41464.1465.nf14661467app\.get(\'/post/:id\', function(req, res){1468 res\.redirect(\'comments\');1469});1470.1471.fi1472.1473.IP "" 01474.1475.SS "app\.error(function)"1476Adds 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:1477.1478.IP "" 41479.1480.nf14811482app\.error(function(err, req, res, next){1483 res\.send(err\.message, 500);1484});1485.1486.fi1487.1488.IP "" 01489.1490.SS "app\.helpers(obj)"1491Registers static view helpers\.1492.1493.IP "" 41494.1495.nf14961497app\.helpers({1498 name: function(first, last){ return first + \', \' + last },1499 firstName: \'tj\',1500 lastName: \'holowaychuk\'1501});1502.1503.fi1504.1505.IP "" 01506.1507.P1508Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1509.1510.IP "" 41511.1512.nf15131514<%= name(firstName, lastName) %>1515.1516.fi1517.1518.IP "" 01519.1520.SS "app\.dynamicHelpers(obj)"1521Registers 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\.1522.1523.IP "" 41524.1525.nf15261527app\.dynamicHelpers({1528 session: function(req, res){1529 return req\.session;1530 }1531});1532.1533.fi1534.1535.IP "" 01536.1537.P1538All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1539.1540.IP "" 41541.1542.nf15431544<%= session\.name %>1545.1546.fi1547.1548.IP "" 01549.1550.SS "app\.mounted(fn)"1551Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1552.1553.IP "" 41554.1555.nf15561557var app = express\.createServer(),1558 blog = express\.createServer();15591560blog\.mounted(function(parent){1561 // parent is app

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1562why, one step back
1562 // "this" is blog

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1563–1565why, one step back
1563});
15641565app\.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1566–1571why, one step back
1566.
1567.fi1568.1569.IP "" 01570.1571.SS "app\.register(ext, exports)"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1572why, one step back
1572Register 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 1573–1584why, one step back
1573.
1574.IP "" 41575.1576.nf15771578 app\.register(\'\.html\', require(\'jade\'));1579.1580.fi1581.1582.IP "" 01583.1584.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1585why, one step back
1585This 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 1586–1606why, one step back
1586.
1587.IP "" 41588.1589.nf15901591 app\.register(\'\.haml\', require(\'haml\-js\'));1592.1593.fi1594.1595.IP "" 01596.1597.P1598For engines that do not comply with the Express specification, we can also wrap their api this way\.1599.1600.IP "" 41601.1602.nf16031604 app\.register(\'\.foo\', {1605 render: function(str, options) {1606 // perhaps their api is

Regenerated docsTj Holowaychukbefore adoption5152823

line 1607why, one step back
1607 // return foo\.toHTML(str, options);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1608–1609why, one step back
1608 }
1609 });

Added jade submodule back. Closes #376Tj Holowaychukbefore adoption018abcf

lines 1610–1662why, one step back
1610.
1611.fi1612.1613.IP "" 01614.1615.SS "app\.listen([port[, host]])"1616Bind 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\.1617.1618.IP "" 41619.1620.nf16211622app\.listen();1623app\.listen(3000);1624app\.listen(3000, \'n\.n\.n\.n\');1625.1626.fi1627.1628.IP "" 01629.1630.P1631The \fIport\fR argument may also be a string representing the path to a unix domain socket:1632.1633.IP "" 41634.1635.nf16361637app\.listen(\'/tmp/express\.sock\');1638.1639.fi1640.1641.IP "" 01642.1643.P1644Then try it out:1645.1646.IP "" 41647.1648.nf16491650$ telnet /tmp/express\.sock1651GET / HTTP/1\.116521653HTTP/1\.1 200 OK1654Content\-Type: text/plain1655Content\-Length: 1116561657Hello World1658.1659.fi1660.1661.IP "" 01662