Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,316 lines · 25.6 KiB

Last changed by

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 155–157why, one step back
155.IP "" 0
156.157.SS "Routing"

Updated docsTj Holowaychukbefore adoptiond691ecb

line 158why, one step back
158Express 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 159–163why, one step back
159.
160.IP "" 4161.162.nf163

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 166–178why, one step back
166});
167.168.fi169.170.IP "" 0171.172.P173A 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:174.175.IP "" 4176.177.nf178

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 180–185why, one step back
180.
181.fi182.183.IP "" 0184.185.P

Updated docsTj Holowaychukbefore adoptiond691ecb

line 186why, one step back
186Regular 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 187–191why, one step back
187.
188.IP "" 4189.190.nf191

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

lines 194–211why, one step back
194});
195.196.fi197.198.IP "" 0199.200.P201Curl requests against the previously defined route:202.203.IP "" 4204.205.nf206207 $ curl http://dev:3000/user208 [null,null]209 $ curl http://dev:3000/users210 [null,null]211 $ curl http://dev:3000/users/1

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

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

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 215–226why, one step back
215.
216.fi217.218.IP "" 0219.220.P221Below are some route examples, and the associated paths that they may consume:222.223.IP "" 4224.225.nf226

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 228–229why, one step back
228 /user/12
229

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 231–233why, one step back
231 /users/5
232 /users233

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 235–237why, one step back
235 /files/jquery\.js
236 /files/javascripts/jquery\.js237

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 243–245why, one step back
243 /user/1
244 /user/1/edit245

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 247–249why, one step back
247 /products\.json
248 /products\.xml249

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 251–259why, one step back
251 /products\.json
252 /products\.xml253 /products254.255.fi256.257.IP "" 0258.259.SS "Passing Route Control"

Updated docsTj Holowaychukbefore adoptiond691ecb

line 260why, one step back
260We 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 261–265why, one step back
261.
262.IP "" 4263.264.nf265

Updated docsTj Holowaychukbefore adoptionb819366

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 269–274why, one step back
269 // do something
270 } else {271 next();272 }273});274

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 276–283why, one step back
276 // do something else
277});278.279.fi280.281.IP "" 0282.283.SS "Middleware"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 284why, one step back
284The 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 285–289why, one step back
285.
286.IP "" 4287.288.nf289

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 291–292why, one step back
291
292var app = express\.createServer(

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 293–294why, one step back
293 express\.logger(),
294 express\.bodyDecoder()

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 295–307why, one step back
295);
296.297.fi298.299.IP "" 0300.301.P302Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:303.304.IP "" 4305.306.nf307

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 309–313why, one step back
309.
310.fi311.312.IP "" 0313.

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 314–340why, one step back
314.P
315Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:316.317.IP "" 4318.319.nf320321var connect = require(\'connect\');322app\.use(connect\.logger());323.324.fi325.326.IP "" 0327.328.P329This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:330.331.IP "" 4332.333.nf334335app\.use(express\.logger());336.337.fi338.339.IP "" 0340.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 341–370why, one step back
341.SS "Error Handling"
342Express 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:343.344.IP "" 4345.346.nf347348function NotFound(msg){349 this\.name = \'NotFound\';350 Error\.call(this, msg);351 Error\.captureStackTrace(this, arguments\.callee);352}353354sys\.inherits(NotFound, Error);355356app\.get(\'/404\', function(req, res){357 throw new NotFound;358});359360app\.get(\'/500\', function(req, res){361 throw new Error(\'keyboard cat!\');362});363.364.fi365.366.IP "" 0367.368.P369We 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\.370.

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 371–373why, one step back
371.P
372Note 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\.373.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 374–409why, one step back
374.IP "" 4
375.376.nf377378app\.error(function(err, req, res, next){379 if (err instanceof NotFound) {380 res\.render(\'404\.jade\');381 } else {382 next(err);383 }384});385.386.fi387.388.IP "" 0389.390.P391Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like392.393.IP "" 4394.395.nf396397app\.error(function(err, req, res){398 res\.render(\'500\.jade\', {399 locals: {400 error: err401 }402 });403});404.405.fi406.407.IP "" 0408.409.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 410why, one step back
410Our 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 411–415why, one step back
411.
412.IP "" 4413.414.nf415

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 417–428why, one step back
417.
418.fi419.420.IP "" 0421.422.P423Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:424.425.IP "" 4426.427.nf428

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 430–438why, one step back
430.
431.fi432.433.IP "" 0434.435.P436The \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\.437.438.SS "View Rendering"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 439why, one step back
439View 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 440–509why, one step back
440.
441.P442Below 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\.443.444.IP "" 4445.446.nf447448app\.get(\'/\', function(req, res){449 res\.render(\'index\.haml\', {450 locals: { title: \'My Site\' }451 });452});453.454.fi455.456.IP "" 0457.458.P459The 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:460.461.IP "" 4462.463.nf464465app\.set(\'view engine\', \'jade\');466.467.fi468.469.IP "" 0470.471.P472Allowing us to render with:473.474.IP "" 4475.476.nf477478res\.render(\'index\');479.480.fi481.482.IP "" 0483.484.P485vs:486.487.IP "" 4488.489.nf490491res\.render(\'index\.jade\');492.493.fi494.495.IP "" 0496.497.P498When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:499.500.IP "" 4501.502.nf503504res\.render(\'another\-page\.ejs\');505.506.fi507.508.IP "" 0509.

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 510–553why, one step back
510.P
511Express 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:512.513.IP "" 4514.515.nf516517app\.set(\'view options\', {518 layout: false519});520.521.fi522.523.IP "" 0524.525.P526Which can then be overridden within the \fBres\.render()\fR call if need be:527.528.IP "" 4529.530.nf531532res\.render(\'myview\.ejs\', { layout: true });533.534.fi535.536.IP "" 0537.538.P539A good example of this is specifying custom \fIejs\fR opening and closing tags:540.541.IP "" 4542.543.nf544545app\.set(\'view options\', {546 open: \'{{\',547 close: \'}}\'548});549.550.fi551.552.IP "" 0553.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 555why, one step back
555The 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 556–593why, one step back
556.
557.IP "" 4558.559.nf560561partial(\'comment\.haml\', { collection: comments });562.563.fi564.565.IP "" 0566.567.P568To 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\.569.570.IP "" 4571.572.nf573574partial(\'comment\', { collection: comments });575.576.fi577.578.IP "" 0579.580.P581And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:582.583.IP "" 4584.585.nf586587partial(\'comments\', comments);588.589.fi590.591.IP "" 0592.593.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 595–602why, one step back
595.
596.IP "\(bu" 4597\fIfirstInCollection\fR True if this is the first object598.599.IP "\(bu" 4600\fIindexInCollection\fR Index of the object in the collection601.602.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 604–610why, one step back
604.
605.IP "" 0606.607.SS "Template Engines"608Below are a few template engines commonly used with Express:609.610.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 612–613why, one step back
612.
613.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 615–639why, one step back
615.
616.IP "\(bu" 4617EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript618.619.IP "" 0620.621.SS "req\.header(key[, defaultValue])"622Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:623.624.IP "" 4625.626.nf627628req\.header(\'Host\');629req\.header(\'host\');630req\.header(\'Accept\', \'*/*\');631.632.fi633.634.IP "" 0635.636.SS "req\.accepts(type)"637Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.638.639.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 640why, one step back
640When 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 641–668why, one step back
641.
642.IP "" 4643.644.nf645646// Accept: text/html647req\.accepts(\'html\');648// => true649650// Accept: text/*; application/json651req\.accepts(\'html\');652req\.accepts(\'text/html\');653req\.accepts(\'text/plain\');654req\.accepts(\'application/json\');655// => true656657req\.accepts(\'image/png\');658req\.accepts(\'png\');659// => false660.661.fi662.663.IP "" 0664.665.SS "req\.param(name)"666Return the value of param \fIname\fR when present\.667.668.IP "\(bu" 4

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 670–671why, one step back
670.
671.IP "\(bu" 4

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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 urlencoded body params (\fIreq\.body\fR), ex: id=12

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 676–679why, one step back
676.
677.IP "" 0678.679.P

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 680why, one step back
680To 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 681–706why, one step back
681.
682.SS "req\.flash(type[, msg])"683Queue flash \fImsg\fR of the given \fItype\fR\.684.685.IP "" 4686.687.nf688689req\.flash(\'info\', \'email sent\');690req\.flash(\'error\', \'email delivery failed\');691req\.flash(\'info\', \'email re\-sent\');692// => 2693694req\.flash(\'info\');695// => [\'email sent\', \'email re\-sent\']696697req\.flash(\'info\');698// => []699700req\.flash();701// => { error: [\'email delivery failed\'], info: [] }702.703.fi704.705.IP "" 0706.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 707–719why, one step back
707.P
708Flash notification message may also utilize formatters, by default only the %s string formatter is available:709.710.IP "" 4711.712.nf713714req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);715.716.fi717.718.IP "" 0719.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 720–762why, one step back
720.SS "req\.isXMLHttpRequest"
721Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:722.723.IP "" 4724.725.nf726727req\.xhr728req\.isXMLHttpRequest729.730.fi731.732.IP "" 0733.734.SS "res\.header(key[, val])"735Get or set the response header \fIkey\fR\.736.737.IP "" 4738.739.nf740741res\.header(\'Content\-Length\');742// => undefined743744res\.header(\'Content\-Length\', 123);745// => 123746747res\.header(\'Content\-Length\');748// => 123749.750.fi751.752.IP "" 0753.754.SS "res\.contentType(type)"755Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.756.757.IP "" 4758.759.nf760761 var filename = \'path/to/image\.png\';762 res\.contentType(filename);

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 764–769why, one step back
764.
765.fi766.767.IP "" 0768.769.SS "res\.attachment([filename])"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 771–832why, one step back
771.
772.IP "" 4773.774.nf775776 res\.attachment(\'path/to/my/image\.png\');777.778.fi779.780.IP "" 0781.782.SS "res\.sendfile(path)"783Used by \fBres\.download()\fR to transfer an arbitrary file\.784.785.IP "" 4786.787.nf788789res\.sendfile(\'path/to/my\.file\');790.791.fi792.793.IP "" 0794.795.P796This is \fInot\fR a substitution for Connect\'s \fIstaticProvider\fR middleware, it does not support HTTP caching, and does not perform any security checks\. This method is utilized by \fIres\.download()\fR to transfer static files, and allows you do to so from outside of the public directory, so suitable security checks should be applied\.797.798.SS "res\.download(file[, filename])"799Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.800.801.IP "" 4802.803.nf804805res\.download(\'path/to/image\.png\');806res\.download(\'path/to/image\.png\', \'foo\.png\');807.808.fi809.810.IP "" 0811.812.P813This is equivalent to:814.815.IP "" 4816.817.nf818819res\.attachment(file);820res\.sendfile(file);821.822.fi823.824.IP "" 0825.826.SS "res\.send(body|status[, headers|status[, status]])"827The \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:828.829.IP "" 4830.831.nf832

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 834–865why, one step back
834 res\.send(new Buffer(\'wahoo\'));
835 res\.send({ some: \'json\' });836 res\.send(\'<p>some html</p>\');837 res\.send(\'Sorry, cant find that\', 404);838 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);839 res\.send(404);840.841.fi842.843.IP "" 0844.845.P846By 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\.847.848.SS "res\.redirect(url[, status])"849Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.850.851.IP "" 4852.853.nf854855res\.redirect(\'/\', 301);856res\.redirect(\'/account\');857res\.redirect(\'http://google\.com\');858res\.redirect(\'home\');859res\.redirect(\'back\');860.861.fi862.863.IP "" 0864.865.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 868–911why, one step back
868.SS "res\.cookie(name, val[, options])"
869Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.870.871.IP "" 4872.873.nf874875// "Remember me" for 15 minutes876res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });877.878.fi879.880.IP "" 0881.882.P883To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:884.885.IP "" 4886.887.nf888889app\.use(express\.cookieDecoder());890891app\.get(\'/\', function(req, res){892 // use req\.cookies\.rememberme893});894.895.fi896.897.IP "" 0898.899.SS "res\.clearCookie(name)"900Clear cookie \fIname\fR by setting "expires" far in the past\.901.902.IP "" 4903.904.nf905906res\.clearCookie(\'rememberme\');907.908.fi909.910.IP "" 0911.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 912–926why, one step back
912.SS "res\.render(view[, options[, fn]])"
913Render \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\.914.915.P916Most 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:917.918.IP "\(bu" 4919\fIcontext|scope\fR Template evaluation context (\fIthis\fR)920.921.IP "\(bu" 4922\fIlocals\fR Object containing local variables923.924.IP "\(bu" 4925\fIdebug\fR Output debugging information926.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 927–932why, one step back
927.IP "\(bu" 4
928\fIstatus\fR Response status code, defaults to 200929.930.IP "\(bu" 4931\fIheaders\fR Response headers object932.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 933–974why, one step back
933.IP "" 0
934.935.SS "res\.partial(view[, options])"936Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.937.938.IP "\(bu" 4939\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.940.941.IP "\(bu" 4942as: \'something\' will add the \fIsomething\fR local variable943.944.IP "\(bu" 4945as: this will use the collection value as the template context946.947.IP "\(bu" 4948as: global will merge the collection value\'s properties with \fIlocals\fR949.950.IP "" 0951952.953.IP "\(bu" 4954\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\.955.956.IP "" 0957.958.P959The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.960.961.IP "" 4962.963.nf964965partial(\'movie\.jade\', { collection: movies });966partial(\'movie\.jade\', movies);967partial(\'movie\', movies);968// In view: movie\.director969.970.fi971.972.IP "" 0973.974.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 976–1002why, one step back
976.
977.IP "" 4978.979.nf980981partial(\'movie\', { collection: movies, as: \'video\' });982// In view: video\.director983.984.fi985.986.IP "" 0987.988.P989Also 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\.990.991.IP "" 4992.993.nf994995partial(\'movie\', { collection: movies, as: this });996// In view: this\.director997.998.fi999.1000.IP "" 01001.1002.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1003why, one step back
1003Another 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 1004–1022why, one step back
1004.
1005.IP "" 41006.1007.nf10081009partials(\'movie\', { collection: movies, as: global });1010// In view: director1011.1012.fi1013.1014.IP "" 01015.1016.SS "app\.set(name[, val])"1017Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1018.1019.IP "" 41020.1021.nf1022

Updated docsTj Holowaychukbefore adoption3234329

lines 1023–1025why, one step back
1023app\.set(\'views\', __dirname + \'/views\');
1024app\.set(\'views\');1025// => \.\.\.path\.\.\.

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 1026–1105why, one step back
1026.
1027.fi1028.1029.IP "" 01030.1031.SS "app\.enable(name)"1032Enable the given setting \fIname\fR:1033.1034.IP "" 41035.1036.nf10371038app\.enable(\'some arbitrary setting\');1039app\.set(\'some arbitrary setting\');1040// => true1041.1042.fi1043.1044.IP "" 01045.1046.SS "app\.disable(name)"1047Disable the given setting \fIname\fR:1048.1049.IP "" 41050.1051.nf10521053app\.disable(\'some setting\');1054app\.set(\'some setting\');1055// => false1056.1057.fi1058.1059.IP "" 01060.1061.SS "app\.configure(env|function[, function])"1062Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1063.1064.IP "" 41065.1066.nf10671068app\.configure(function(){1069 // executed for each env1070});10711072app\.configure(\'development\', function(){1073 // executed for \'development\' only1074});1075.1076.fi1077.1078.IP "" 01079.1080.SS "app\.redirect(name, val)"1081For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1082.1083.IP "" 41084.1085.nf10861087app\.redirect(\'google\', \'http://google\.com\');1088.1089.fi1090.1091.IP "" 01092.1093.P1094Now in a route we may call:1095.1096.P1097res\.redirect(\'google\');1098.1099.P1100We may also map dynamic redirects:1101.1102.IP "" 41103.1104.nf1105

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 1108–1142why, one step back
1108});
1109.1110.fi1111.1112.IP "" 01113.1114.P1115So 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\.1116.1117.IP "" 41118.1119.nf11201121app\.get(\'/post/:id\', function(req, res){1122 res\.redirect(\'comments\');1123});1124.1125.fi1126.1127.IP "" 01128.1129.SS "app\.error(function)"1130Adds 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:1131.1132.IP "" 41133.1134.nf11351136app\.error(function(err, req, res, next){1137 res\.send(err\.message, 500);1138});1139.1140.fi1141.1142.IP "" 0

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

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

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

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 1146–1151why, one step back
1146.
1147.IP "" 41148.1149.nf11501151app\.helpers({

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

lines 1152–1174why, one step back
1152 name: function(first, last){ return first + \', \' + last },
1153 firstName: \'tj\',1154 lastName: \'holowaychuk\'1155});1156.1157.fi1158.1159.IP "" 01160.1161.P1162Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1163.1164.IP "" 41165.1166.nf11671168<%= name(firstName, lastName) %>1169.1170.fi1171.1172.IP "" 01173.1174.SS "app\.dynamicHelpers(obj)"

Updated docsTj Holowaychukbefore adoptiond691ecb

line 1175why, one step back
1175Registers 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 1176–1181why, one step back
1176.
1177.IP "" 41178.1179.nf11801181app\.dynamicHelpers({

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 1183–1191why, one step back
1183 return req\.session;
1184 }1185});1186.1187.fi1188.1189.IP "" 01190.1191.P

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

lines 1192–1198why, one step back
1192All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:
1193.1194.IP "" 41195.1196.nf11971198<%= session\.name %>

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 1199–1215why, one step back
1199.
1200.fi1201.1202.IP "" 01203.1204.SS "app\.mounted(fn)"1205Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1206.1207.IP "" 41208.1209.nf12101211var app = express\.createServer(),1212 blog = express\.createServer();12131214blog\.mounted(function(parent){1215 // parent is app

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 1217–1219why, one step back
1217});
12181219app\.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1220–1225why, one step back
1220.
1221.fi1222.1223.IP "" 01224.1225.SS "app\.register(ext, exports)"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1226why, one step back
1226Register 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 1227–1238why, one step back
1227.
1228.IP "" 41229.1230.nf12311232 app\.register(\'\.html\', require(\'jade\'));1233.1234.fi1235.1236.IP "" 01237.1238.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1239why, one step back
1239This 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 1240–1263why, one step back
1240.
1241.IP "" 41242.1243.nf12441245 app\.register(\'\.haml\', require(\'haml\-js\'));1246.1247.fi1248.1249.IP "" 01250.1251.P1252For engines that do not comply with the Express specification, we can also wrap their api this way\.1253.1254.IP "" 41255.1256.nf12571258 app\.register(\'\.foo\', {1259 render: function(str, options) {1260 // perhaps their api is1261 // foo\.toHTML(str, options);1262 }1263 });

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

lines 1264–1267why, one step back
1264.
1265.fi1266.1267.IP "" 0

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 1268–1316why, one step back
1268.
1269.SS "app\.listen([port[, host]])"1270Bind 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\.1271.1272.IP "" 41273.1274.nf12751276app\.listen();1277app\.listen(3000);1278app\.listen(3000, \'n\.n\.n\.n\');1279.1280.fi1281.1282.IP "" 01283.1284.P1285The \fIport\fR argument may also be a string representing the path to a unix domain socket:1286.1287.IP "" 41288.1289.nf12901291app\.listen(\'/tmp/express\.sock\');1292.1293.fi1294.1295.IP "" 01296.1297.P1298Then try it out:1299.1300.IP "" 41301.1302.nf13031304$ telnet /tmp/express\.sock1305GET / HTTP/1\.113061307HTTP/1\.1 200 OK1308Content\-Type: text/plain1309Content\-Length: 1113101311Hello World1312.1313.fi1314.1315.IP "" 01316