Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,749 lines · 36.4 KiB

Last changed by

Regenerate api docsTj Holowaychukbefore adoption129e21e

History of this file

Take it

The walk stopped after 200 commits: lines older than 1706721 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

Updated ejsTj Holowaychukbefore adoption1706721

line 3why, one step back
3.

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

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

Updated ejsTj Holowaychukbefore adoption1706721

line 5why, one step back
5.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated ejsTj Holowaychukbefore adoption1706721

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());

Updated ejsTj Holowaychukbefore adoption1706721

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\'));

Updated ejsTj Holowaychukbefore adoption1706721

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 }));

Updated ejsTj Holowaychukbefore adoption1706721

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());

Updated ejsTj Holowaychukbefore adoption1706721

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 \.\.\."

Updated ejsTj Holowaychukbefore adoption1706721

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:

Updated ejsTj Holowaychukbefore adoption1706721

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

Updated ejsTj Holowaychukbefore adoption1706721

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.

Updated ejsTj Holowaychukbefore adoption1706721

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.

Updated ejsTj Holowaychukbefore adoption1706721

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/?

Updated ejsTj Holowaychukbefore adoption1706721

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){

Updated ejsTj Holowaychukbefore adoption1706721

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]

Updated ejsTj Holowaychukbefore adoption1706721

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"]

Updated ejsTj Holowaychukbefore adoption1706721

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"

Updated ejsTj Holowaychukbefore adoption1706721

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated ejsTj Holowaychukbefore adoption1706721

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated ejsTj Holowaychukbefore adoption1706721

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/*\.*"

Updated ejsTj Holowaychukbefore adoption1706721

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?"

Updated ejsTj Holowaychukbefore adoption1706721

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"

Updated ejsTj Holowaychukbefore adoption1706721

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?"

Updated ejsTj Holowaychukbefore adoption1706721

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\.

Updated ejsTj Holowaychukbefore adoption1706721

lines 267–287why, one step back
267.
268.IP "" 4269.270.nf271272app\.get(\'/users/:id?\', function(req, res, next){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\.

Updated ejsTj Holowaychukbefore adoption1706721

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.

Updated ejsTj Holowaychukbefore adoption1706721

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.

Updated ejsTj Holowaychukbefore adoption1706721

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:

Updated ejsTj Holowaychukbefore adoption1706721

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 }));

Updated ejsTj Holowaychukbefore adoption1706721

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 }));

Updated ejsTj Holowaychukbefore adoption1706721

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\.

Updated ejsTj Holowaychukbefore adoption1706721

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.

Updated ejsTj Holowaychukbefore adoption1706721

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:

Updated ejsTj Holowaychukbefore adoption1706721

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);

Updated ejsTj Holowaychukbefore adoption1706721

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:

Updated ejsTj Holowaychukbefore adoption1706721

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

Updated ejsTj Holowaychukbefore adoption1706721

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.

Updated ejsTj Holowaychukbefore adoption1706721

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.

Updated ejsTj Holowaychukbefore adoption1706721

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

Updated ejsTj Holowaychukbefore adoption1706721

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

Updated ejsTj Holowaychukbefore adoption1706721

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

Updated ejsTj Holowaychukbefore adoption1706721

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.

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

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.

Updated ejsTj Holowaychukbefore adoption1706721

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\.

Updated ejsTj Holowaychukbefore adoption1706721

lines 966–989why, 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.

Added req.is() docsTj Holowaychukbefore adoption806aefa

lines 990–1047why, one step back
990.SS "req\.is(type)"
991Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.992.993.IP "" 4994.995.nf996997 // With Content\-Type: text/html; charset=utf\-8998 req\.is(\'html\');999 req\.is(\'text/html\');1000 // => true10011002 // When Content\-Type is application/json1003 req\.is(\'json\');1004 req\.is(\'application/json\');1005 // => true10061007 req\.is(\'html\');1008 // => false1009.1010.fi1011.1012.IP "" 01013.1014.P1015Ad\-hoc callbacks can also be registered with Express, to perform assertions again the request, for example if we need an expressive way to check if our incoming request is an image, we can register \fI"an image"\fR callback:1016.1017.IP "" 41018.1019.nf10201021 app\.is(\'an image\', function(req){1022 return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1023 });1024.1025.fi1026.1027.IP "" 01028.1029.P1030Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1031.1032.IP "" 41033.1034.nf10351036 app\.post(\'/image/upload\', function(req, res, next){1037 if (req\.is(\'an image\')) {1038 // do something1039 } else {1040 next();1041 }1042 });1043.1044.fi1045.1046.IP "" 01047.

Merge branch 'is'Tj Holowaychukbefore adoption7a71380

lines 1048–1076why, one step back
1048.P
1049Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1050.1051.P1052Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1053.1054.IP "" 41055.1056.nf10571058req\.is(\'image/*\');1059.1060.fi1061.1062.IP "" 01063.1064.P1065We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1066.1067.IP "" 41068.1069.nf10701071req\.is(\'*/json\');1072.1073.fi1074.1075.IP "" 01076.

Updated ejsTj Holowaychukbefore adoption1706721

lines 1077–1091why, one step back
1077.SS "req\.param(name)"
1078Return the value of param \fIname\fR when present\.1079.1080.IP "\(bu" 41081Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1082.1083.IP "\(bu" 41084Checks query string params (\fIreq\.query\fR), ex: ?id=121085.1086.IP "\(bu" 41087Checks urlencoded body params (\fIreq\.body\fR), ex: id=121088.1089.IP "" 01090.1091.P

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Updated ejsTj Holowaychukbefore adoption1706721

lines 1093–1118why, one step back
1093.
1094.SS "req\.flash(type[, msg])"1095Queue flash \fImsg\fR of the given \fItype\fR\.1096.1097.IP "" 41098.1099.nf11001101req\.flash(\'info\', \'email sent\');1102req\.flash(\'error\', \'email delivery failed\');1103req\.flash(\'info\', \'email re\-sent\');1104// => 211051106req\.flash(\'info\');1107// => [\'email sent\', \'email re\-sent\']11081109req\.flash(\'info\');1110// => []11111112req\.flash();1113// => { error: [\'email delivery failed\'], info: [] }1114.1115.fi1116.1117.IP "" 01118.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1119–1131why, one step back
1119.P
1120Flash notification message may also utilize formatters, by default only the %s string formatter is available:1121.1122.IP "" 41123.1124.nf11251126req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1127.1128.fi1129.1130.IP "" 01131.

Updated ejsTj Holowaychukbefore adoption1706721

lines 1132–1174why, one step back
1132.SS "req\.isXMLHttpRequest"
1133Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1134.1135.IP "" 41136.1137.nf11381139req\.xhr1140req\.isXMLHttpRequest1141.1142.fi1143.1144.IP "" 01145.1146.SS "res\.header(key[, val])"1147Get or set the response header \fIkey\fR\.1148.1149.IP "" 41150.1151.nf11521153res\.header(\'Content\-Length\');1154// => undefined11551156res\.header(\'Content\-Length\', 123);1157// => 12311581159res\.header(\'Content\-Length\');1160// => 1231161.1162.fi1163.1164.IP "" 01165.1166.SS "res\.contentType(type)"1167Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1168.1169.IP "" 41170.1171.nf11721173 var filename = \'path/to/image\.png\';1174 res\.contentType(filename);

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated ejsTj Holowaychukbefore adoption1706721

lines 1176–1181why, one step back
1176.
1177.fi1178.1179.IP "" 01180.1181.SS "res\.attachment([filename])"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated ejsTj Holowaychukbefore adoption1706721

lines 1183–1207why, one step back
1183.
1184.IP "" 41185.1186.nf11871188 res\.attachment(\'path/to/my/image\.png\');1189.1190.fi1191.1192.IP "" 01193.1194.SS "res\.sendfile(path)"1195Used by \fBres\.download()\fR to transfer an arbitrary file\.1196.1197.IP "" 41198.1199.nf12001201res\.sendfile(\'path/to/my\.file\');1202.1203.fi1204.1205.IP "" 01206.1207.P

Updated docsTj Holowaychukbefore adoptionf0eab06

lines 1208–1227why, one step back
1208This 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\.
1209.1210.IP "" 41211.1212.nf12131214res\.sendfile(path, function(err, path){1215 if (err) {1216 // handle the error1217 } else {1218 console\.log(\'transferred %s\', path);1219 }1220});1221.1222.fi1223.1224.IP "" 01225.1226.P1227When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.

Updated ejsTj Holowaychukbefore adoption1706721

lines 1228–1263why, one step back
1228.
1229.SS "res\.download(file[, filename])"1230Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1231.1232.IP "" 41233.1234.nf12351236res\.download(\'path/to/image\.png\');1237res\.download(\'path/to/image\.png\', \'foo\.png\');1238.1239.fi1240.1241.IP "" 01242.1243.P1244This is equivalent to:1245.1246.IP "" 41247.1248.nf12491250res\.attachment(file);1251res\.sendfile(file);1252.1253.fi1254.1255.IP "" 01256.1257.SS "res\.send(body|status[, headers|status[, status]])"1258The \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:1259.1260.IP "" 41261.1262.nf1263

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated ejsTj Holowaychukbefore adoption1706721

lines 1265–1296why, one step back
1265 res\.send(new Buffer(\'wahoo\'));
1266 res\.send({ some: \'json\' });1267 res\.send(\'<p>some html</p>\');1268 res\.send(\'Sorry, cant find that\', 404);1269 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1270 res\.send(404);1271.1272.fi1273.1274.IP "" 01275.1276.P1277By 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\.1278.1279.SS "res\.redirect(url[, status])"1280Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1281.1282.IP "" 41283.1284.nf12851286res\.redirect(\'/\', 301);1287res\.redirect(\'/account\');1288res\.redirect(\'http://google\.com\');1289res\.redirect(\'home\');1290res\.redirect(\'back\');1291.1292.fi1293.1294.IP "" 01295.1296.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated ejsTj Holowaychukbefore adoption1706721

line 1298why, one step back
1298.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1299–1342why, one step back
1299.SS "res\.cookie(name, val[, options])"
1300Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1301.1302.IP "" 41303.1304.nf13051306// "Remember me" for 15 minutes1307res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1308.1309.fi1310.1311.IP "" 01312.1313.P1314To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1315.1316.IP "" 41317.1318.nf13191320app\.use(express\.cookieDecoder());13211322app\.get(\'/\', function(req, res){1323 // use req\.cookies\.rememberme1324});1325.1326.fi1327.1328.IP "" 01329.1330.SS "res\.clearCookie(name)"1331Clear cookie \fIname\fR by setting "expires" far in the past\.1332.1333.IP "" 41334.1335.nf13361337res\.clearCookie(\'rememberme\');1338.1339.fi1340.1341.IP "" 01342.

Updated ejsTj Holowaychukbefore adoption1706721

lines 1343–1349why, one step back
1343.SS "res\.render(view[, options[, fn]])"
1344Render \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\.1345.1346.P1347Most 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:1348.1349.IP "\(bu" 4

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

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

Updated ejsTj Holowaychukbefore adoption1706721

lines 1351–1357why, one step back
1351.
1352.IP "\(bu" 41353\fIlocals\fR Object containing local variables1354.1355.IP "\(bu" 41356\fIdebug\fR Output debugging information1357.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1358–1363why, one step back
1358.IP "\(bu" 4
1359\fIstatus\fR Response status code, defaults to 2001360.1361.IP "\(bu" 41362\fIheaders\fR Response headers object1363.

Updated ejsTj Holowaychukbefore adoption1706721

lines 1364–1395why, one step back
1364.IP "" 0
1365.1366.SS "res\.partial(view[, options])"1367Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1368.1369.IP "\(bu" 41370\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.1371.1372.IP "\(bu" 41373as: \'something\' will add the \fIsomething\fR local variable1374.1375.IP "\(bu" 41376as: this will use the collection value as the template context1377.1378.IP "\(bu" 41379as: global will merge the collection value\'s properties with \fIlocals\fR1380.1381.IP "" 013821383.1384.IP "\(bu" 41385\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\.1386.1387.IP "" 01388.1389.P1390The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1391.1392.IP "" 41393.1394.nf1395

Regenerated docsTj Holowaychukbefore adoption2a40cec

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

Updated ejsTj Holowaychukbefore adoption1706721

lines 1398–1407why, one step back
1398partial(\'movie\.jade\', { collection: movies });
1399partial(\'movie\.jade\', movies);1400partial(\'movie\', movies);1401// In view: movie\.director1402.1403.fi1404.1405.IP "" 01406.1407.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated ejsTj Holowaychukbefore adoption1706721

lines 1409–1435why, one step back
1409.
1410.IP "" 41411.1412.nf14131414partial(\'movie\', { collection: movies, as: \'video\' });1415// In view: video\.director1416.1417.fi1418.1419.IP "" 01420.1421.P1422Also 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\.1423.1424.IP "" 41425.1426.nf14271428partial(\'movie\', { collection: movies, as: this });1429// In view: this\.director1430.1431.fi1432.1433.IP "" 01434.1435.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated ejsTj Holowaychukbefore adoption1706721

lines 1437–1648why, one step back
1437.
1438.IP "" 41439.1440.nf14411442partials(\'movie\', { collection: movies, as: global });1443// In view: director1444.1445.fi1446.1447.IP "" 01448.1449.SS "app\.set(name[, val])"1450Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1451.1452.IP "" 41453.1454.nf14551456app\.set(\'views\', __dirname + \'/views\');1457app\.set(\'views\');1458// => \.\.\.path\.\.\.1459.1460.fi1461.1462.IP "" 01463.1464.SS "app\.enable(name)"1465Enable the given setting \fIname\fR:1466.1467.IP "" 41468.1469.nf14701471app\.enable(\'some arbitrary setting\');1472app\.set(\'some arbitrary setting\');1473// => true1474.1475.fi1476.1477.IP "" 01478.1479.SS "app\.disable(name)"1480Disable the given setting \fIname\fR:1481.1482.IP "" 41483.1484.nf14851486app\.disable(\'some setting\');1487app\.set(\'some setting\');1488// => false1489.1490.fi1491.1492.IP "" 01493.1494.SS "app\.configure(env|function[, function])"1495Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1496.1497.IP "" 41498.1499.nf15001501app\.configure(function(){1502 // executed for each env1503});15041505app\.configure(\'development\', function(){1506 // executed for \'development\' only1507});1508.1509.fi1510.1511.IP "" 01512.1513.SS "app\.redirect(name, val)"1514For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1515.1516.IP "" 41517.1518.nf15191520app\.redirect(\'google\', \'http://google\.com\');1521.1522.fi1523.1524.IP "" 01525.1526.P1527Now in a route we may call:1528.1529.P1530res\.redirect(\'google\');1531.1532.P1533We may also map dynamic redirects:1534.1535.IP "" 41536.1537.nf15381539app\.redirect(\'comments\', function(req, res){1540 return \'/post/\' + req\.params\.id + \'/comments\';1541});1542.1543.fi1544.1545.IP "" 01546.1547.P1548So 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\.1549.1550.IP "" 41551.1552.nf15531554app\.get(\'/post/:id\', function(req, res){1555 res\.redirect(\'comments\');1556});1557.1558.fi1559.1560.IP "" 01561.1562.SS "app\.error(function)"1563Adds 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:1564.1565.IP "" 41566.1567.nf15681569app\.error(function(err, req, res, next){1570 res\.send(err\.message, 500);1571});1572.1573.fi1574.1575.IP "" 01576.1577.SS "app\.helpers(obj)"1578Registers static view helpers\.1579.1580.IP "" 41581.1582.nf15831584app\.helpers({1585 name: function(first, last){ return first + \', \' + last },1586 firstName: \'tj\',1587 lastName: \'holowaychuk\'1588});1589.1590.fi1591.1592.IP "" 01593.1594.P1595Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1596.1597.IP "" 41598.1599.nf16001601<%= name(firstName, lastName) %>1602.1603.fi1604.1605.IP "" 01606.1607.SS "app\.dynamicHelpers(obj)"1608Registers 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\.1609.1610.IP "" 41611.1612.nf16131614app\.dynamicHelpers({1615 session: function(req, res){1616 return req\.session;1617 }1618});1619.1620.fi1621.1622.IP "" 01623.1624.P1625All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1626.1627.IP "" 41628.1629.nf16301631<%= session\.name %>1632.1633.fi1634.1635.IP "" 01636.1637.SS "app\.mounted(fn)"1638Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1639.1640.IP "" 41641.1642.nf16431644var app = express\.createServer(),1645 blog = express\.createServer();16461647blog\.mounted(function(parent){1648 // parent is app

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated ejsTj Holowaychukbefore adoption1706721

lines 1650–1652why, one step back
1650});
16511652app\.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1653–1658why, one step back
1653.
1654.fi1655.1656.IP "" 01657.1658.SS "app\.register(ext, exports)"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1659why, one step back
1659Register 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 1660–1671why, one step back
1660.
1661.IP "" 41662.1663.nf16641665 app\.register(\'\.html\', require(\'jade\'));1666.1667.fi1668.1669.IP "" 01670.1671.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1672why, one step back
1672This 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 1673–1693why, one step back
1673.
1674.IP "" 41675.1676.nf16771678 app\.register(\'\.haml\', require(\'haml\-js\'));1679.1680.fi1681.1682.IP "" 01683.1684.P1685For engines that do not comply with the Express specification, we can also wrap their api this way\.1686.1687.IP "" 41688.1689.nf16901691 app\.register(\'\.foo\', {1692 render: function(str, options) {1693 // perhaps their api is

Regenerated docsTj Holowaychukbefore adoption5152823

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1695–1696why, one step back
1695 }
1696 });

Updated ejsTj Holowaychukbefore adoption1706721

lines 1697–1749why, one step back
1697.
1698.fi1699.1700.IP "" 01701.1702.SS "app\.listen([port[, host]])"1703Bind 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\.1704.1705.IP "" 41706.1707.nf17081709app\.listen();1710app\.listen(3000);1711app\.listen(3000, \'n\.n\.n\.n\');1712.1713.fi1714.1715.IP "" 01716.1717.P1718The \fIport\fR argument may also be a string representing the path to a unix domain socket:1719.1720.IP "" 41721.1722.nf17231724app\.listen(\'/tmp/express\.sock\');1725.1726.fi1727.1728.IP "" 01729.1730.P1731Then try it out:1732.1733.IP "" 41734.1735.nf17361737$ telnet /tmp/express\.sock1738GET / HTTP/1\.117391740HTTP/1\.1 200 OK1741Content\-Type: text/plain1742Content\-Length: 1117431744Hello World1745.1746.fi1747.1748.IP "" 01749