Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,338 lines · 26.0 KiB

Last changed by

Updated docsTj Holowaychukbefore adoptionf0eab06

History of this file

Take it

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 3why, one step back
3.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 5why, one step back
5.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 9why, one step back
9.SS "Installation"

No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9

line 10why, one step back
10curl:

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 11–15why, one step back
11.
12.IP "" 413.14.nf15

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

line 16why, one step back
16$ curl \-# http://expressjs\.com/install\.sh | sh

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 17–22why, one step back
17.
18.fi19.20.IP "" 021.22.P

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

line 23why, one step back
23npm:

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 24–28why, one step back
24.
25.IP "" 426.27.nf28

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

line 29why, one step back
29$ npm install express

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 30–72why, one step back
30.
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.P

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 74–79why, one step back
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 configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 109–137why, 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.P122To alter the environment we can set the \fICONNECT_ENV\fR environment variable, or more specifically \fIEXPRESS_ENV\fR, for example:123.124.IP "" 4125.126.nf127128$ EXPRESS_ENV=production node app\.js129.130.fi131.132.IP "" 0133.134.SS "Settings"135Express supports the following settings out of the box:136.137.IP "\(bu" 4

Updated docsTj Holowaychukbefore adoption4d32762

line 138why, one step back
138\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 139–140why, one step back
139.
140.IP "\(bu" 4

New "home" docsTj Holowaychukbefore adoption1e7a12f

line 141why, one step back
141\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 142–148why, one step back
142.
143.IP "\(bu" 4144\fIviews\fR Root views directory defaulting to \fBCWD/views\fR145.146.IP "\(bu" 4147\fIview engine\fR Default view engine name for views rendered without extensions148.

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 149–154why, one step back
149.IP "\(bu" 4
150\fIview options\fR An object specifying global view options151.152.IP "\(bu" 4153\fIpartials\fR Root view partials directory defaulting to \fIviews\fR/partials\.154.

Updated docsTj Holowaychukbefore adoptionf0eab06

lines 155–157why, one step back
155.IP "\(bu" 4
156\fIstream threshold\fR Bytesize indicating when a file should be streamed for \fIres\.sendfile()\fR using \fIfs\.ReadStream()\fR and \fIsys\.pump()\fR\.157.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 158–160why, one step back
158.IP "" 0
159.160.SS "Routing"

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 162–166why, one step back
162.
163.IP "" 4164.165.nf166

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 167–168why, one step back
167app\.get(\'/user/:id\', function(req, res){
168 res\.send(\'user \' + req\.params\.id);

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 169–181why, one step back
169});
170.171.fi172.173.IP "" 0174.175.P176A 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:177.178.IP "" 4179.180.nf181

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 183–188why, one step back
183.
184.fi185.186.IP "" 0187.188.P

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 190–194why, one step back
190.
191.IP "" 4192.193.nf194

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated docsTj Holowaychukbefore adoptiond691ecb

line 196why, one step back
196 res\.send(req\.params);

Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b

lines 197–214why, one step back
197});
198.199.fi200.201.IP "" 0202.203.P204Curl requests against the previously defined route:205.206.IP "" 4207.208.nf209210 $ curl http://dev:3000/user211 [null,null]212 $ curl http://dev:3000/users213 [null,null]214 $ curl http://dev:3000/users/1

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 218–229why, one step back
218.
219.fi220.221.IP "" 0222.223.P224Below are some route examples, and the associated paths that they may consume:225.226.IP "" 4227.228.nf229

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 231–232why, one step back
231 /user/12
232

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 234–236why, one step back
234 /users/5
235 /users236

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 238–240why, one step back
238 /files/jquery\.js
239 /files/javascripts/jquery\.js240

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 246–248why, one step back
246 /user/1
247 /user/1/edit248

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 250–252why, one step back
250 /products\.json
251 /products\.xml252

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 254–262why, one step back
254 /products\.json
255 /products\.xml256 /products257.258.fi259.260.IP "" 0261.262.SS "Passing Route Control"

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 264–268why, one step back
264.
265.IP "" 4266.267.nf268

Updated docsTj Holowaychukbefore adoptionb819366

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

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 270–271why, one step back
270 var id = req\.params\.id;
271 if (id) {

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 272–277why, one step back
272 // do something
273 } else {274 next();275 }276});277

Updated docsTj Holowaychukbefore adoptiond691ecb

line 278why, one step back
278app\.get(\'/users\', function(req, res){

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 279–286why, one step back
279 // do something else
280});281.282.fi283.284.IP "" 0285.286.SS "Middleware"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 287why, one step back
287The Express \fIPlugin\fR is no more! middleware 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:

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 288–292why, one step back
288.
289.IP "" 4290.291.nf292

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 293why, one step back
293var express = require(\'express\');

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 294–295why, one step back
294
295var app = express\.createServer(

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 296–297why, one step back
296 express\.logger(),
297 express\.bodyDecoder()

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 298–310why, one step back
298);
299.300.fi301.302.IP "" 0303.304.P305Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:306.307.IP "" 4308.309.nf310

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 311why, one step back
311app\.use(express\.logger({ format: \':method :uri\' }));

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 312–316why, one step back
312.
313.fi314.315.IP "" 0316.

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 317–343why, one step back
317.P
318Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:319.320.IP "" 4321.322.nf323324var connect = require(\'connect\');325app\.use(connect\.logger());326.327.fi328.329.IP "" 0330.331.P332This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:333.334.IP "" 4335.336.nf337338app\.use(express\.logger());339.340.fi341.342.IP "" 0343.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 344–373why, one step back
344.SS "Error Handling"
345Express 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:346.347.IP "" 4348.349.nf350351function NotFound(msg){352 this\.name = \'NotFound\';353 Error\.call(this, msg);354 Error\.captureStackTrace(this, arguments\.callee);355}356357sys\.inherits(NotFound, Error);358359app\.get(\'/404\', function(req, res){360 throw new NotFound;361});362363app\.get(\'/500\', function(req, res){364 throw new Error(\'keyboard cat!\');365});366.367.fi368.369.IP "" 0370.371.P372We 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\.373.

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 374–376why, one step back
374.P
375Note 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\.376.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 377–412why, one step back
377.IP "" 4
378.379.nf380381app\.error(function(err, req, res, next){382 if (err instanceof NotFound) {383 res\.render(\'404\.jade\');384 } else {385 next(err);386 }387});388.389.fi390.391.IP "" 0392.393.P394Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like395.396.IP "" 4397.398.nf399400app\.error(function(err, req, res){401 res\.render(\'500\.jade\', {402 locals: {403 error: err404 }405 });406});407.408.fi409.410.IP "" 0411.412.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 414–418why, one step back
414.
415.IP "" 4416.417.nf418

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 420–431why, one step back
420.
421.fi422.423.IP "" 0424.425.P426Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:427.428.IP "" 4429.430.nf431

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 433–441why, one step back
433.
434.fi435.436.IP "" 0437.438.P439The \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\.440.441.SS "View Rendering"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 443–512why, one step back
443.
444.P445Below 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\.446.447.IP "" 4448.449.nf450451app\.get(\'/\', function(req, res){452 res\.render(\'index\.haml\', {453 locals: { title: \'My Site\' }454 });455});456.457.fi458.459.IP "" 0460.461.P462The 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:463.464.IP "" 4465.466.nf467468app\.set(\'view engine\', \'jade\');469.470.fi471.472.IP "" 0473.474.P475Allowing us to render with:476.477.IP "" 4478.479.nf480481res\.render(\'index\');482.483.fi484.485.IP "" 0486.487.P488vs:489.490.IP "" 4491.492.nf493494res\.render(\'index\.jade\');495.496.fi497.498.IP "" 0499.500.P501When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:502.503.IP "" 4504.505.nf506507res\.render(\'another\-page\.ejs\');508.509.fi510.511.IP "" 0512.

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 513–556why, one step back
513.P
514Express 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:515.516.IP "" 4517.518.nf519520app\.set(\'view options\', {521 layout: false522});523.524.fi525.526.IP "" 0527.528.P529Which can then be overridden within the \fBres\.render()\fR call if need be:530.531.IP "" 4532.533.nf534535res\.render(\'myview\.ejs\', { layout: true });536.537.fi538.539.IP "" 0540.541.P542A good example of this is specifying custom \fIejs\fR opening and closing tags:543.544.IP "" 4545.546.nf547548app\.set(\'view options\', {549 open: \'{{\',550 close: \'}}\'551});552.553.fi554.555.IP "" 0556.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 559–596why, one step back
559.
560.IP "" 4561.562.nf563564partial(\'comment\.haml\', { collection: comments });565.566.fi567.568.IP "" 0569.570.P571To 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\.572.573.IP "" 4574.575.nf576577partial(\'comment\', { collection: comments });578.579.fi580.581.IP "" 0582.583.P584And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:585.586.IP "" 4587.588.nf589590partial(\'comments\', comments);591.592.fi593.594.IP "" 0595.596.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 598–605why, one step back
598.
599.IP "\(bu" 4600\fIfirstInCollection\fR True if this is the first object601.602.IP "\(bu" 4603\fIindexInCollection\fR Index of the object in the collection604.605.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 607–613why, one step back
607.
608.IP "" 0609.610.SS "Template Engines"611Below are a few template engines commonly used with Express:612.613.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 615–616why, one step back
615.
616.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 618–642why, one step back
618.
619.IP "\(bu" 4620EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript621.622.IP "" 0623.624.SS "req\.header(key[, defaultValue])"625Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:626.627.IP "" 4628.629.nf630631req\.header(\'Host\');632req\.header(\'host\');633req\.header(\'Accept\', \'*/*\');634.635.fi636.637.IP "" 0638.639.SS "req\.accepts(type)"640Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.641.642.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 644–671why, one step back
644.
645.IP "" 4646.647.nf648649// Accept: text/html650req\.accepts(\'html\');651// => true652653// Accept: text/*; application/json654req\.accepts(\'html\');655req\.accepts(\'text/html\');656req\.accepts(\'text/plain\');657req\.accepts(\'application/json\');658// => true659660req\.accepts(\'image/png\');661req\.accepts(\'png\');662// => false663.664.fi665.666.IP "" 0667.668.SS "req\.param(name)"669Return the value of param \fIname\fR when present\.670.671.IP "\(bu" 4

Updated docsTj Holowaychukbefore adoptiond691ecb

line 672why, one step back
672Checks route placeholders (\fIreq\.params\fR), ex: /user/:id

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 673–674why, one step back
673.
674.IP "\(bu" 4

Updated docsTj Holowaychukbefore adoptiond691ecb

line 675why, one step back
675Checks query string params (\fIreq\.query\fR), ex: ?id=12

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 676–677why, one step back
676.
677.IP "\(bu" 4

Updated docsTj Holowaychukbefore adoptiond691ecb

line 678why, one step back
678Checks urlencoded body params (\fIreq\.body\fR), ex: id=12

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 679–682why, one step back
679.
680.IP "" 0681.682.P

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 684–709why, one step back
684.
685.SS "req\.flash(type[, msg])"686Queue flash \fImsg\fR of the given \fItype\fR\.687.688.IP "" 4689.690.nf691692req\.flash(\'info\', \'email sent\');693req\.flash(\'error\', \'email delivery failed\');694req\.flash(\'info\', \'email re\-sent\');695// => 2696697req\.flash(\'info\');698// => [\'email sent\', \'email re\-sent\']699700req\.flash(\'info\');701// => []702703req\.flash();704// => { error: [\'email delivery failed\'], info: [] }705.706.fi707.708.IP "" 0709.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 710–722why, one step back
710.P
711Flash notification message may also utilize formatters, by default only the %s string formatter is available:712.713.IP "" 4714.715.nf716717req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);718.719.fi720.721.IP "" 0722.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 723–765why, one step back
723.SS "req\.isXMLHttpRequest"
724Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:725.726.IP "" 4727.728.nf729730req\.xhr731req\.isXMLHttpRequest732.733.fi734.735.IP "" 0736.737.SS "res\.header(key[, val])"738Get or set the response header \fIkey\fR\.739.740.IP "" 4741.742.nf743744res\.header(\'Content\-Length\');745// => undefined746747res\.header(\'Content\-Length\', 123);748// => 123749750res\.header(\'Content\-Length\');751// => 123752.753.fi754.755.IP "" 0756.757.SS "res\.contentType(type)"758Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.759.760.IP "" 4761.762.nf763764 var filename = \'path/to/image\.png\';765 res\.contentType(filename);

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 767–772why, one step back
767.
768.fi769.770.IP "" 0771.772.SS "res\.attachment([filename])"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 774–798why, one step back
774.
775.IP "" 4776.777.nf778779 res\.attachment(\'path/to/my/image\.png\');780.781.fi782.783.IP "" 0784.785.SS "res\.sendfile(path)"786Used by \fBres\.download()\fR to transfer an arbitrary file\.787.788.IP "" 4789.790.nf791792res\.sendfile(\'path/to/my\.file\');793.794.fi795.796.IP "" 0797.798.P

Updated docsTj Holowaychukbefore adoptionf0eab06

lines 799–818why, one step back
799This 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\.
800.801.IP "" 4802.803.nf804805res\.sendfile(path, function(err, path){806 if (err) {807 // handle the error808 } else {809 console\.log(\'transferred %s\', path);810 }811});812.813.fi814.815.IP "" 0816.817.P818When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 819–854why, one step back
819.
820.SS "res\.download(file[, filename])"821Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.822.823.IP "" 4824.825.nf826827res\.download(\'path/to/image\.png\');828res\.download(\'path/to/image\.png\', \'foo\.png\');829.830.fi831.832.IP "" 0833.834.P835This is equivalent to:836.837.IP "" 4838.839.nf840841res\.attachment(file);842res\.sendfile(file);843.844.fi845.846.IP "" 0847.848.SS "res\.send(body|status[, headers|status[, status]])"849The \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:850.851.IP "" 4852.853.nf854

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 856–887why, one step back
856 res\.send(new Buffer(\'wahoo\'));
857 res\.send({ some: \'json\' });858 res\.send(\'<p>some html</p>\');859 res\.send(\'Sorry, cant find that\', 404);860 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);861 res\.send(404);862.863.fi864.865.IP "" 0866.867.P868By 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\.869.870.SS "res\.redirect(url[, status])"871Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.872.873.IP "" 4874.875.nf876877res\.redirect(\'/\', 301);878res\.redirect(\'/account\');879res\.redirect(\'http://google\.com\');880res\.redirect(\'home\');881res\.redirect(\'back\');882.883.fi884.885.IP "" 0886.887.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 889why, one step back
889.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 890–933why, one step back
890.SS "res\.cookie(name, val[, options])"
891Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.892.893.IP "" 4894.895.nf896897// "Remember me" for 15 minutes898res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });899.900.fi901.902.IP "" 0903.904.P905To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:906.907.IP "" 4908.909.nf910911app\.use(express\.cookieDecoder());912913app\.get(\'/\', function(req, res){914 // use req\.cookies\.rememberme915});916.917.fi918.919.IP "" 0920.921.SS "res\.clearCookie(name)"922Clear cookie \fIname\fR by setting "expires" far in the past\.923.924.IP "" 4925.926.nf927928res\.clearCookie(\'rememberme\');929.930.fi931.932.IP "" 0933.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 934–948why, one step back
934.SS "res\.render(view[, options[, fn]])"
935Render \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\.936.937.P938Most 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:939.940.IP "\(bu" 4941\fIcontext|scope\fR Template evaluation context (\fIthis\fR)942.943.IP "\(bu" 4944\fIlocals\fR Object containing local variables945.946.IP "\(bu" 4947\fIdebug\fR Output debugging information948.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 949–954why, one step back
949.IP "\(bu" 4
950\fIstatus\fR Response status code, defaults to 200951.952.IP "\(bu" 4953\fIheaders\fR Response headers object954.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 955–996why, one step back
955.IP "" 0
956.957.SS "res\.partial(view[, options])"958Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.959.960.IP "\(bu" 4961\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.962.963.IP "\(bu" 4964as: \'something\' will add the \fIsomething\fR local variable965.966.IP "\(bu" 4967as: this will use the collection value as the template context968.969.IP "\(bu" 4970as: global will merge the collection value\'s properties with \fIlocals\fR971.972.IP "" 0973974.975.IP "\(bu" 4976\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\.977.978.IP "" 0979.980.P981The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.982.983.IP "" 4984.985.nf986987partial(\'movie\.jade\', { collection: movies });988partial(\'movie\.jade\', movies);989partial(\'movie\', movies);990// In view: movie\.director991.992.fi993.994.IP "" 0995.996.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 998–1024why, one step back
998.
999.IP "" 41000.1001.nf10021003partial(\'movie\', { collection: movies, as: \'video\' });1004// In view: video\.director1005.1006.fi1007.1008.IP "" 01009.1010.P1011Also 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\.1012.1013.IP "" 41014.1015.nf10161017partial(\'movie\', { collection: movies, as: this });1018// In view: this\.director1019.1020.fi1021.1022.IP "" 01023.1024.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 1026–1044why, one step back
1026.
1027.IP "" 41028.1029.nf10301031partials(\'movie\', { collection: movies, as: global });1032// In view: director1033.1034.fi1035.1036.IP "" 01037.1038.SS "app\.set(name[, val])"1039Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1040.1041.IP "" 41042.1043.nf1044

Updated docsTj Holowaychukbefore adoption3234329

lines 1045–1047why, one step back
1045app\.set(\'views\', __dirname + \'/views\');
1046app\.set(\'views\');1047// => \.\.\.path\.\.\.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 1048–1127why, one step back
1048.
1049.fi1050.1051.IP "" 01052.1053.SS "app\.enable(name)"1054Enable the given setting \fIname\fR:1055.1056.IP "" 41057.1058.nf10591060app\.enable(\'some arbitrary setting\');1061app\.set(\'some arbitrary setting\');1062// => true1063.1064.fi1065.1066.IP "" 01067.1068.SS "app\.disable(name)"1069Disable the given setting \fIname\fR:1070.1071.IP "" 41072.1073.nf10741075app\.disable(\'some setting\');1076app\.set(\'some setting\');1077// => false1078.1079.fi1080.1081.IP "" 01082.1083.SS "app\.configure(env|function[, function])"1084Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1085.1086.IP "" 41087.1088.nf10891090app\.configure(function(){1091 // executed for each env1092});10931094app\.configure(\'development\', function(){1095 // executed for \'development\' only1096});1097.1098.fi1099.1100.IP "" 01101.1102.SS "app\.redirect(name, val)"1103For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1104.1105.IP "" 41106.1107.nf11081109app\.redirect(\'google\', \'http://google\.com\');1110.1111.fi1112.1113.IP "" 01114.1115.P1116Now in a route we may call:1117.1118.P1119res\.redirect(\'google\');1120.1121.P1122We may also map dynamic redirects:1123.1124.IP "" 41125.1126.nf1127

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 1128–1129why, one step back
1128app\.redirect(\'comments\', function(req, res){
1129 return \'/post/\' + req\.params\.id + \'/comments\';

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 1130–1164why, one step back
1130});
1131.1132.fi1133.1134.IP "" 01135.1136.P1137So 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\.1138.1139.IP "" 41140.1141.nf11421143app\.get(\'/post/:id\', function(req, res){1144 res\.redirect(\'comments\');1145});1146.1147.fi1148.1149.IP "" 01150.1151.SS "app\.error(function)"1152Adds 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:1153.1154.IP "" 41155.1156.nf11571158app\.error(function(err, req, res, next){1159 res\.send(err\.message, 500);1160});1161.1162.fi1163.1164.IP "" 0

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 1165–1166why, one step back
1165.
1166.SS "app\.helpers(obj)"

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

line 1167why, one step back
1167Registers static view helpers\.

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 1168–1173why, one step back
1168.
1169.IP "" 41170.1171.nf11721173app\.helpers({

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

lines 1174–1196why, one step back
1174 name: function(first, last){ return first + \', \' + last },
1175 firstName: \'tj\',1176 lastName: \'holowaychuk\'1177});1178.1179.fi1180.1181.IP "" 01182.1183.P1184Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1185.1186.IP "" 41187.1188.nf11891190<%= name(firstName, lastName) %>1191.1192.fi1193.1194.IP "" 01195.1196.SS "app\.dynamicHelpers(obj)"

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

lines 1198–1203why, one step back
1198.
1199.IP "" 41200.1201.nf12021203app\.dynamicHelpers({

Updated docsTj Holowaychukbefore adoptiond691ecb

line 1204why, one step back
1204 session: function(req, res){

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 1205–1213why, one step back
1205 return req\.session;
1206 }1207});1208.1209.fi1210.1211.IP "" 01212.1213.P

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

lines 1214–1220why, one step back
1214All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:
1215.1216.IP "" 41217.1218.nf12191220<%= session\.name %>

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 1221–1237why, one step back
1221.
1222.fi1223.1224.IP "" 01225.1226.SS "app\.mounted(fn)"1227Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1228.1229.IP "" 41230.1231.nf12321233var app = express\.createServer(),1234 blog = express\.createServer();12351236blog\.mounted(function(parent){1237 // parent is app

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 1239–1241why, one step back
1239});
12401241app\.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1242–1247why, one step back
1242.
1243.fi1244.1245.IP "" 01246.1247.SS "app\.register(ext, exports)"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1248why, one step back
1248Register 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 1249–1260why, one step back
1249.
1250.IP "" 41251.1252.nf12531254 app\.register(\'\.html\', require(\'jade\'));1255.1256.fi1257.1258.IP "" 01259.1260.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1261why, one step back
1261This 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 1262–1285why, one step back
1262.
1263.IP "" 41264.1265.nf12661267 app\.register(\'\.haml\', require(\'haml\-js\'));1268.1269.fi1270.1271.IP "" 01272.1273.P1274For engines that do not comply with the Express specification, we can also wrap their api this way\.1275.1276.IP "" 41277.1278.nf12791280 app\.register(\'\.foo\', {1281 render: function(str, options) {1282 // perhaps their api is1283 // foo\.toHTML(str, options);1284 }1285 });

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

lines 1286–1289why, one step back
1286.
1287.fi1288.1289.IP "" 0

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 1290–1338why, one step back
1290.
1291.SS "app\.listen([port[, host]])"1292Bind 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\.1293.1294.IP "" 41295.1296.nf12971298app\.listen();1299app\.listen(3000);1300app\.listen(3000, \'n\.n\.n\.n\');1301.1302.fi1303.1304.IP "" 01305.1306.P1307The \fIport\fR argument may also be a string representing the path to a unix domain socket:1308.1309.IP "" 41310.1311.nf13121313app\.listen(\'/tmp/express\.sock\');1314.1315.fi1316.1317.IP "" 01318.1319.P1320Then try it out:1321.1322.IP "" 41323.1324.nf13251326$ telnet /tmp/express\.sock1327GET / HTTP/1\.113281329HTTP/1\.1 200 OK1330Content\-Type: text/plain1331Content\-Length: 1113321333Hello World1334.1335.fi1336.1337.IP "" 01338