guide.1
This file
Path
docs/guide.1
1,749 lines · 36.4 KiB
Last changed by
Regenerate api docsTj Holowaychukbefore adoption129e21e
History of this fileTake it
The walk stopped after 200 commits: lines older than 82dbae6 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.3Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
line 3why, one step back3.HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
line 4why, one step back4.TH "GUIDE" "" "October 2010" "" ""Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
line 5why, one step back5.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 6–8why, one step back6.SH "NAME"7\fBguide\fR8.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 9–79why, one step back9.SS "Installation"10curl:11.12.IP "" 413.14.nf1516$ curl \-# http://expressjs\.com/install\.sh | sh17.18.fi19.20.IP "" 021.22.P23npm:24.25.IP "" 426.27.nf2829$ npm install express30.31.fi32.33.IP "" 034.35.P36git clone, first update the submodules:37.38.IP "" 439.40.nf4142$ git submodule update \-\-init43$ make install44$ make install\-support45.46.fi47.48.IP "" 049.50.SS "Creating An Application"51The \fIexpress\.Server\fR now inherits from \fIhttp\.Server\fR, however follows the same idiom by providing \fIexpress\.createServer()\fR as shown below\. This means that you can utilize Express server\'s transparently with other libraries\.52.53.IP "" 454.55.nf5657var app = require(\'express\')\.createServer();5859app\.get(\'/\', function(req, res){60 res\.send(\'hello world\');61});6263app\.listen(3000);64.65.fi66.67.IP "" 068.69.SS "Configuration"70Express supports arbitrary environments, such as \fIproduction\fR and \fIdevelopment\fR\. Developers can use the \fIconfigure()\fR method to setup needs required by the current environment\. When \fIconfigure()\fR is called without an environment name it will be run in \fIevery\fR environment prior to the environment specific callback\.71.72.P73In the example below we only \fIdumpExceptions\fR, and respond with exception stack traces in \fIdevelopment\fR mode, however for both environments we utilize \fImethodOverride\fR and \fIbodyDecoder\fR\. Note the use of \fIapp\.router\fR, which can (optionally) be used to mount the application routes, otherwise the first call to \fIapp\.{get,put,del,post}()\fR will mount the routes\.74.75.IP "" 476.77.nf7879app\.configure(function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 80–81why, one step back80 app\.use(express\.methodOverride());81 app\.use(express\.bodyDecoder());Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
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\'));Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
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 }));Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
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());Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
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 \.\.\."Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
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:Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 123–127why, one step back123.124.IP "" 4125.126.nf127Rebuilt docsTj Holowaychukbefore adoption2724ce3
line 128why, one step back128$ NODE_ENV=production node app\.jsCheck CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 129–133why, one step back129.130.fi131.132.IP "" 0133.Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 134–136why, one step back134.P135This is \fIvery\fR important, as many caching mechanisms are \fIonly enabled\fR when in production\.136.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 137–151why, one step back137.SS "Settings"138Express supports the following settings out of the box:139.140.IP "\(bu" 4141\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR142.143.IP "\(bu" 4144\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.145.146.IP "\(bu" 4147\fIviews\fR Root views directory defaulting to \fBCWD/views\fR148.149.IP "\(bu" 4150\fIview engine\fR Default view engine name for views rendered without extensions151.Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 152–157why, one step back152.IP "\(bu" 4153\fIview options\fR An object specifying global view options154.155.IP "\(bu" 4156\fIpartials\fR Root view partials directory defaulting to \fIviews\fR/partials\.157.Updated docsTj Holowaychukbefore adoptionf0eab06
lines 158–160why, one step back158.IP "\(bu" 4159\fIstream threshold\fR Bytesize indicating when a file should be streamed for \fIres\.sendfile()\fR using \fIfs\.ReadStream()\fR and \fIsys\.pump()\fR\.160.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 161–184why, one step back161.IP "" 0162.163.SS "Routing"164Express utilizes the HTTP verbs to provide a meaningful, expressive routing API\. For example we may want to render a user\'s account for the path \fI/user/12\fR, this can be done by defining the route below\. The values associated to the named placeholders are available as \fBreq\.params\fR\.165.166.IP "" 4167.168.nf169170app\.get(\'/user/:id\', function(req, res){171 res\.send(\'user \' + req\.params\.id);172});173.174.fi175.176.IP "" 0177.178.P179A route is simple a string which is compiled to a \fIRegExp\fR internally\. For example when \fI/user/:id\fR is compiled, a simplified version of the regexp may look similar to:180.181.IP "" 4182.183.nf184Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 185why, one step back185\e/user\e/([^\e/]+)\e/?Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 186–197why, one step back186.187.fi188.189.IP "" 0190.191.P192Regular expression literals may also be passed for complex uses\. Since capture groups with literal \fIRegExp\fR\'s are anonymous we can access them directly \fBreq\.params\fR\.193.194.IP "" 4195.196.nf197Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 198why, one step back198app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 199–217why, one step back199 res\.send(req\.params);200});201.202.fi203.204.IP "" 0205.206.P207Curl requests against the previously defined route:208.209.IP "" 4210.211.nf212213 $ curl http://dev:3000/user214 [null,null]215 $ curl http://dev:3000/users216 [null,null]217 $ curl http://dev:3000/users/1Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 218why, one step back218 ["1",null]Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
line 219why, one step back219 $ curl http://dev:3000/users/1\.\.15Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 220why, one step back220 ["1","15"]Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 221–232why, one step back221.222.fi223.224.IP "" 0225.226.P227Below are some route examples, and the associated paths that they may consume:228.229.IP "" 4230.231.nf232Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 233why, one step back233 "/user/:id"Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 234–235why, one step back234 /user/12235Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 236why, one step back236 "/users/:id?"Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 237–239why, one step back237 /users/5238 /users239Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 240why, one step back240 "/files/*"Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 241–243why, one step back241 /files/jquery\.js242 /files/javascripts/jquery\.js243Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 244why, one step back244 "/file/*\.*"Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 245–247why, one step back245 /files/jquery\.js246 /files/javascripts/jquery\.js247Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 248why, one step back248 "/user/:id/:operation?"Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 249–251why, one step back249 /user/1250 /user/1/edit251Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 252why, one step back252 "/products\.:format"Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 253–255why, one step back253 /products\.json254 /products\.xml255Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 256why, one step back256 "/products\.:format?"Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 257–265why, one step back257 /products\.json258 /products\.xml259 /products260.261.fi262.263.IP "" 0264.265.SS "Passing Route Control"Regenerated docsTj Holowaychukbefore adoption334a18a
line 266why, one step back266We 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\.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 267–271why, one step back267.268.IP "" 4269.270.nf271Updated docsTj Holowaychukbefore adoptionb819366
line 272why, one step back272app\.get(\'/users/:id?\', function(req, res, next){Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 273–287why, one step back273 var id = req\.params\.id;274 if (id) {275 // do something276 } else {277 next();278 }279});280281app\.get(\'/users\', function(req, res){282 // do something else283});284.285.fi286.287.IP "" 0Regenerated docsTj Holowaychukbefore adoption334a18a
line 288why, one step back288.Regenerated docsTj Holowaychukbefore adoption090debe
lines 289–346why, one step back289.SS "Middleware"290Middleware via Connect \fIhttp://github\.com/senchalabs/connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:291.292.IP "" 4293.294.nf295296 var express = require(\'express\');297298var app = express\.createServer(299 express\.logger(),300 express\.bodyDecoder()301 );302.303.fi304.305.IP "" 0306.307.P308Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:309.310.IP "" 4311.312.nf313314app\.use(express\.logger({ format: \':method :uri\' }));315.316.fi317.318.IP "" 0319.320.P321Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:322.323.IP "" 4324.325.nf326327var connect = require(\'connect\');328app\.use(connect\.logger());329.330.fi331.332.IP "" 0333.334.P335This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:336.337.IP "" 4338.339.nf340341app\.use(express\.logger());342.343.fi344.345.IP "" 0346.Regenerated docsTj Holowaychukbefore adoption334a18a
lines 347–350why, one step back347.SS "Route Middleware"348Routes may utilize route\-specific middleware by passing one or more additional callbacks (or arrays) to the method\. This feature is extremely useful for restricting access, loading data used by the route etc\.349.350.PRegenerated docsTj Holowaychukbefore adoption0faac20
line 351why, one step back351Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.Regenerated docsTj Holowaychukbefore adoption334a18a
lines 352–356why, one step back352.353.IP "" 4354.355.nf356Regenerated docsTj Holowaychukbefore adoption0faac20
lines 357–358why, one step back357app\.get(\'/user/:id\', function(req, res, next){358 loadUser(req\.params\.id, function(err, user){Regenerated guideTj Holowaychukbefore adoptionab3337d
lines 359–360why, one step back359 if (err) return next(err);360 res\.send(\'Viewing user \' + user\.name);Regenerated docsTj Holowaychukbefore adoption0faac20
lines 361–362why, one step back361 });362});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 363–374why, one step back363.364.fi365.366.IP "" 0367.368.P369To keep things DRY and to increase readability we can apply this logic within a middleware\. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time\.370.371.IP "" 4372.373.nf374Regenerated docsTj Holowaychukbefore adoption0faac20
lines 375–383why, one step back375function loadUser(req, res, next) {376 // You would fetch your user from the db377 var user = users[req\.params\.id];378 if (user) {379 req\.user = user;380 next();381 } else {382 next(new Error(\'Failed to load user \' + req\.params\.id));383 }Regenerated docsTj Holowaychukbefore adoption334a18a
line 384why, one step back384}Regenerated docsTj Holowaychukbefore adoption0faac20
line 385why, one step back385Regenerated docsTj Holowaychukbefore adoption334a18a
line 386why, one step back386app\.get(\'/user/:id\', loadUser, function(req, res){Regenerated docsTj Holowaychukbefore adoption0faac20
lines 387–388why, one step back387 res\.send(\'Viewing user \' + req\.user\.name);388});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 389–400why, one step back389.390.fi391.392.IP "" 0393.394.P395Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account\. In the example below only the authenticated user may edit his/her account\.396.397.IP "" 4398.399.nf400Regenerated docsTj Holowaychukbefore adoption0faac20
lines 401–402why, one step back401function andRestrictToSelf(req, res, next) {402 req\.authenticatedUser\.id == req\.user\.idRegenerated guideTj Holowaychukbefore adoptionab3337d
lines 403–404why, one step back403 ? next()404 : next(new Error(\'Unauthorized\'));Regenerated docsTj Holowaychukbefore adoption334a18a
line 405why, one step back405}Regenerated docsTj Holowaychukbefore adoption0faac20
line 406why, one step back406Regenerated docsTj Holowaychukbefore adoption334a18a
line 407why, one step back407app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){Regenerated docsTj Holowaychukbefore adoption0faac20
lines 408–409why, one step back408 res\.send(\'Editing user \' + req\.user\.name);409});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 410–421why, one step back410.411.fi412.413.IP "" 0414.415.P416Keeping in mind that middleware are simply functions, we can define function that \fIreturns\fR the middleware in order to create a more expressive and flexible solution as shown below\.417.418.IP "" 4419.420.nf421Regenerated docsTj Holowaychukbefore adoption0faac20
lines 422–424why, one step back422function andRestrictTo(role) {423 return function(req, res, next) {424 req\.authenticatedUser\.role == roleRegenerated guideTj Holowaychukbefore adoptionab3337d
lines 425–426why, one step back425 ? next()426 : next(new Error(\'Unauthorized\'));Regenerated docsTj Holowaychukbefore adoption0faac20
line 427why, one step back427 }Regenerated docsTj Holowaychukbefore adoption334a18a
line 428why, one step back428}Regenerated docsTj Holowaychukbefore adoption0faac20
line 429why, one step back429Regenerated docsTj Holowaychukbefore adoption334a18a
line 430why, one step back430app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){Regenerated docsTj Holowaychukbefore adoption0faac20
lines 431–432why, one step back431 res\.send(\'Deleted user \' + req\.user\.name);432});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 433–444why, one step back433.434.fi435.436.IP "" 0437.438.P439Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.440.441.IP "" 4442.443.nf444Regenerated docsTj Holowaychukbefore adoption0faac20
lines 445–454why, one step back445var a = [middleware1, middleware2]446 , b = [middleware3, middleware4]447 , all = [a, b];448449app\.get(\'/foo\', a, function(){});450app\.get(\'/bar\', a, function(){});451452app\.get(\'/\', a, middleware3, middleware4, function(){});453app\.get(\'/\', a, b, function(){});454app\.get(\'/\', all, function(){});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 455–461why, one step back455.456.fi457.458.IP "" 0459.460.P461For this example in full, view the route middleware example \fIhttp://github\.com/visionmedia/express/blob/master/examples/route\-middleware/app\.js\fR in the repository\.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
line 462why, one step back462.HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 463–472why, one step back463.SS "HTTP Methods"464We have seen \fIapp\.get()\fR a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as \fIapp\.post()\fR, \fIapp\.del()\fR, etc\.465.466.P467A common example for \fIPOST\fR usage, is when "submitting" a form\. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it\.468.469.IP "" 4470.471.nf472Regenerated guideTj Holowaychukbefore adoptionab3337d
lines 473–477why, one step back473 <form method="post" action="/">474 <input type="text" name="user[name]" />475 <input type="text" name="user[email]" />476 <input type="submit" value="Submit" />477 </form>HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 478–543why, one step back478.479.fi480.481.IP "" 0482.483.P484By default Express does not know what to do with this request body, so we should add the \fIbodyDecoder\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:485.486.IP "" 4487.488.nf489490app\.use(express\.bodyDecoder());491.492.fi493.494.IP "" 0495.496.P497Our route below will now have access to the \fIreq\.body\.user\fR object which will contain the \fIname\fR and \fIemail\fR properties when defined\.498.499.IP "" 4500.501.nf502503app\.post(\'/\', function(req, res){504 console\.log(req\.body\.user);505 res\.redirect(\'back\');506});507.508.fi509.510.IP "" 0511.512.P513When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyDecoder\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.514.515.IP "" 4516.517.nf518519app\.use(express\.bodyDecoder());520app\.use(express\.methodOverride());521.522.fi523.524.IP "" 0525.526.P527The reason that these are not always defaults, is simply because these are not required for Express to be fully functional\. Depending on the needs of your application, you may not need these at all, your methods such as \fIPUT\fR and \fIDELETE\fR can still be accessed by clients which can use them directly, although \fImethodOverride\fR provides a great solution for forms\. Below shows what the usage of \fIPUT\fR might look like:528.529.IP "" 4530.531.nf532533<form method="post" action="/">534 <input type="hidden" name="_method" value="put" />535 <input type="text" name="user[name]" />536 <input type="text" name="user[email]" />537 <input type="submit" value="Submit" />538</form>539540app\.put(\'/\', function(){541 console\.log(req\.body\.user);542 res\.redirect(\'back\');543});Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 544–548why, one step back544.545.fi546.547.IP "" 0548.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 549–578why, one step back549.SS "Error Handling"550Express provides the \fIapp\.error()\fR method which receives exceptions thrown within a route, or passed to \fInext(err)\fR\. Below is an example which serves different pages based on our ad\-hoc \fINotFound\fR exception:551.552.IP "" 4553.554.nf555556function NotFound(msg){557 this\.name = \'NotFound\';558 Error\.call(this, msg);559 Error\.captureStackTrace(this, arguments\.callee);560}561562sys\.inherits(NotFound, Error);563564app\.get(\'/404\', function(req, res){565 throw new NotFound;566});567568app\.get(\'/500\', function(req, res){569 throw new Error(\'keyboard cat!\');570});571.572.fi573.574.IP "" 0575.576.P577We can call \fIapp\.error()\fR several times as shown below\. Here we check for an instanceof \fINotFound\fR and show the 404 page, or we pass on to the next error handler\.578.Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 579–581why, one step back579.P580Note that these handlers can be defined anywhere, as they will be placed below the route handlers on \fIlisten()\fR\. This allows for definition within \fIconfigure()\fR blocks so we can handle exceptions in different ways based on the environment\.581.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 582–617why, one step back582.IP "" 4583.584.nf585586app\.error(function(err, req, res, next){587 if (err instanceof NotFound) {588 res\.render(\'404\.jade\');589 } else {590 next(err);591 }592});593.594.fi595.596.IP "" 0597.598.P599Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like600.601.IP "" 4602.603.nf604605app\.error(function(err, req, res){606 res\.render(\'500\.jade\', {607 locals: {608 error: err609 }610 });611});612.613.fi614.615.IP "" 0616.617.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 618why, one step back618Our 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:Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 619–623why, one step back619.620.IP "" 4621.622.nf623Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 624why, one step back624app\.use(express\.errorHandler({ dumpExceptions: true }));Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 625–636why, one step back625.626.fi627.628.IP "" 0629.630.P631Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:632.633.IP "" 4634.635.nf636Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 637why, one step back637app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 638–646why, one step back638.639.fi640.641.IP "" 0642.643.P644The \fIerrorHandler\fR middleware also responds with \fIjson\fR if \fIAccept: application/json\fR is present, which is useful for developing apps that rely heavily on client\-side JavaScript\.645.646.SS "View Rendering"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 647why, one step back647View 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\.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 648–717why, one step back648.649.P650Below is an example using Haml\.js \fIhttp://github\.com/visionmedia/haml\.js\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.html\fR will be passed as the \fIbody\fR local variable in \fIlayout\.haml\fR\.651.652.IP "" 4653.654.nf655656app\.get(\'/\', function(req, res){657 res\.render(\'index\.haml\', {658 locals: { title: \'My Site\' }659 });660});661.662.fi663.664.IP "" 0665.666.P667The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using Jade \fIhttp://github\.com/visionmedia/jade\fR we could set:668.669.IP "" 4670.671.nf672673app\.set(\'view engine\', \'jade\');674.675.fi676.677.IP "" 0678.679.P680Allowing us to render with:681.682.IP "" 4683.684.nf685686res\.render(\'index\');687.688.fi689.690.IP "" 0691.692.P693vs:694.695.IP "" 4696.697.nf698699res\.render(\'index\.jade\');700.701.fi702.703.IP "" 0704.705.P706When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:707.708.IP "" 4709.710.nf711712res\.render(\'another\-page\.ejs\');713.714.fi715.716.IP "" 0717.Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 718–746why, one step back718.P719Express also provides the \fIview options\fR setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:720.721.IP "" 4722.723.nf724725app\.set(\'view options\', {726 layout: false727});728.729.fi730.731.IP "" 0732.733.P734Which can then be overridden within the \fBres\.render()\fR call if need be:735.736.IP "" 4737.738.nf739740res\.render(\'myview\.ejs\', { layout: true });741.742.fi743.744.IP "" 0745.746.PRebuilt docsTj Holowaychukbefore adoption2724ce3
lines 747–785why, one step back747When an alternate layout is required, we may also specify a path\. For example if we have \fIview engine\fR set to \fIjade\fR and a file named \fI\./views/mylayout\.jade\fR we can simply pass:748.749.IP "" 4750.751.nf752753res\.render(\'page\', { layout: \'mylayout\' });754.755.fi756.757.IP "" 0758.759.P760Otherwise we must specify the extension:761.762.IP "" 4763.764.nf765766res\.render(\'page\', { layout: \'mylayout\.jade\' });767.768.fi769.770.IP "" 0771.772.P773These paths may also be absolute:774.775.IP "" 4776.777.nf778779res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });780.781.fi782.783.IP "" 0784.785.PAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 786–800why, one step back786A good example of this is specifying custom \fIejs\fR opening and closing tags:787.788.IP "" 4789.790.nf791792app\.set(\'view options\', {793 open: \'{{\',794 close: \'}}\'795});796.797.fi798.799.IP "" 0800.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
line 801why, one step back801.SS "View Partials"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 802why, one step back802The 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:Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 803–833why, one step back803.804.IP "" 4805.806.nf807808partial(\'comment\.haml\', { collection: comments });809.810.fi811.812.IP "" 0813.814.P815To make things even less verbose we can assume the extension as \fI\.haml\fR when omitted, however if we wished we could use an ejs partial, within a haml view for example\.816.817.IP "" 4818.819.nf820821partial(\'comment\', { collection: comments });822.823.fi824.825.IP "" 0826.827.P828And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:829.830.IP "" 4831.832.nf833Regenerated docsTj Holowaychukbefore adoption2a40cec
line 834why, one step back834partial(\'comment\', comments);Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 835–840why, one step back835.836.fi837.838.IP "" 0839.840.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 841why, one step back841When using the partial collection support a few "magic" variables are provided for free:Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 842–849why, one step back842.843.IP "\(bu" 4844\fIfirstInCollection\fR True if this is the first object845.846.IP "\(bu" 4847\fIindexInCollection\fR Index of the object in the collection848.849.IP "\(bu" 4Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 850why, one step back850\fIlastInCollection\fR True if this is the last objectCheck CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
line 851why, one step back851.Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 852–854why, one step back852.IP "\(bu" 4853\fIcollectionLength\fR Length of the collection854.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 855–856why, one step back855.IP "" 0856.Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 857–859why, one step back857.P858For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.859.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 860–863why, one step back860.SS "Template Engines"861Below are a few template engines commonly used with Express:862.863.IP "\(bu" 4Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 864why, one step back864Jade \fIhttp://jade\-lang\.com\fR haml\.js successorCheck CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 865–866why, one step back865.866.IP "\(bu" 4Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 867why, one step back867Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templatesCheck CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 868–870why, one step back868.869.IP "\(bu" 4870EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScriptRebuilt docsTj Holowaychukbefore adoption2724ce3
line 871why, one step back871.Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 872–874why, one step back872.IP "\(bu" 4873CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating874.Rebuilt docsTj Holowaychukbefore adoption2724ce3
lines 875–902why, one step back875.IP "" 0876.877.SS "Session Support"878Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieDecoder\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.879.880.IP "" 4881.882.nf883884app\.use(express\.cookieDecoder());885app\.use(express\.session());886.887.fi888.889.IP "" 0890.891.P892By default the \fIsession\fR middleware uses the memory store bundled with Connect, however many implementations exist\. For example connect\-redis \fIhttp://github\.com/visionmedia/connect\-redis\fR supplies a Redis \fIhttp://code\.google\.com/p/redis/\fR session store and can be used as shown below:893.894.IP "" 4895.896.nf897898var RedisStore = require(\'connect\-redis\');899app\.use(express\.cookieDecoder());900app\.use(express\.session({ store: new RedisStore }));901.902.fiCheck CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 903–905why, one step back903.904.IP "" 0905.Regenerated guideTj Holowaychukbefore adoptionf179979
lines 906–913why, one step back906.P907Now the \fIreq\.session\fR and \fIreq\.sessionStore\fR properties will be accessible to all routes and subsequent middleware\. Properties on \fIreq\.session\fR are automatically saved on a response, so for example if we wish to shopping cart data:908.909.IP "" 4910.911.nf912913var RedisStore = require(\'connect\-redis\');Regenerated docsTj Holowaychukbefore adoption1c9831a
line 914why, one step back914app\.use(express\.bodyDecoder());Regenerated guideTj Holowaychukbefore adoptionf179979
lines 915–942why, one step back915app\.use(express\.cookieDecoder());916app\.use(express\.session({ store: new RedisStore }));917918app\.post(\'/add\-to\-cart\', function(req, res){919 // Perhaps we posted several items with a form920 // (use the bodyDecoder() middleware for this)921 var items = req\.body\.items;922 req\.session\.items = items;923 res\.redirect(\'back\');924});925926app\.get(\'/add\-to\-cart\', function(req, res){927 // When redirected back to GET /add\-to\-cart928 // we could check req\.session\.items && req\.session\.items\.length929 // to print out a message930 if (req\.session\.items && req\.session\.items\.length) {931 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);932 }933 res\.render(\'shopping\-cart\');934});935.936.fi937.938.IP "" 0939.940.P941The \fIreq\.session\fR object also has methods such as \fISession#touch()\fR, \fISession#destroy()\fR, \fISession#regenerate()\fR among others to maintain and manipulate sessions\. For more information view the Connect Session \fIhttp://senchalabs\.github\.com/connect/session\.html\fR documentation\.942.Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc
lines 943–945why, one step back943.SS "Migration Guide"944Pre\-beta Express developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.945.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 946–964why, one step back946.SS "req\.header(key[, defaultValue])"947Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:948.949.IP "" 4950.951.nf952953req\.header(\'Host\');954req\.header(\'host\');955req\.header(\'Accept\', \'*/*\');956.957.fi958.959.IP "" 0960.961.SS "req\.accepts(type)"962Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.963.964.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 965why, one step back965When 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\.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 966–989why, one step back966.967.IP "" 4968.969.nf970971// Accept: text/html972req\.accepts(\'html\');973// => true974975// Accept: text/*; application/json976req\.accepts(\'html\');977req\.accepts(\'text/html\');978req\.accepts(\'text/plain\');979req\.accepts(\'application/json\');980// => true981982req\.accepts(\'image/png\');983req\.accepts(\'png\');984// => false985.986.fi987.988.IP "" 0989.Added req.is() docsTj Holowaychukbefore adoption806aefa
lines 990–1047why, one step back990.SS "req\.is(type)"991Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.992.993.IP "" 4994.995.nf996997 // With Content\-Type: text/html; charset=utf\-8998 req\.is(\'html\');999 req\.is(\'text/html\');1000 // => true10011002 // When Content\-Type is application/json1003 req\.is(\'json\');1004 req\.is(\'application/json\');1005 // => true10061007 req\.is(\'html\');1008 // => false1009.1010.fi1011.1012.IP "" 01013.1014.P1015Ad\-hoc callbacks can also be registered with Express, to perform assertions again the request, for example if we need an expressive way to check if our incoming request is an image, we can register \fI"an image"\fR callback:1016.1017.IP "" 41018.1019.nf10201021 app\.is(\'an image\', function(req){1022 return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1023 });1024.1025.fi1026.1027.IP "" 01028.1029.P1030Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1031.1032.IP "" 41033.1034.nf10351036 app\.post(\'/image/upload\', function(req, res, next){1037 if (req\.is(\'an image\')) {1038 // do something1039 } else {1040 next();1041 }1042 });1043.1044.fi1045.1046.IP "" 01047.Merge branch 'is'Tj Holowaychukbefore adoption7a71380
lines 1048–1076why, one step back1048.P1049Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1050.1051.P1052Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1053.1054.IP "" 41055.1056.nf10571058req\.is(\'image/*\');1059.1060.fi1061.1062.IP "" 01063.1064.P1065We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1066.1067.IP "" 41068.1069.nf10701071req\.is(\'*/json\');1072.1073.fi1074.1075.IP "" 01076.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1077–1091why, one step back1077.SS "req\.param(name)"1078Return the value of param \fIname\fR when present\.1079.1080.IP "\(bu" 41081Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1082.1083.IP "\(bu" 41084Checks query string params (\fIreq\.query\fR), ex: ?id=121085.1086.IP "\(bu" 41087Checks urlencoded body params (\fIreq\.body\fR), ex: id=121088.1089.IP "" 01090.1091.PAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
line 1092why, one step back1092To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1093–1118why, one step back1093.1094.SS "req\.flash(type[, msg])"1095Queue flash \fImsg\fR of the given \fItype\fR\.1096.1097.IP "" 41098.1099.nf11001101req\.flash(\'info\', \'email sent\');1102req\.flash(\'error\', \'email delivery failed\');1103req\.flash(\'info\', \'email re\-sent\');1104// => 211051106req\.flash(\'info\');1107// => [\'email sent\', \'email re\-sent\']11081109req\.flash(\'info\');1110// => []11111112req\.flash();1113// => { error: [\'email delivery failed\'], info: [] }1114.1115.fi1116.1117.IP "" 01118.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1119–1131why, one step back1119.P1120Flash notification message may also utilize formatters, by default only the %s string formatter is available:1121.1122.IP "" 41123.1124.nf11251126req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1127.1128.fi1129.1130.IP "" 01131.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1132–1174why, one step back1132.SS "req\.isXMLHttpRequest"1133Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1134.1135.IP "" 41136.1137.nf11381139req\.xhr1140req\.isXMLHttpRequest1141.1142.fi1143.1144.IP "" 01145.1146.SS "res\.header(key[, val])"1147Get or set the response header \fIkey\fR\.1148.1149.IP "" 41150.1151.nf11521153res\.header(\'Content\-Length\');1154// => undefined11551156res\.header(\'Content\-Length\', 123);1157// => 12311581159res\.header(\'Content\-Length\');1160// => 1231161.1162.fi1163.1164.IP "" 01165.1166.SS "res\.contentType(type)"1167Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1168.1169.IP "" 41170.1171.nf11721173 var filename = \'path/to/image\.png\';1174 res\.contentType(filename);Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1175why, one step back1175 // res\.headers[\'Content\-Type\'] is now "image/png"Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1176–1181why, one step back1176.1177.fi1178.1179.IP "" 01180.1181.SS "res\.attachment([filename])"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1182why, one step back1182Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1183–1207why, one step back1183.1184.IP "" 41185.1186.nf11871188 res\.attachment(\'path/to/my/image\.png\');1189.1190.fi1191.1192.IP "" 01193.1194.SS "res\.sendfile(path)"1195Used by \fBres\.download()\fR to transfer an arbitrary file\.1196.1197.IP "" 41198.1199.nf12001201res\.sendfile(\'path/to/my\.file\');1202.1203.fi1204.1205.IP "" 01206.1207.PUpdated docsTj Holowaychukbefore adoptionf0eab06
lines 1208–1227why, one step back1208This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed\. When a callback is not given, and the file has \fBnot\fR been streamed, \fInext(err)\fR will be called on an exception\.1209.1210.IP "" 41211.1212.nf12131214res\.sendfile(path, function(err, path){1215 if (err) {1216 // handle the error1217 } else {1218 console\.log(\'transferred %s\', path);1219 }1220});1221.1222.fi1223.1224.IP "" 01225.1226.P1227When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1228–1263why, one step back1228.1229.SS "res\.download(file[, filename])"1230Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1231.1232.IP "" 41233.1234.nf12351236res\.download(\'path/to/image\.png\');1237res\.download(\'path/to/image\.png\', \'foo\.png\');1238.1239.fi1240.1241.IP "" 01242.1243.P1244This is equivalent to:1245.1246.IP "" 41247.1248.nf12491250res\.attachment(file);1251res\.sendfile(file);1252.1253.fi1254.1255.IP "" 01256.1257.SS "res\.send(body|status[, headers|status[, status]])"1258The \fBres\.send()\fR method is a high level response utility allowing you to pass objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status code based responses\. The following are all valid uses:1259.1260.IP "" 41261.1262.nf1263Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1264why, one step back1264 res\.send(); // 204Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1265–1296why, one step back1265 res\.send(new Buffer(\'wahoo\'));1266 res\.send({ some: \'json\' });1267 res\.send(\'<p>some html</p>\');1268 res\.send(\'Sorry, cant find that\', 404);1269 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1270 res\.send(404);1271.1272.fi1273.1274.IP "" 01275.1276.P1277By default the \fIContent\-Type\fR response header is set, however if explicitly assigned through \fBres\.send()\fR or previously with \fBres\.header()\fR or \fBres\.contentType()\fR it will not be set again\.1278.1279.SS "res\.redirect(url[, status])"1280Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1281.1282.IP "" 41283.1284.nf12851286res\.redirect(\'/\', 301);1287res\.redirect(\'/account\');1288res\.redirect(\'http://google\.com\');1289res\.redirect(\'home\');1290res\.redirect(\'back\');1291.1292.fi1293.1294.IP "" 01295.1296.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1297why, one step back1297Express 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 "/"\.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
line 1298why, one step back1298.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1299–1342why, one step back1299.SS "res\.cookie(name, val[, options])"1300Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1301.1302.IP "" 41303.1304.nf13051306// "Remember me" for 15 minutes1307res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1308.1309.fi1310.1311.IP "" 01312.1313.P1314To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1315.1316.IP "" 41317.1318.nf13191320app\.use(express\.cookieDecoder());13211322app\.get(\'/\', function(req, res){1323 // use req\.cookies\.rememberme1324});1325.1326.fi1327.1328.IP "" 01329.1330.SS "res\.clearCookie(name)"1331Clear cookie \fIname\fR by setting "expires" far in the past\.1332.1333.IP "" 41334.1335.nf13361337res\.clearCookie(\'rememberme\');1338.1339.fi1340.1341.IP "" 01342.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1343–1349why, one step back1343.SS "res\.render(view[, options[, fn]])"1344Render \fIview\fR with the given \fIoptions\fR and optional callback \fIfn\fR\. When a callback function is given a response will \fInot\fR be made automatically, however otherwise a response of \fI200\fR and \fItext/html\fR is given\.1345.1346.P1347Most engines accept one or more of the following options, both haml \fIhttp://github\.com/visionmedia/haml\.js\fR and jade \fIhttp://github\.com/visionmedia/jade\fR accept all:1348.1349.IP "\(bu" 4HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
line 1350why, one step back1350\fIscope\fR Template evaluation context (value of \fIthis\fR)Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1351–1357why, one step back1351.1352.IP "\(bu" 41353\fIlocals\fR Object containing local variables1354.1355.IP "\(bu" 41356\fIdebug\fR Output debugging information1357.Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1358–1363why, one step back1358.IP "\(bu" 41359\fIstatus\fR Response status code, defaults to 2001360.1361.IP "\(bu" 41362\fIheaders\fR Response headers object1363.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1364–1395why, one step back1364.IP "" 01365.1366.SS "res\.partial(view[, options])"1367Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1368.1369.IP "\(bu" 41370\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.1371.1372.IP "\(bu" 41373as: \'something\' will add the \fIsomething\fR local variable1374.1375.IP "\(bu" 41376as: this will use the collection value as the template context1377.1378.IP "\(bu" 41379as: global will merge the collection value\'s properties with \fIlocals\fR1380.1381.IP "" 013821383.1384.IP "\(bu" 41385\fIcollection\fR Array of objects, the name is derived from the view name itself\. For example \fIvideo\.html\fR will have a object \fIvideo\fR available to it\.1386.1387.IP "" 01388.1389.P1390The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1391.1392.IP "" 41393.1394.nf1395Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 1396–1397why, one step back1396partial(\'theatre/movie\.jade\', { collection: movies });1397partial(\'theatre/movie\.jade\', movies);Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1398–1407why, one step back1398partial(\'movie\.jade\', { collection: movies });1399partial(\'movie\.jade\', movies);1400partial(\'movie\', movies);1401// In view: movie\.director1402.1403.fi1404.1405.IP "" 01406.1407.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1408why, one step back1408To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1409–1435why, one step back1409.1410.IP "" 41411.1412.nf14131414partial(\'movie\', { collection: movies, as: \'video\' });1415// In view: video\.director1416.1417.fi1418.1419.IP "" 01420.1421.P1422Also we can make our movie the value of \fIthis\fR within our view so that instead of \fImovie\.director\fR we could use \fIthis\.director\fR\.1423.1424.IP "" 41425.1426.nf14271428partial(\'movie\', { collection: movies, as: this });1429// In view: this\.director1430.1431.fi1432.1433.IP "" 01434.1435.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1436why, one step back1436Another 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:Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1437–1455why, one step back1437.1438.IP "" 41439.1440.nf14411442partials(\'movie\', { collection: movies, as: global });1443// In view: director1444.1445.fi1446.1447.IP "" 01448.1449.SS "app\.set(name[, val])"1450Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1451.1452.IP "" 41453.1454.nf1455Updated docsTj Holowaychukbefore adoption3234329
lines 1456–1458why, one step back1456app\.set(\'views\', __dirname + \'/views\');1457app\.set(\'views\');1458// => \.\.\.path\.\.\.Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1459–1648why, one step back1459.1460.fi1461.1462.IP "" 01463.1464.SS "app\.enable(name)"1465Enable the given setting \fIname\fR:1466.1467.IP "" 41468.1469.nf14701471app\.enable(\'some arbitrary setting\');1472app\.set(\'some arbitrary setting\');1473// => true1474.1475.fi1476.1477.IP "" 01478.1479.SS "app\.disable(name)"1480Disable the given setting \fIname\fR:1481.1482.IP "" 41483.1484.nf14851486app\.disable(\'some setting\');1487app\.set(\'some setting\');1488// => false1489.1490.fi1491.1492.IP "" 01493.1494.SS "app\.configure(env|function[, function])"1495Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1496.1497.IP "" 41498.1499.nf15001501app\.configure(function(){1502 // executed for each env1503});15041505app\.configure(\'development\', function(){1506 // executed for \'development\' only1507});1508.1509.fi1510.1511.IP "" 01512.1513.SS "app\.redirect(name, val)"1514For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1515.1516.IP "" 41517.1518.nf15191520app\.redirect(\'google\', \'http://google\.com\');1521.1522.fi1523.1524.IP "" 01525.1526.P1527Now in a route we may call:1528.1529.P1530res\.redirect(\'google\');1531.1532.P1533We may also map dynamic redirects:1534.1535.IP "" 41536.1537.nf15381539app\.redirect(\'comments\', function(req, res){1540 return \'/post/\' + req\.params\.id + \'/comments\';1541});1542.1543.fi1544.1545.IP "" 01546.1547.P1548So now we may do the following, and the redirect will dynamically adjust to the context of the request\. If we called this route with \fIGET /post/12\fR our redirect \fILocation\fR would be \fI/post/12/comments\fR\.1549.1550.IP "" 41551.1552.nf15531554app\.get(\'/post/:id\', function(req, res){1555 res\.redirect(\'comments\');1556});1557.1558.fi1559.1560.IP "" 01561.1562.SS "app\.error(function)"1563Adds an error handler \fIfunction\fR which will receive the exception as the first parameter as shown below\. Note that we may set several error handlers by making several calls to this method, however the handler should call \fInext(err)\fR if it does not wish to deal with the exception:1564.1565.IP "" 41566.1567.nf15681569app\.error(function(err, req, res, next){1570 res\.send(err\.message, 500);1571});1572.1573.fi1574.1575.IP "" 01576.1577.SS "app\.helpers(obj)"1578Registers static view helpers\.1579.1580.IP "" 41581.1582.nf15831584app\.helpers({1585 name: function(first, last){ return first + \', \' + last },1586 firstName: \'tj\',1587 lastName: \'holowaychuk\'1588});1589.1590.fi1591.1592.IP "" 01593.1594.P1595Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1596.1597.IP "" 41598.1599.nf16001601<%= name(firstName, lastName) %>1602.1603.fi1604.1605.IP "" 01606.1607.SS "app\.dynamicHelpers(obj)"1608Registers dynamic view helpers\. Dynamic view helpers are simply functions which accept \fIreq\fR, \fIres\fR, and are evaluated against the \fIServer\fR instance before a view is rendered\. The \fIreturn value\fR of this function becomes the local variable it is associated with\.1609.1610.IP "" 41611.1612.nf16131614app\.dynamicHelpers({1615 session: function(req, res){1616 return req\.session;1617 }1618});1619.1620.fi1621.1622.IP "" 01623.1624.P1625All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1626.1627.IP "" 41628.1629.nf16301631<%= session\.name %>1632.1633.fi1634.1635.IP "" 01636.1637.SS "app\.mounted(fn)"1638Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1639.1640.IP "" 41641.1642.nf16431644var app = express\.createServer(),1645 blog = express\.createServer();16461647blog\.mounted(function(parent){1648 // parent is appMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1649why, one step back1649 // "this" is blogCheck CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1650–1652why, one step back1650});16511652app\.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1653–1658why, one step back1653.1654.fi1655.1656.IP "" 01657.1658.SS "app\.register(ext, exports)"Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1659why, one step back1659Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1660–1671why, one step back1660.1661.IP "" 41662.1663.nf16641665 app\.register(\'\.html\', require(\'jade\'));1666.1667.fi1668.1669.IP "" 01670.1671.PMerge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 1672why, one step back1672This is also useful for libraries that may not match extensions correctly\. For example my haml\.js library is installed from npm as "hamljs" so instead of layout\.hamljs, we can register the engine as "\.haml":Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1673–1693why, one step back1673.1674.IP "" 41675.1676.nf16771678 app\.register(\'\.haml\', require(\'haml\-js\'));1679.1680.fi1681.1682.IP "" 01683.1684.P1685For engines that do not comply with the Express specification, we can also wrap their api this way\.1686.1687.IP "" 41688.1689.nf16901691 app\.register(\'\.foo\', {1692 render: function(str, options) {1693 // perhaps their api isRegenerated docsTj Holowaychukbefore adoption5152823
line 1694why, one step back1694 // return foo\.toHTML(str, options);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1695–1696why, one step back1695 }1696 });Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6
lines 1697–1749why, one step back1697.1698.fi1699.1700.IP "" 01701.1702.SS "app\.listen([port[, host]])"1703Bind the app server to the given \fIport\fR, which defaults to 3000\. When \fIhost\fR is omitted all connections will be accepted via \fIINADDR_ANY\fR\.1704.1705.IP "" 41706.1707.nf17081709app\.listen();1710app\.listen(3000);1711app\.listen(3000, \'n\.n\.n\.n\');1712.1713.fi1714.1715.IP "" 01716.1717.P1718The \fIport\fR argument may also be a string representing the path to a unix domain socket:1719.1720.IP "" 41721.1722.nf17231724app\.listen(\'/tmp/express\.sock\');1725.1726.fi1727.1728.IP "" 01729.1730.P1731Then try it out:1732.1733.IP "" 41734.1735.nf17361737$ telnet /tmp/express\.sock1738GET / HTTP/1\.117391740HTTP/1\.1 200 OK1741Content\-Type: text/plain1742Content\-Length: 1117431744Hello World1745.1746.fi1747.1748.IP "" 01749