Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,700 lines · 34.2 KiB

Last changed by

Regenerated docsTj Holowaychukbefore adoption334a18a

History of this file

Take it

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

line 3why, one step back
3.

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

line 5why, one step back
5.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9

line 10why, one step back
10curl:

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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:

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 129–140why, one step back
129.
130.fi131.132.IP "" 0133.134.SS "Settings"135Express supports the following settings out of the box:136.137.IP "\(bu" 4138\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR139.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\.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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]

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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"

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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"

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Regenerated docsTj Holowaychukbefore adoption334a18a

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 285–453why, one step back
285.
286.SS "Route Middleware"287Routes 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\.288.289.P290Typically async data retrieval might look similar to below, where we take the ":id" parameter, and attempt loading a user\.291.292.P293app\.get(\'/user/:id\', function(req, res, next){294.295.IP "" 4296.297.nf298299 loadUser(req\.params\.id, function(err, user){300 if (err) return next(err);301 res\.send(\'Viewing user \' + user\.name);302 });303.304.fi305.306.IP "" 0307.308.P309});310.311.P312To 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\.313.314.P315function loadUser(req, res, next) {316.317.IP "" 4318.319.nf320321 // You would fetch your user from the db322 var user = users[req\.params\.id];323 if (user) {324 req\.user = user;325 next();326 } else {327 next(new Error(\'Failed to load user \' + req\.params\.id));328 }329.330.fi331.332.IP "" 0333.334.P335}336.337.P338app\.get(\'/user/:id\', loadUser, function(req, res){339.340.IP "" 4341.342.nf343344 res\.send(\'Viewing user \' + req\.user\.name);345.346.fi347.348.IP "" 0349.350.P351});352.353.P354Multiple 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\.355.356.P357function andRestrictToSelf(req, res, next) {358.359.IP "" 4360.361.nf362363 req\.authenticatedUser\.id == req\.user\.id364 ? next()365 : next(new Error(\'Unauthorized\'));366.367.fi368.369.IP "" 0370.371.P372}373.374.P375app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){376.377.IP "" 4378.379.nf380381 res\.send(\'Editing user \' + req\.user\.name);382.383.fi384.385.IP "" 0386.387.P388});389.390.P391Keeping 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\.392.393.P394function andRestrictTo(role) {395.396.IP "" 4397.398.nf399400 return function(req, res, next) {401 req\.authenticatedUser\.role == role402 ? next()403 : next(new Error(\'Unauthorized\'));404 }405.406.fi407.408.IP "" 0409.410.P411}412.413.P414app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){415.416.IP "" 4417.418.nf419420 res\.send(\'Deleted user \' + req\.user\.name);421.422.fi423.424.IP "" 0425.426.P427});428.429.P430Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.431.432.P433var a = [middleware1, middleware2]434.435.IP "" 4436.437.nf438439, b = [middleware3, middleware4]440, all = [a, b];441.442.fi443.444.IP "" 0445.446.P447app\.get(\'/foo\', a, function(){}); app\.get(\'/bar\', a, function(){});448.449.P450app\.get(\'/\', a, middleware3, middleware4, function(){}); app\.get(\'/\', a, b, function(){}); app\.get(\'/\', all, function(){});451.452.P453For 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\.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

line 454why, one step back
454.

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 455–542why, one step back
455.SS "HTTP Methods"
456We 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\.457.458.P459A 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\.460.461.P462.463.IP "" 4464.465.nf466467 <input type="text" name="user[name]" />468 <input type="text" name="user[email]" />469 <input type="submit" value="Submit" />470.471.fi472.473.IP "" 0474.475.P476.477.P478By 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:479.480.IP "" 4481.482.nf483484app\.use(express\.bodyDecoder());485.486.fi487.488.IP "" 0489.490.P491Our 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\.492.493.IP "" 4494.495.nf496497app\.post(\'/\', function(req, res){498 console\.log(req\.body\.user);499 res\.redirect(\'back\');500});501.502.fi503.504.IP "" 0505.506.P507When 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\.508.509.IP "" 4510.511.nf512513app\.use(express\.bodyDecoder());514app\.use(express\.methodOverride());515.516.fi517.518.IP "" 0519.520.P521The 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:522.523.IP "" 4524.525.nf526527<form method="post" action="/">528 <input type="hidden" name="_method" value="put" />529 <input type="text" name="user[name]" />530 <input type="text" name="user[email]" />531 <input type="submit" value="Submit" />532</form>533534app\.put(\'/\', function(){535 console\.log(req\.body\.user);536 res\.redirect(\'back\');537});538.539.fi540.541.IP "" 0542.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

line 543why, one step back
543.SS "Middleware"

Rebuilt docsTj Holowaychukbefore adoption2724ce3

line 544why, one step back
544Middleware 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:

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 545–549why, one step back
545.
546.IP "" 4547.548.nf549

Rebuilt docsTj Holowaychukbefore adoption2724ce3

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 551–552why, one step back
551
552var app = express\.createServer(

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 553–554why, one step back
553 express\.logger(),
554 express\.bodyDecoder()

Rebuilt docsTj Holowaychukbefore adoption2724ce3

line 555why, one step back
555 );

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 556–567why, one step back
556.
557.fi558.559.IP "" 0560.561.P562Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:563.564.IP "" 4565.566.nf567

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 569–573why, one step back
569.
570.fi571.572.IP "" 0573.

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 574–600why, one step back
574.P
575Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:576.577.IP "" 4578.579.nf580581var connect = require(\'connect\');582app\.use(connect\.logger());583.584.fi585.586.IP "" 0587.588.P589This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:590.591.IP "" 4592.593.nf594595app\.use(express\.logger());596.597.fi598.599.IP "" 0600.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 601–630why, one step back
601.SS "Error Handling"
602Express 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:603.604.IP "" 4605.606.nf607608function NotFound(msg){609 this\.name = \'NotFound\';610 Error\.call(this, msg);611 Error\.captureStackTrace(this, arguments\.callee);612}613614sys\.inherits(NotFound, Error);615616app\.get(\'/404\', function(req, res){617 throw new NotFound;618});619620app\.get(\'/500\', function(req, res){621 throw new Error(\'keyboard cat!\');622});623.624.fi625.626.IP "" 0627.628.P629We 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\.630.

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 631–633why, one step back
631.P
632Note 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\.633.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 634–669why, one step back
634.IP "" 4
635.636.nf637638app\.error(function(err, req, res, next){639 if (err instanceof NotFound) {640 res\.render(\'404\.jade\');641 } else {642 next(err);643 }644});645.646.fi647.648.IP "" 0649.650.P651Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like652.653.IP "" 4654.655.nf656657app\.error(function(err, req, res){658 res\.render(\'500\.jade\', {659 locals: {660 error: err661 }662 });663});664.665.fi666.667.IP "" 0668.669.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 671–675why, one step back
671.
672.IP "" 4673.674.nf675

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 677–688why, one step back
677.
678.fi679.680.IP "" 0681.682.P683Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:684.685.IP "" 4686.687.nf688

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 690–698why, one step back
690.
691.fi692.693.IP "" 0694.695.P696The \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\.697.698.SS "View Rendering"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 700–769why, one step back
700.
701.P702Below 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\.703.704.IP "" 4705.706.nf707708app\.get(\'/\', function(req, res){709 res\.render(\'index\.haml\', {710 locals: { title: \'My Site\' }711 });712});713.714.fi715.716.IP "" 0717.718.P719The 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:720.721.IP "" 4722.723.nf724725app\.set(\'view engine\', \'jade\');726.727.fi728.729.IP "" 0730.731.P732Allowing us to render with:733.734.IP "" 4735.736.nf737738res\.render(\'index\');739.740.fi741.742.IP "" 0743.744.P745vs:746.747.IP "" 4748.749.nf750751res\.render(\'index\.jade\');752.753.fi754.755.IP "" 0756.757.P758When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:759.760.IP "" 4761.762.nf763764res\.render(\'another\-page\.ejs\');765.766.fi767.768.IP "" 0769.

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 770–798why, one step back
770.P
771Express 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:772.773.IP "" 4774.775.nf776777app\.set(\'view options\', {778 layout: false779});780.781.fi782.783.IP "" 0784.785.P786Which can then be overridden within the \fBres\.render()\fR call if need be:787.788.IP "" 4789.790.nf791792res\.render(\'myview\.ejs\', { layout: true });793.794.fi795.796.IP "" 0797.798.P

Rebuilt docsTj Holowaychukbefore adoption2724ce3

lines 799–837why, one step back
799When 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:
800.801.IP "" 4802.803.nf804805res\.render(\'page\', { layout: \'mylayout\' });806.807.fi808.809.IP "" 0810.811.P812Otherwise we must specify the extension:813.814.IP "" 4815.816.nf817818res\.render(\'page\', { layout: \'mylayout\.jade\' });819.820.fi821.822.IP "" 0823.824.P825These paths may also be absolute:826.827.IP "" 4828.829.nf830831res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });832.833.fi834.835.IP "" 0836.837.P

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 838–852why, one step back
838A good example of this is specifying custom \fIejs\fR opening and closing tags:
839.840.IP "" 4841.842.nf843844app\.set(\'view options\', {845 open: \'{{\',846 close: \'}}\'847});848.849.fi850.851.IP "" 0852.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 855–892why, one step back
855.
856.IP "" 4857.858.nf859860partial(\'comment\.haml\', { collection: comments });861.862.fi863.864.IP "" 0865.866.P867To 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\.868.869.IP "" 4870.871.nf872873partial(\'comment\', { collection: comments });874.875.fi876.877.IP "" 0878.879.P880And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:881.882.IP "" 4883.884.nf885886partial(\'comments\', comments);887.888.fi889.890.IP "" 0891.892.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 894–901why, one step back
894.
895.IP "\(bu" 4896\fIfirstInCollection\fR True if this is the first object897.898.IP "\(bu" 4899\fIindexInCollection\fR Index of the object in the collection900.901.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 903–909why, one step back
903.
904.IP "" 0905.906.SS "Template Engines"907Below are a few template engines commonly used with Express:908.909.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 911–912why, one step back
911.
912.IP "\(bu" 4

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 914–916why, one step back
914.
915.IP "\(bu" 4916EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript

Rebuilt docsTj Holowaychukbefore adoption2724ce3

lines 917–945why, one step back
917.
918.IP "" 0919.920.SS "Session Support"921Sessions 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\.922.923.IP "" 4924.925.nf926927app\.use(express\.cookieDecoder());928app\.use(express\.session());929.930.fi931.932.IP "" 0933.934.P935By 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:936.937.IP "" 4938.939.nf940941var RedisStore = require(\'connect\-redis\');942app\.use(express\.cookieDecoder());943app\.use(express\.session({ store: new RedisStore }));944.945.fi

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 946–948why, one step back
946.
947.IP "" 0948.

Regenerated guideTj Holowaychukbefore adoptionf179979

lines 949–985why, one step back
949.P
950Now 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:951.952.IP "" 4953.954.nf955956var RedisStore = require(\'connect\-redis\');957app\.use(express\.cookieDecoder());958app\.use(express\.session({ store: new RedisStore }));959app\.use(express\.bodyDecoder());960961app\.post(\'/add\-to\-cart\', function(req, res){962 // Perhaps we posted several items with a form963 // (use the bodyDecoder() middleware for this)964 var items = req\.body\.items;965 req\.session\.items = items;966 res\.redirect(\'back\');967});968969app\.get(\'/add\-to\-cart\', function(req, res){970 // When redirected back to GET /add\-to\-cart971 // we could check req\.session\.items && req\.session\.items\.length972 // to print out a message973 if (req\.session\.items && req\.session\.items\.length) {974 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);975 }976 res\.render(\'shopping\-cart\');977});978.979.fi980.981.IP "" 0982.983.P984The \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\.985.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 986–1004why, one step back
986.SS "req\.header(key[, defaultValue])"
987Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:988.989.IP "" 4990.991.nf992993req\.header(\'Host\');994req\.header(\'host\');995req\.header(\'Accept\', \'*/*\');996.997.fi998.999.IP "" 01000.1001.SS "req\.accepts(type)"1002Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1003.1004.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1006–1033why, one step back
1006.
1007.IP "" 41008.1009.nf10101011// Accept: text/html1012req\.accepts(\'html\');1013// => true10141015// Accept: text/*; application/json1016req\.accepts(\'html\');1017req\.accepts(\'text/html\');1018req\.accepts(\'text/plain\');1019req\.accepts(\'application/json\');1020// => true10211022req\.accepts(\'image/png\');1023req\.accepts(\'png\');1024// => false1025.1026.fi1027.1028.IP "" 01029.1030.SS "req\.param(name)"1031Return the value of param \fIname\fR when present\.1032.1033.IP "\(bu" 4

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1035–1036why, one step back
1035.
1036.IP "\(bu" 4

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1038–1039why, one step back
1038.
1039.IP "\(bu" 4

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1041–1044why, one step back
1041.
1042.IP "" 01043.1044.P

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1046–1071why, one step back
1046.
1047.SS "req\.flash(type[, msg])"1048Queue flash \fImsg\fR of the given \fItype\fR\.1049.1050.IP "" 41051.1052.nf10531054req\.flash(\'info\', \'email sent\');1055req\.flash(\'error\', \'email delivery failed\');1056req\.flash(\'info\', \'email re\-sent\');1057// => 210581059req\.flash(\'info\');1060// => [\'email sent\', \'email re\-sent\']10611062req\.flash(\'info\');1063// => []10641065req\.flash();1066// => { error: [\'email delivery failed\'], info: [] }1067.1068.fi1069.1070.IP "" 01071.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1072–1084why, one step back
1072.P
1073Flash notification message may also utilize formatters, by default only the %s string formatter is available:1074.1075.IP "" 41076.1077.nf10781079req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1080.1081.fi1082.1083.IP "" 01084.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1085–1127why, one step back
1085.SS "req\.isXMLHttpRequest"
1086Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1087.1088.IP "" 41089.1090.nf10911092req\.xhr1093req\.isXMLHttpRequest1094.1095.fi1096.1097.IP "" 01098.1099.SS "res\.header(key[, val])"1100Get or set the response header \fIkey\fR\.1101.1102.IP "" 41103.1104.nf11051106res\.header(\'Content\-Length\');1107// => undefined11081109res\.header(\'Content\-Length\', 123);1110// => 12311111112res\.header(\'Content\-Length\');1113// => 1231114.1115.fi1116.1117.IP "" 01118.1119.SS "res\.contentType(type)"1120Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1121.1122.IP "" 41123.1124.nf11251126 var filename = \'path/to/image\.png\';1127 res\.contentType(filename);

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1129–1134why, one step back
1129.
1130.fi1131.1132.IP "" 01133.1134.SS "res\.attachment([filename])"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1136–1160why, one step back
1136.
1137.IP "" 41138.1139.nf11401141 res\.attachment(\'path/to/my/image\.png\');1142.1143.fi1144.1145.IP "" 01146.1147.SS "res\.sendfile(path)"1148Used by \fBres\.download()\fR to transfer an arbitrary file\.1149.1150.IP "" 41151.1152.nf11531154res\.sendfile(\'path/to/my\.file\');1155.1156.fi1157.1158.IP "" 01159.1160.P

Updated docsTj Holowaychukbefore adoptionf0eab06

lines 1161–1180why, one step back
1161This 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\.
1162.1163.IP "" 41164.1165.nf11661167res\.sendfile(path, function(err, path){1168 if (err) {1169 // handle the error1170 } else {1171 console\.log(\'transferred %s\', path);1172 }1173});1174.1175.fi1176.1177.IP "" 01178.1179.P1180When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1181–1216why, one step back
1181.
1182.SS "res\.download(file[, filename])"1183Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1184.1185.IP "" 41186.1187.nf11881189res\.download(\'path/to/image\.png\');1190res\.download(\'path/to/image\.png\', \'foo\.png\');1191.1192.fi1193.1194.IP "" 01195.1196.P1197This is equivalent to:1198.1199.IP "" 41200.1201.nf12021203res\.attachment(file);1204res\.sendfile(file);1205.1206.fi1207.1208.IP "" 01209.1210.SS "res\.send(body|status[, headers|status[, status]])"1211The \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:1212.1213.IP "" 41214.1215.nf1216

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1218–1249why, one step back
1218 res\.send(new Buffer(\'wahoo\'));
1219 res\.send({ some: \'json\' });1220 res\.send(\'<p>some html</p>\');1221 res\.send(\'Sorry, cant find that\', 404);1222 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1223 res\.send(404);1224.1225.fi1226.1227.IP "" 01228.1229.P1230By 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\.1231.1232.SS "res\.redirect(url[, status])"1233Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1234.1235.IP "" 41236.1237.nf12381239res\.redirect(\'/\', 301);1240res\.redirect(\'/account\');1241res\.redirect(\'http://google\.com\');1242res\.redirect(\'home\');1243res\.redirect(\'back\');1244.1245.fi1246.1247.IP "" 01248.1249.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

line 1251why, one step back
1251.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1252–1295why, one step back
1252.SS "res\.cookie(name, val[, options])"
1253Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1254.1255.IP "" 41256.1257.nf12581259// "Remember me" for 15 minutes1260res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1261.1262.fi1263.1264.IP "" 01265.1266.P1267To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1268.1269.IP "" 41270.1271.nf12721273app\.use(express\.cookieDecoder());12741275app\.get(\'/\', function(req, res){1276 // use req\.cookies\.rememberme1277});1278.1279.fi1280.1281.IP "" 01282.1283.SS "res\.clearCookie(name)"1284Clear cookie \fIname\fR by setting "expires" far in the past\.1285.1286.IP "" 41287.1288.nf12891290res\.clearCookie(\'rememberme\');1291.1292.fi1293.1294.IP "" 01295.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1296–1302why, one step back
1296.SS "res\.render(view[, options[, fn]])"
1297Render \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\.1298.1299.P1300Most 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:1301.1302.IP "\(bu" 4

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1304–1310why, one step back
1304.
1305.IP "\(bu" 41306\fIlocals\fR Object containing local variables1307.1308.IP "\(bu" 41309\fIdebug\fR Output debugging information1310.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1311–1316why, one step back
1311.IP "\(bu" 4
1312\fIstatus\fR Response status code, defaults to 2001313.1314.IP "\(bu" 41315\fIheaders\fR Response headers object1316.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1317–1358why, one step back
1317.IP "" 0
1318.1319.SS "res\.partial(view[, options])"1320Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1321.1322.IP "\(bu" 41323\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.1324.1325.IP "\(bu" 41326as: \'something\' will add the \fIsomething\fR local variable1327.1328.IP "\(bu" 41329as: this will use the collection value as the template context1330.1331.IP "\(bu" 41332as: global will merge the collection value\'s properties with \fIlocals\fR1333.1334.IP "" 013351336.1337.IP "\(bu" 41338\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\.1339.1340.IP "" 01341.1342.P1343The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1344.1345.IP "" 41346.1347.nf13481349partial(\'movie\.jade\', { collection: movies });1350partial(\'movie\.jade\', movies);1351partial(\'movie\', movies);1352// In view: movie\.director1353.1354.fi1355.1356.IP "" 01357.1358.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1360–1386why, one step back
1360.
1361.IP "" 41362.1363.nf13641365partial(\'movie\', { collection: movies, as: \'video\' });1366// In view: video\.director1367.1368.fi1369.1370.IP "" 01371.1372.P1373Also 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\.1374.1375.IP "" 41376.1377.nf13781379partial(\'movie\', { collection: movies, as: this });1380// In view: this\.director1381.1382.fi1383.1384.IP "" 01385.1386.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1388–1406why, one step back
1388.
1389.IP "" 41390.1391.nf13921393partials(\'movie\', { collection: movies, as: global });1394// In view: director1395.1396.fi1397.1398.IP "" 01399.1400.SS "app\.set(name[, val])"1401Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1402.1403.IP "" 41404.1405.nf1406

Updated docsTj Holowaychukbefore adoption3234329

lines 1407–1409why, one step back
1407app\.set(\'views\', __dirname + \'/views\');
1408app\.set(\'views\');1409// => \.\.\.path\.\.\.

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1410–1489why, one step back
1410.
1411.fi1412.1413.IP "" 01414.1415.SS "app\.enable(name)"1416Enable the given setting \fIname\fR:1417.1418.IP "" 41419.1420.nf14211422app\.enable(\'some arbitrary setting\');1423app\.set(\'some arbitrary setting\');1424// => true1425.1426.fi1427.1428.IP "" 01429.1430.SS "app\.disable(name)"1431Disable the given setting \fIname\fR:1432.1433.IP "" 41434.1435.nf14361437app\.disable(\'some setting\');1438app\.set(\'some setting\');1439// => false1440.1441.fi1442.1443.IP "" 01444.1445.SS "app\.configure(env|function[, function])"1446Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1447.1448.IP "" 41449.1450.nf14511452app\.configure(function(){1453 // executed for each env1454});14551456app\.configure(\'development\', function(){1457 // executed for \'development\' only1458});1459.1460.fi1461.1462.IP "" 01463.1464.SS "app\.redirect(name, val)"1465For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1466.1467.IP "" 41468.1469.nf14701471app\.redirect(\'google\', \'http://google\.com\');1472.1473.fi1474.1475.IP "" 01476.1477.P1478Now in a route we may call:1479.1480.P1481res\.redirect(\'google\');1482.1483.P1484We may also map dynamic redirects:1485.1486.IP "" 41487.1488.nf1489

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1492–1558why, one step back
1492});
1493.1494.fi1495.1496.IP "" 01497.1498.P1499So 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\.1500.1501.IP "" 41502.1503.nf15041505app\.get(\'/post/:id\', function(req, res){1506 res\.redirect(\'comments\');1507});1508.1509.fi1510.1511.IP "" 01512.1513.SS "app\.error(function)"1514Adds 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:1515.1516.IP "" 41517.1518.nf15191520app\.error(function(err, req, res, next){1521 res\.send(err\.message, 500);1522});1523.1524.fi1525.1526.IP "" 01527.1528.SS "app\.helpers(obj)"1529Registers static view helpers\.1530.1531.IP "" 41532.1533.nf15341535app\.helpers({1536 name: function(first, last){ return first + \', \' + last },1537 firstName: \'tj\',1538 lastName: \'holowaychuk\'1539});1540.1541.fi1542.1543.IP "" 01544.1545.P1546Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1547.1548.IP "" 41549.1550.nf15511552<%= name(firstName, lastName) %>1553.1554.fi1555.1556.IP "" 01557.1558.SS "app\.dynamicHelpers(obj)"

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1560–1565why, one step back
1560.
1561.IP "" 41562.1563.nf15641565app\.dynamicHelpers({

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1567–1582why, one step back
1567 return req\.session;
1568 }1569});1570.1571.fi1572.1573.IP "" 01574.1575.P1576All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1577.1578.IP "" 41579.1580.nf15811582<%= session\.name %>

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 1583–1599why, one step back
1583.
1584.fi1585.1586.IP "" 01587.1588.SS "app\.mounted(fn)"1589Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1590.1591.IP "" 41592.1593.nf15941595var app = express\.createServer(),1596 blog = express\.createServer();15971598blog\.mounted(function(parent){1599 // parent is app

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 1601–1603why, one step back
1601});
16021603app\.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1604–1609why, one step back
1604.
1605.fi1606.1607.IP "" 01608.1609.SS "app\.register(ext, exports)"

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1610why, one step back
1610Register 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 1611–1622why, one step back
1611.
1612.IP "" 41613.1614.nf16151616 app\.register(\'\.html\', require(\'jade\'));1617.1618.fi1619.1620.IP "" 01621.1622.P

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 1623why, one step back
1623This 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 1624–1647why, one step back
1624.
1625.IP "" 41626.1627.nf16281629 app\.register(\'\.haml\', require(\'haml\-js\'));1630.1631.fi1632.1633.IP "" 01634.1635.P1636For engines that do not comply with the Express specification, we can also wrap their api this way\.1637.1638.IP "" 41639.1640.nf16411642 app\.register(\'\.foo\', {1643 render: function(str, options) {1644 // perhaps their api is1645 // foo\.toHTML(str, options);1646 }1647 });

Split blog example into another fileTj Holowaychukbefore adoptiona65c203

lines 1648–1700why, one step back
1648.
1649.fi1650.1651.IP "" 01652.1653.SS "app\.listen([port[, host]])"1654Bind 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\.1655.1656.IP "" 41657.1658.nf16591660app\.listen();1661app\.listen(3000);1662app\.listen(3000, \'n\.n\.n\.n\');1663.1664.fi1665.1666.IP "" 01667.1668.P1669The \fIport\fR argument may also be a string representing the path to a unix domain socket:1670.1671.IP "" 41672.1673.nf16741675app\.listen(\'/tmp/express\.sock\');1676.1677.fi1678.1679.IP "" 01680.1681.P1682Then try it out:1683.1684.IP "" 41685.1686.nf16871688$ telnet /tmp/express\.sock1689GET / HTTP/1\.116901691HTTP/1\.1 200 OK1692Content\-Type: text/plain1693Content\-Length: 1116941695Hello World1696.1697.fi1698.1699.IP "" 01700