guide.1
This file
Path
docs/guide.1
1,645 lines · 34.2 KiB
Last changed by
Regenerated guideTj Holowaychukbefore adoptionab3337d
History of this fileTake 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 back1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.3Split blog example into another fileTj Holowaychukbefore adoptiona65c203
line 3why, one step back3.HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
line 4why, one step back4.TH "GUIDE" "" "October 2010" "" ""Split blog example into another fileTj Holowaychukbefore adoptiona65c203
line 5why, one step back5.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 6–8why, one step back6.SH "NAME"7\fBguide\fR8.Split blog example into another fileTj Holowaychukbefore adoptiona65c203
line 9why, one step back9.SS "Installation"No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9
line 10why, one step back10curl:Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 11–72why, one step back11.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.PUpdated configuration docsTj Holowaychukbefore adoptionf8ccaa3
line 73why, one step back73In 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 back74.75.IP "" 476.77.nf7879app\.configure(function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 80–81why, one step back80 app\.use(express\.methodOverride());81 app\.use(express\.bodyDecoder());Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
line 82why, one step back82 app\.use(app\.router);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 83why, one step back83 app\.use(express\.staticProvider(__dirname + \'/public\'));Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 84–86why, one step back84});8586app\.configure(\'development\', function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 87why, one step back87 app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 88–90why, one step back88});8990app\.configure(\'production\', function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 91why, one step back91 app\.use(express\.errorHandler());Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 92–107why, one step back92});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 back108 // => "\.\.\. views directory \.\.\."Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 109–121why, one step back109110 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.PRebuilt docsTj Holowaychukbefore adoption2724ce3
line 122why, one step back122To 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 back123.124.IP "" 4125.126.nf127Rebuilt docsTj Holowaychukbefore adoption2724ce3
line 128why, one step back128$ NODE_ENV=production node app\.jsSplit blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 129–140why, one step back129.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" 4New "home" docsTj Holowaychukbefore adoption1e7a12f
line 141why, one step back141\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 back142.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 back149.IP "\(bu" 4150\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 back155.IP "\(bu" 4156\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 back158.IP "" 0159.160.SS "Routing"Updated docsTj Holowaychukbefore adoptiond691ecb
line 161why, one step back161Express 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 back162.163.IP "" 4164.165.nf166Updated docsTj Holowaychukbefore adoptiond691ecb
lines 167–168why, one step back167app\.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 back169});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.nf181Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 182why, one step back182\e/user\e/([^\e/]+)\e/?Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 183–188why, one step back183.184.fi185.186.IP "" 0187.188.PUpdated docsTj Holowaychukbefore adoptiond691ecb
line 189why, one step back189Regular 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 back190.191.IP "" 4192.193.nf194Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 195why, one step back195app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){Updated docsTj Holowaychukbefore adoptiond691ecb
line 196why, one step back196 res\.send(req\.params);Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 197–214why, one step back197});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/1Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 215why, one step back215 ["1",null]Split blog example into another fileTj Holowaychukbefore adoptiona65c203
line 216why, one step back216 $ curl http://dev:3000/users/1\.\.15Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 217why, one step back217 ["1","15"]Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 218–229why, one step back218.219.fi220.221.IP "" 0222.223.P224Below are some route examples, and the associated paths that they may consume:225.226.IP "" 4227.228.nf229Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 230why, one step back230 "/user/:id"Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 231–232why, one step back231 /user/12232Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 233why, one step back233 "/users/:id?"Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 234–236why, one step back234 /users/5235 /users236Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 237why, one step back237 "/files/*"Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 238–240why, one step back238 /files/jquery\.js239 /files/javascripts/jquery\.js240Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 241why, one step back241 "/file/*\.*"Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 242–244why, one step back242 /files/jquery\.js243 /files/javascripts/jquery\.js244Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 245why, one step back245 "/user/:id/:operation?"Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 246–248why, one step back246 /user/1247 /user/1/edit248Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 249why, one step back249 "/products\.:format"Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 250–252why, one step back250 /products\.json251 /products\.xml252Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 253why, one step back253 "/products\.:format?"Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 254–262why, one step back254 /products\.json255 /products\.xml256 /products257.258.fi259.260.IP "" 0261.262.SS "Passing Route Control"Regenerated docsTj Holowaychukbefore adoption334a18a
line 263why, one step back263We 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 back264.265.IP "" 4266.267.nf268Updated docsTj Holowaychukbefore adoptionb819366
line 269why, one step back269app\.get(\'/users/:id?\', function(req, res, next){Updated docsTj Holowaychukbefore adoptiond691ecb
lines 270–271why, one step back270 var id = req\.params\.id;271 if (id) {Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 272–277why, one step back272 // do something273 } else {274 next();275 }276});277Updated docsTj Holowaychukbefore adoptiond691ecb
line 278why, one step back278app\.get(\'/users\', function(req, res){Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 279–284why, one step back279 // do something else280});281.282.fi283.284.IP "" 0Regenerated docsTj Holowaychukbefore adoption334a18a
line 285why, one step back285.Regenerated docsTj Holowaychukbefore adoption090debe
lines 286–343why, one step back286.SS "Middleware"287Middleware 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:288.289.IP "" 4290.291.nf292293 var express = require(\'express\');294295var app = express\.createServer(296 express\.logger(),297 express\.bodyDecoder()298 );299.300.fi301.302.IP "" 0303.304.P305Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:306.307.IP "" 4308.309.nf310311app\.use(express\.logger({ format: \':method :uri\' }));312.313.fi314.315.IP "" 0316.317.P318Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:319.320.IP "" 4321.322.nf323324var connect = require(\'connect\');325app\.use(connect\.logger());326.327.fi328.329.IP "" 0330.331.P332This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:333.334.IP "" 4335.336.nf337338app\.use(express\.logger());339.340.fi341.342.IP "" 0343.Regenerated docsTj Holowaychukbefore adoption334a18a
lines 344–347why, one step back344.SS "Route Middleware"345Routes 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\.346.347.PRegenerated docsTj Holowaychukbefore adoption0faac20
line 348why, one step back348Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.Regenerated docsTj Holowaychukbefore adoption334a18a
lines 349–353why, one step back349.350.IP "" 4351.352.nf353Regenerated docsTj Holowaychukbefore adoption0faac20
lines 354–355why, one step back354app\.get(\'/user/:id\', function(req, res, next){355 loadUser(req\.params\.id, function(err, user){Regenerated guideTj Holowaychukbefore adoptionab3337d
lines 356–357why, one step back356 if (err) return next(err);357 res\.send(\'Viewing user \' + user\.name);Regenerated docsTj Holowaychukbefore adoption0faac20
lines 358–359why, one step back358 });359});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 360–371why, one step back360.361.fi362.363.IP "" 0364.365.P366To 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\.367.368.IP "" 4369.370.nf371Regenerated docsTj Holowaychukbefore adoption0faac20
lines 372–380why, one step back372function loadUser(req, res, next) {373 // You would fetch your user from the db374 var user = users[req\.params\.id];375 if (user) {376 req\.user = user;377 next();378 } else {379 next(new Error(\'Failed to load user \' + req\.params\.id));380 }Regenerated docsTj Holowaychukbefore adoption334a18a
line 381why, one step back381}Regenerated docsTj Holowaychukbefore adoption0faac20
line 382why, one step back382Regenerated docsTj Holowaychukbefore adoption334a18a
line 383why, one step back383app\.get(\'/user/:id\', loadUser, function(req, res){Regenerated docsTj Holowaychukbefore adoption0faac20
lines 384–385why, one step back384 res\.send(\'Viewing user \' + req\.user\.name);385});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 386–397why, one step back386.387.fi388.389.IP "" 0390.391.P392Multiple 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\.393.394.IP "" 4395.396.nf397Regenerated docsTj Holowaychukbefore adoption0faac20
lines 398–399why, one step back398function andRestrictToSelf(req, res, next) {399 req\.authenticatedUser\.id == req\.user\.idRegenerated guideTj Holowaychukbefore adoptionab3337d
lines 400–401why, one step back400 ? next()401 : next(new Error(\'Unauthorized\'));Regenerated docsTj Holowaychukbefore adoption334a18a
line 402why, one step back402}Regenerated docsTj Holowaychukbefore adoption0faac20
line 403why, one step back403Regenerated docsTj Holowaychukbefore adoption334a18a
line 404why, one step back404app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){Regenerated docsTj Holowaychukbefore adoption0faac20
lines 405–406why, one step back405 res\.send(\'Editing user \' + req\.user\.name);406});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 407–418why, one step back407.408.fi409.410.IP "" 0411.412.P413Keeping 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\.414.415.IP "" 4416.417.nf418Regenerated docsTj Holowaychukbefore adoption0faac20
lines 419–421why, one step back419function andRestrictTo(role) {420 return function(req, res, next) {421 req\.authenticatedUser\.role == roleRegenerated guideTj Holowaychukbefore adoptionab3337d
lines 422–423why, one step back422 ? next()423 : next(new Error(\'Unauthorized\'));Regenerated docsTj Holowaychukbefore adoption0faac20
line 424why, one step back424 }Regenerated docsTj Holowaychukbefore adoption334a18a
line 425why, one step back425}Regenerated docsTj Holowaychukbefore adoption0faac20
line 426why, one step back426Regenerated docsTj Holowaychukbefore adoption334a18a
line 427why, one step back427app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){Regenerated docsTj Holowaychukbefore adoption0faac20
lines 428–429why, one step back428 res\.send(\'Deleted user \' + req\.user\.name);429});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 430–441why, one step back430.431.fi432.433.IP "" 0434.435.P436Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.437.438.IP "" 4439.440.nf441Regenerated docsTj Holowaychukbefore adoption0faac20
lines 442–451why, one step back442var a = [middleware1, middleware2]443 , b = [middleware3, middleware4]444 , all = [a, b];445446app\.get(\'/foo\', a, function(){});447app\.get(\'/bar\', a, function(){});448449app\.get(\'/\', a, middleware3, middleware4, function(){});450app\.get(\'/\', a, b, function(){});451app\.get(\'/\', all, function(){});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 452–458why, one step back452.453.fi454.455.IP "" 0456.457.P458For 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 459why, one step back459.HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 460–469why, one step back460.SS "HTTP Methods"461We 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\.462.463.P464A 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\.465.466.IP "" 4467.468.nf469Regenerated guideTj Holowaychukbefore adoptionab3337d
lines 470–474why, one step back470 <form method="post" action="/">471 <input type="text" name="user[name]" />472 <input type="text" name="user[email]" />473 <input type="submit" value="Submit" />474 </form>HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 475–540why, one step back475.476.fi477.478.IP "" 0479.480.P481By 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:482.483.IP "" 4484.485.nf486487app\.use(express\.bodyDecoder());488.489.fi490.491.IP "" 0492.493.P494Our 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\.495.496.IP "" 4497.498.nf499500app\.post(\'/\', function(req, res){501 console\.log(req\.body\.user);502 res\.redirect(\'back\');503});504.505.fi506.507.IP "" 0508.509.P510When 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\.511.512.IP "" 4513.514.nf515516app\.use(express\.bodyDecoder());517app\.use(express\.methodOverride());518.519.fi520.521.IP "" 0522.523.P524The 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:525.526.IP "" 4527.528.nf529530<form method="post" action="/">531 <input type="hidden" name="_method" value="put" />532 <input type="text" name="user[name]" />533 <input type="text" name="user[email]" />534 <input type="submit" value="Submit" />535</form>536537app\.put(\'/\', function(){538 console\.log(req\.body\.user);539 res\.redirect(\'back\');540});Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 541–545why, one step back541.542.fi543.544.IP "" 0545.Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 546–575why, one step back546.SS "Error Handling"547Express 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:548.549.IP "" 4550.551.nf552553function NotFound(msg){554 this\.name = \'NotFound\';555 Error\.call(this, msg);556 Error\.captureStackTrace(this, arguments\.callee);557}558559sys\.inherits(NotFound, Error);560561app\.get(\'/404\', function(req, res){562 throw new NotFound;563});564565app\.get(\'/500\', function(req, res){566 throw new Error(\'keyboard cat!\');567});568.569.fi570.571.IP "" 0572.573.P574We 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\.575.Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 576–578why, one step back576.P577Note 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\.578.Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 579–614why, one step back579.IP "" 4580.581.nf582583app\.error(function(err, req, res, next){584 if (err instanceof NotFound) {585 res\.render(\'404\.jade\');586 } else {587 next(err);588 }589});590.591.fi592.593.IP "" 0594.595.P596Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like597.598.IP "" 4599.600.nf601602app\.error(function(err, req, res){603 res\.render(\'500\.jade\', {604 locals: {605 error: err606 }607 });608});609.610.fi611.612.IP "" 0613.614.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 615why, one step back615Our 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 616–620why, one step back616.617.IP "" 4618.619.nf620Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 621why, one step back621app\.use(express\.errorHandler({ dumpExceptions: true }));Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 622–633why, one step back622.623.fi624.625.IP "" 0626.627.P628Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:629.630.IP "" 4631.632.nf633Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 634why, one step back634app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 635–643why, one step back635.636.fi637.638.IP "" 0639.640.P641The \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\.642.643.SS "View Rendering"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 644why, one step back644View 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 645–714why, one step back645.646.P647Below 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\.648.649.IP "" 4650.651.nf652653app\.get(\'/\', function(req, res){654 res\.render(\'index\.haml\', {655 locals: { title: \'My Site\' }656 });657});658.659.fi660.661.IP "" 0662.663.P664The 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:665.666.IP "" 4667.668.nf669670app\.set(\'view engine\', \'jade\');671.672.fi673.674.IP "" 0675.676.P677Allowing us to render with:678.679.IP "" 4680.681.nf682683res\.render(\'index\');684.685.fi686.687.IP "" 0688.689.P690vs:691.692.IP "" 4693.694.nf695696res\.render(\'index\.jade\');697.698.fi699.700.IP "" 0701.702.P703When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:704.705.IP "" 4706.707.nf708709res\.render(\'another\-page\.ejs\');710.711.fi712.713.IP "" 0714.Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 715–743why, one step back715.P716Express 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:717.718.IP "" 4719.720.nf721722app\.set(\'view options\', {723 layout: false724});725.726.fi727.728.IP "" 0729.730.P731Which can then be overridden within the \fBres\.render()\fR call if need be:732.733.IP "" 4734.735.nf736737res\.render(\'myview\.ejs\', { layout: true });738.739.fi740.741.IP "" 0742.743.PRebuilt docsTj Holowaychukbefore adoption2724ce3
lines 744–782why, one step back744When 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:745.746.IP "" 4747.748.nf749750res\.render(\'page\', { layout: \'mylayout\' });751.752.fi753.754.IP "" 0755.756.P757Otherwise we must specify the extension:758.759.IP "" 4760.761.nf762763res\.render(\'page\', { layout: \'mylayout\.jade\' });764.765.fi766.767.IP "" 0768.769.P770These paths may also be absolute:771.772.IP "" 4773.774.nf775776res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });777.778.fi779.780.IP "" 0781.782.PAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 783–797why, one step back783A good example of this is specifying custom \fIejs\fR opening and closing tags:784.785.IP "" 4786.787.nf788789app\.set(\'view options\', {790 open: \'{{\',791 close: \'}}\'792});793.794.fi795.796.IP "" 0797.Split blog example into another fileTj Holowaychukbefore adoptiona65c203
line 798why, one step back798.SS "View Partials"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 799why, one step back799The 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 800–837why, one step back800.801.IP "" 4802.803.nf804805partial(\'comment\.haml\', { collection: comments });806.807.fi808.809.IP "" 0810.811.P812To 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\.813.814.IP "" 4815.816.nf817818partial(\'comment\', { collection: comments });819.820.fi821.822.IP "" 0823.824.P825And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:826.827.IP "" 4828.829.nf830831partial(\'comments\', comments);832.833.fi834.835.IP "" 0836.837.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 838why, one step back838When using the partial collection support a few "magic" variables are provided for free:Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 839–846why, one step back839.840.IP "\(bu" 4841\fIfirstInCollection\fR True if this is the first object842.843.IP "\(bu" 4844\fIindexInCollection\fR Index of the object in the collection845.846.IP "\(bu" 4Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 847why, one step back847\fIlastInCollection\fR True if this is the last objectSplit blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 848–854why, one step back848.849.IP "" 0850.851.SS "Template Engines"852Below are a few template engines commonly used with Express:853.854.IP "\(bu" 4Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 855why, one step back855Jade \fIhttp://jade\-lang\.com\fR haml\.js successorSplit blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 856–857why, one step back856.857.IP "\(bu" 4Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 858why, one step back858Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templatesSplit blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 859–861why, one step back859.860.IP "\(bu" 4861EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScriptRebuilt docsTj Holowaychukbefore adoption2724ce3
lines 862–890why, one step back862.863.IP "" 0864.865.SS "Session Support"866Sessions 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\.867.868.IP "" 4869.870.nf871872app\.use(express\.cookieDecoder());873app\.use(express\.session());874.875.fi876.877.IP "" 0878.879.P880By 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:881.882.IP "" 4883.884.nf885886var RedisStore = require(\'connect\-redis\');887app\.use(express\.cookieDecoder());888app\.use(express\.session({ store: new RedisStore }));889.890.fiSplit blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 891–893why, one step back891.892.IP "" 0893.Regenerated guideTj Holowaychukbefore adoptionf179979
lines 894–930why, one step back894.P895Now 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:896.897.IP "" 4898.899.nf900901var RedisStore = require(\'connect\-redis\');902app\.use(express\.cookieDecoder());903app\.use(express\.session({ store: new RedisStore }));904app\.use(express\.bodyDecoder());905906app\.post(\'/add\-to\-cart\', function(req, res){907 // Perhaps we posted several items with a form908 // (use the bodyDecoder() middleware for this)909 var items = req\.body\.items;910 req\.session\.items = items;911 res\.redirect(\'back\');912});913914app\.get(\'/add\-to\-cart\', function(req, res){915 // When redirected back to GET /add\-to\-cart916 // we could check req\.session\.items && req\.session\.items\.length917 // to print out a message918 if (req\.session\.items && req\.session\.items\.length) {919 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);920 }921 res\.render(\'shopping\-cart\');922});923.924.fi925.926.IP "" 0927.928.P929The \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\.930.Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 931–949why, one step back931.SS "req\.header(key[, defaultValue])"932Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:933.934.IP "" 4935.936.nf937938req\.header(\'Host\');939req\.header(\'host\');940req\.header(\'Accept\', \'*/*\');941.942.fi943.944.IP "" 0945.946.SS "req\.accepts(type)"947Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.948.949.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 950why, one step back950When 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 951–978why, one step back951.952.IP "" 4953.954.nf955956// Accept: text/html957req\.accepts(\'html\');958// => true959960// Accept: text/*; application/json961req\.accepts(\'html\');962req\.accepts(\'text/html\');963req\.accepts(\'text/plain\');964req\.accepts(\'application/json\');965// => true966967req\.accepts(\'image/png\');968req\.accepts(\'png\');969// => false970.971.fi972.973.IP "" 0974.975.SS "req\.param(name)"976Return the value of param \fIname\fR when present\.977.978.IP "\(bu" 4Updated docsTj Holowaychukbefore adoptiond691ecb
line 979why, one step back979Checks route placeholders (\fIreq\.params\fR), ex: /user/:idSplit blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 980–981why, one step back980.981.IP "\(bu" 4Updated docsTj Holowaychukbefore adoptiond691ecb
line 982why, one step back982Checks query string params (\fIreq\.query\fR), ex: ?id=12Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 983–984why, one step back983.984.IP "\(bu" 4Updated docsTj Holowaychukbefore adoptiond691ecb
line 985why, one step back985Checks urlencoded body params (\fIreq\.body\fR), ex: id=12Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 986–989why, one step back986.987.IP "" 0988.989.PAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
line 990why, one step back990To 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 991–1016why, one step back991.992.SS "req\.flash(type[, msg])"993Queue flash \fImsg\fR of the given \fItype\fR\.994.995.IP "" 4996.997.nf998999req\.flash(\'info\', \'email sent\');1000req\.flash(\'error\', \'email delivery failed\');1001req\.flash(\'info\', \'email re\-sent\');1002// => 210031004req\.flash(\'info\');1005// => [\'email sent\', \'email re\-sent\']10061007req\.flash(\'info\');1008// => []10091010req\.flash();1011// => { error: [\'email delivery failed\'], info: [] }1012.1013.fi1014.1015.IP "" 01016.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1017–1029why, one step back1017.P1018Flash notification message may also utilize formatters, by default only the %s string formatter is available:1019.1020.IP "" 41021.1022.nf10231024req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1025.1026.fi1027.1028.IP "" 01029.Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1030–1072why, one step back1030.SS "req\.isXMLHttpRequest"1031Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1032.1033.IP "" 41034.1035.nf10361037req\.xhr1038req\.isXMLHttpRequest1039.1040.fi1041.1042.IP "" 01043.1044.SS "res\.header(key[, val])"1045Get or set the response header \fIkey\fR\.1046.1047.IP "" 41048.1049.nf10501051res\.header(\'Content\-Length\');1052// => undefined10531054res\.header(\'Content\-Length\', 123);1055// => 12310561057res\.header(\'Content\-Length\');1058// => 1231059.1060.fi1061.1062.IP "" 01063.1064.SS "res\.contentType(type)"1065Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1066.1067.IP "" 41068.1069.nf10701071 var filename = \'path/to/image\.png\';1072 res\.contentType(filename);Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1073why, one step back1073 // res\.headers[\'Content\-Type\'] is now "image/png"Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1074–1079why, one step back1074.1075.fi1076.1077.IP "" 01078.1079.SS "res\.attachment([filename])"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1080why, one step back1080Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1081–1105why, one step back1081.1082.IP "" 41083.1084.nf10851086 res\.attachment(\'path/to/my/image\.png\');1087.1088.fi1089.1090.IP "" 01091.1092.SS "res\.sendfile(path)"1093Used by \fBres\.download()\fR to transfer an arbitrary file\.1094.1095.IP "" 41096.1097.nf10981099res\.sendfile(\'path/to/my\.file\');1100.1101.fi1102.1103.IP "" 01104.1105.PUpdated docsTj Holowaychukbefore adoptionf0eab06
lines 1106–1125why, one step back1106This 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\.1107.1108.IP "" 41109.1110.nf11111112res\.sendfile(path, function(err, path){1113 if (err) {1114 // handle the error1115 } else {1116 console\.log(\'transferred %s\', path);1117 }1118});1119.1120.fi1121.1122.IP "" 01123.1124.P1125When 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 1126–1161why, one step back1126.1127.SS "res\.download(file[, filename])"1128Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1129.1130.IP "" 41131.1132.nf11331134res\.download(\'path/to/image\.png\');1135res\.download(\'path/to/image\.png\', \'foo\.png\');1136.1137.fi1138.1139.IP "" 01140.1141.P1142This is equivalent to:1143.1144.IP "" 41145.1146.nf11471148res\.attachment(file);1149res\.sendfile(file);1150.1151.fi1152.1153.IP "" 01154.1155.SS "res\.send(body|status[, headers|status[, status]])"1156The \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:1157.1158.IP "" 41159.1160.nf1161Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1162why, one step back1162 res\.send(); // 204Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1163–1194why, one step back1163 res\.send(new Buffer(\'wahoo\'));1164 res\.send({ some: \'json\' });1165 res\.send(\'<p>some html</p>\');1166 res\.send(\'Sorry, cant find that\', 404);1167 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1168 res\.send(404);1169.1170.fi1171.1172.IP "" 01173.1174.P1175By 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\.1176.1177.SS "res\.redirect(url[, status])"1178Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1179.1180.IP "" 41181.1182.nf11831184res\.redirect(\'/\', 301);1185res\.redirect(\'/account\');1186res\.redirect(\'http://google\.com\');1187res\.redirect(\'home\');1188res\.redirect(\'back\');1189.1190.fi1191.1192.IP "" 01193.1194.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1195why, one step back1195Express 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 1196why, one step back1196.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1197–1240why, one step back1197.SS "res\.cookie(name, val[, options])"1198Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1199.1200.IP "" 41201.1202.nf12031204// "Remember me" for 15 minutes1205res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1206.1207.fi1208.1209.IP "" 01210.1211.P1212To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1213.1214.IP "" 41215.1216.nf12171218app\.use(express\.cookieDecoder());12191220app\.get(\'/\', function(req, res){1221 // use req\.cookies\.rememberme1222});1223.1224.fi1225.1226.IP "" 01227.1228.SS "res\.clearCookie(name)"1229Clear cookie \fIname\fR by setting "expires" far in the past\.1230.1231.IP "" 41232.1233.nf12341235res\.clearCookie(\'rememberme\');1236.1237.fi1238.1239.IP "" 01240.Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1241–1247why, one step back1241.SS "res\.render(view[, options[, fn]])"1242Render \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\.1243.1244.P1245Most 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:1246.1247.IP "\(bu" 4HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
line 1248why, one step back1248\fIscope\fR Template evaluation context (value of \fIthis\fR)Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1249–1255why, one step back1249.1250.IP "\(bu" 41251\fIlocals\fR Object containing local variables1252.1253.IP "\(bu" 41254\fIdebug\fR Output debugging information1255.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1256–1261why, one step back1256.IP "\(bu" 41257\fIstatus\fR Response status code, defaults to 2001258.1259.IP "\(bu" 41260\fIheaders\fR Response headers object1261.Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1262–1303why, one step back1262.IP "" 01263.1264.SS "res\.partial(view[, options])"1265Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1266.1267.IP "\(bu" 41268\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.1269.1270.IP "\(bu" 41271as: \'something\' will add the \fIsomething\fR local variable1272.1273.IP "\(bu" 41274as: this will use the collection value as the template context1275.1276.IP "\(bu" 41277as: global will merge the collection value\'s properties with \fIlocals\fR1278.1279.IP "" 012801281.1282.IP "\(bu" 41283\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\.1284.1285.IP "" 01286.1287.P1288The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1289.1290.IP "" 41291.1292.nf12931294partial(\'movie\.jade\', { collection: movies });1295partial(\'movie\.jade\', movies);1296partial(\'movie\', movies);1297// In view: movie\.director1298.1299.fi1300.1301.IP "" 01302.1303.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1304why, one step back1304To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1305–1331why, one step back1305.1306.IP "" 41307.1308.nf13091310partial(\'movie\', { collection: movies, as: \'video\' });1311// In view: video\.director1312.1313.fi1314.1315.IP "" 01316.1317.P1318Also 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\.1319.1320.IP "" 41321.1322.nf13231324partial(\'movie\', { collection: movies, as: this });1325// In view: this\.director1326.1327.fi1328.1329.IP "" 01330.1331.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1332why, one step back1332Another 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 1333–1351why, one step back1333.1334.IP "" 41335.1336.nf13371338partials(\'movie\', { collection: movies, as: global });1339// In view: director1340.1341.fi1342.1343.IP "" 01344.1345.SS "app\.set(name[, val])"1346Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1347.1348.IP "" 41349.1350.nf1351Updated docsTj Holowaychukbefore adoption3234329
lines 1352–1354why, one step back1352app\.set(\'views\', __dirname + \'/views\');1353app\.set(\'views\');1354// => \.\.\.path\.\.\.Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1355–1434why, one step back1355.1356.fi1357.1358.IP "" 01359.1360.SS "app\.enable(name)"1361Enable the given setting \fIname\fR:1362.1363.IP "" 41364.1365.nf13661367app\.enable(\'some arbitrary setting\');1368app\.set(\'some arbitrary setting\');1369// => true1370.1371.fi1372.1373.IP "" 01374.1375.SS "app\.disable(name)"1376Disable the given setting \fIname\fR:1377.1378.IP "" 41379.1380.nf13811382app\.disable(\'some setting\');1383app\.set(\'some setting\');1384// => false1385.1386.fi1387.1388.IP "" 01389.1390.SS "app\.configure(env|function[, function])"1391Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1392.1393.IP "" 41394.1395.nf13961397app\.configure(function(){1398 // executed for each env1399});14001401app\.configure(\'development\', function(){1402 // executed for \'development\' only1403});1404.1405.fi1406.1407.IP "" 01408.1409.SS "app\.redirect(name, val)"1410For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1411.1412.IP "" 41413.1414.nf14151416app\.redirect(\'google\', \'http://google\.com\');1417.1418.fi1419.1420.IP "" 01421.1422.P1423Now in a route we may call:1424.1425.P1426res\.redirect(\'google\');1427.1428.P1429We may also map dynamic redirects:1430.1431.IP "" 41432.1433.nf1434Updated docsTj Holowaychukbefore adoptiond691ecb
lines 1435–1436why, one step back1435app\.redirect(\'comments\', function(req, res){1436 return \'/post/\' + req\.params\.id + \'/comments\';Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1437–1503why, one step back1437});1438.1439.fi1440.1441.IP "" 01442.1443.P1444So 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\.1445.1446.IP "" 41447.1448.nf14491450app\.get(\'/post/:id\', function(req, res){1451 res\.redirect(\'comments\');1452});1453.1454.fi1455.1456.IP "" 01457.1458.SS "app\.error(function)"1459Adds 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:1460.1461.IP "" 41462.1463.nf14641465app\.error(function(err, req, res, next){1466 res\.send(err\.message, 500);1467});1468.1469.fi1470.1471.IP "" 01472.1473.SS "app\.helpers(obj)"1474Registers static view helpers\.1475.1476.IP "" 41477.1478.nf14791480app\.helpers({1481 name: function(first, last){ return first + \', \' + last },1482 firstName: \'tj\',1483 lastName: \'holowaychuk\'1484});1485.1486.fi1487.1488.IP "" 01489.1490.P1491Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1492.1493.IP "" 41494.1495.nf14961497<%= name(firstName, lastName) %>1498.1499.fi1500.1501.IP "" 01502.1503.SS "app\.dynamicHelpers(obj)"Updated docsTj Holowaychukbefore adoptiond691ecb
line 1504why, one step back1504Registers 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 1505–1510why, one step back1505.1506.IP "" 41507.1508.nf15091510app\.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 1511why, one step back1511 session: function(req, res){Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1512–1527why, one step back1512 return req\.session;1513 }1514});1515.1516.fi1517.1518.IP "" 01519.1520.P1521All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1522.1523.IP "" 41524.1525.nf15261527<%= session\.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 1528–1544why, one step back1528.1529.fi1530.1531.IP "" 01532.1533.SS "app\.mounted(fn)"1534Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1535.1536.IP "" 41537.1538.nf15391540var app = express\.createServer(),1541 blog = express\.createServer();15421543blog\.mounted(function(parent){1544 // parent is appMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1545why, one step back1545 // "this" is blogRebuilt docsTj Holowaychukbefore adoptionba88e48
lines 1546–1548why, one step back1546});15471548app\.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1549–1554why, one step back1549.1550.fi1551.1552.IP "" 01553.1554.SS "app\.register(ext, exports)"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1555why, one step back1555Register 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 1556–1567why, one step back1556.1557.IP "" 41558.1559.nf15601561 app\.register(\'\.html\', require(\'jade\'));1562.1563.fi1564.1565.IP "" 01566.1567.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1568why, one step back1568This 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 1569–1592why, one step back1569.1570.IP "" 41571.1572.nf15731574 app\.register(\'\.haml\', require(\'haml\-js\'));1575.1576.fi1577.1578.IP "" 01579.1580.P1581For engines that do not comply with the Express specification, we can also wrap their api this way\.1582.1583.IP "" 41584.1585.nf15861587 app\.register(\'\.foo\', {1588 render: function(str, options) {1589 // perhaps their api is1590 // foo\.toHTML(str, options);1591 }1592 });Split blog example into another fileTj Holowaychukbefore adoptiona65c203
lines 1593–1645why, one step back1593.1594.fi1595.1596.IP "" 01597.1598.SS "app\.listen([port[, host]])"1599Bind 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\.1600.1601.IP "" 41602.1603.nf16041605app\.listen();1606app\.listen(3000);1607app\.listen(3000, \'n\.n\.n\.n\');1608.1609.fi1610.1611.IP "" 01612.1613.P1614The \fIport\fR argument may also be a string representing the path to a unix domain socket:1615.1616.IP "" 41617.1618.nf16191620app\.listen(\'/tmp/express\.sock\');1621.1622.fi1623.1624.IP "" 01625.1626.P1627Then try it out:1628.1629.IP "" 41630.1631.nf16321633$ telnet /tmp/express\.sock1634GET / HTTP/1\.116351636HTTP/1\.1 200 OK1637Content\-Type: text/plain1638Content\-Length: 1116391640Hello World1641.1642.fi1643.1644.IP "" 01645