Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,464 lines · 56.2 KiB · HTML

Last changed by

regenerated docsTj Holowaychukbefore adoptiondd7158a

History of this file

Take it

The walk stopped after 200 commits: lines older than 242efc7 point at it.

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1–182why, one step back
1<html>
2 <head>3 <title>Express - node web framework</title>4 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>5 <style>6 #tagline {7 margin-left: 75px;8 margin-bottom: 30px;9 color: rgba(255,255,255,0.7); }10 html {11 background: #1c1c1c url(images/bg.tile.jpg); }1213 body {14 margin: 0;15 padding-bottom: 30px;16 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";17 font-size: 14px;18 line-height: 1.5;19 -webkit-font-smoothing: antialiased;20 background: url(images/bg.jpg) 50% 0 no-repeat;21 color: #8b8b8b; }2223 * {24 outline: none; }2526 em {27 color: white; }2829 a img {30 border: none !important; }3132 a {33 font-weight: bold;34 text-decoration: none;35 color: white;36 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;37 -webkit-transition-duration: 0.15s;38 -webkit-transition-timing-function: ease-out; }39 a:hover {40 opacity: 0.8; }4142 h1, h2, h3, h4 {43 margin: 45px 0 0 0;44 color: white;45 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4647 h3 {48 font-size: 18px; }49 h4 {50 margin-left: 10px;51 font-size: 14px;52 }5354 pre {55 margin: 20px 10px;56 padding: 25px 20px;57 background: rgba(0,0,0,0.5);58 border: 1px solid #323232;59 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);60 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -webkit-border-radius: 5px;62 -moz-border-radius: 5px; }6364 code {65 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6667 ul {68 margin: 15px 0;69 padding: 0 0 0 35px; }70 ul li {71 margin: 0;72 padding: 2px 0;73 list-style: square; }74 ul li ul {75 margin: 0;76 padding-left: 12px;77 }7879 .man-name, #Express { display:none; }8081 .sect {82 margin-left: 40px; }83 img {84 margin-left: 20px;85 margin-bottom: 15px;86 }8788 #logo {89 display: block;90 margin-left: 30%;91 margin-bottom: 30px;92 width: 194px;93 height: 51px;94 background: url(images/logo.png) 0 0 no-repeat;95 text-indent: -99999px; }96 #logo:hover {97 opacity: 0.7; }98 #logo:active {99 opacity: 0.3; }100101 #ribbon {102 position: fixed;103 top: 0;104 right: 0;105 z-index: 2; }106107 #wrapper {108 width: 100%;109 min-height: 800px;110 background: url(images/top.png) 0 0 repeat-x; }111112 #container {113 margin: 0 auto;114 padding-top: 80px;115 width: 550px; }116117 #toc {118 position: fixed;119 top: 0;120 left: 0;121 margin: 0 0 0 15px;122 padding: 15px;123 height: 100%;124 background: rgba(0,0,0,0.2);125 overflow: auto;126 border-right: 1px solid rgba(255,255,255,0.05);127 }128 #toc li {129 padding: 0;130 list-style: none;131 }132 #toc li a {133 font-size: 11px;134 }135 #menu {136 margin-left: 75px;137 padding: 0;138 padding-bottom: 30px; }139 #menu li {140 display: inline;141 list-style: none; }142 #menu li a {143 display: block;144 float: left;145 margin: 0 2px;146 padding: 3px 15px;147 background: rgba(0,0,0,0.2);148 -webkit-border-radius: 8px;149 -moz-border-radius: 8px;150 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);151 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;153 -webkit-transition-duration: 0.15s;154 -webkit-transition-timing-function: ease-out; }155 #menu li a:hover,156 #menu li a.active {157 background: rgba(0,0,0,0.5); }158 #menu li a:active {159 background: rgba(0,0,0,0.1);160 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);161 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }162 </style>163 <script>164 $(function(){165 $('.section').hide();166 $('.toggle, a.section-title').toggle(function(){167 $(this).siblings('ul').fadeIn(300);168 return false;169 }, function(){170 $(this).siblings('ul').fadeOut(300);171 return false;172 });173 });174 </script>175 </head>176 <body>177 <a href='http://github.com/visionmedia/express'> 178 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 179 </a>180 <div id="wrapper">181 <div id="container"><ul id="toc">182<li><a href="#Installation">Installation</a></li>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 183–184why, one step back
183<li><a href="#Creating-A-Server">Creating A Server</a></li>
184<li><a href="#Creating-An-HTTPS-Server">Creating An HTTPS Server</a></li>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 185–192why, one step back
185<li><a href="#Configuration">Configuration</a></li>
186<li><a href="#Settings">Settings</a></li>187<li><a href="#Routing">Routing</a></li>188<li><a href="#Passing-Route-Control">Passing Route Control</a></li>189<li><a href="#Middleware">Middleware</a></li>190<li><a href="#Route-Middleware">Route Middleware</a></li>191<li><a href="#HTTP-Methods">HTTP Methods</a></li>192<li><a href="#Error-Handling">Error Handling</a></li>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 193why, one step back
193<li><a href="#Route-Param-Pre-conditions">Route Param Pre-conditions</a></li>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 194–195why, one step back
194<li><a href="#View-Rendering">View Rendering</a></li>
195<li><a href="#View-Partials">View Partials</a></li>

view lookup docsTj Holowaychukbefore adoption8a62f8c

line 196why, one step back
196<li><a href="#View-Lookup">View Lookup</a></li>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 197–198why, one step back
197<li><a href="#Template-Engines">Template Engines</a></li>
198<li><a href="#Session-Support">Session Support</a></li>

docsTj Holowaychukbefore adoption5581ca2

line 199why, one step back
199<li><a href="#Migration-Guide">Migration Guide</a></li>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 200why, one step back
200<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 201–205why, one step back
201<li><a href="#req-header-key-defaultValue">header()</a></li>
202<li><a href="#req-accepts-type">accepts()</a></li>203<li><a href="#req-is-type">is()</a></li>204<li><a href="#req-param-name-default">param()</a></li>205<li><a href="#req-flash-type-msg">flash()</a></li>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 206–208why, one step back
206<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>
207</ul></li>208<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 209–222why, one step back
209<li><a href="#res-header-key-val">header()</a></li>
210<li><a href="#res-charset">charset</a></li>211<li><a href="#res-contentType-type">contentType()</a></li>212<li><a href="#res-attachment-filename">attachment()</a></li>213<li><a href="#res-sendfile-path-options-callback">sendfile()</a></li>214<li><a href="#res-download-file-filename-callback">download()</a></li>215<li><a href="#res-send-body-status-headers-status-status">send()</a></li>216<li><a href="#res-redirect-url-status">redirect()</a></li>217<li><a href="#res-cookie-name-val-options">cookie()</a></li>218<li><a href="#res-clearCookie-name">clearCookie()</a></li>219<li><a href="#res-render-view-options-fn">render()</a></li>220<li><a href="#res-partial-view-options">partial()</a></li>221<li><a href="#res-local-name-val">local()</a></li>222<li><a href="#res-local-obj">local()</a></li>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 223–224why, one step back
223</ul></li>
224<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 225–237why, one step back
225<li><a href="#app-set-name-val">set()</a></li>
226<li><a href="#app-enable-name">enable()</a></li>227<li><a href="#app-enabled-name">enabled()</a></li>228<li><a href="#app-disable-name">disable()</a></li>229<li><a href="#app-disabled-name">disabled()</a></li>230<li><a href="#app-configure-env-function-function">configure()</a></li>231<li><a href="#app-redirect-name-val">redirect()</a></li>232<li><a href="#app-error-function">error()</a></li>233<li><a href="#app-helpers-obj">helpers()</a></li>234<li><a href="#app-dynamicHelpers-obj">dynamicHelpers()</a></li>235<li><a href="#app-mounted-fn">mounted()</a></li>236<li><a href="#app-register-ext-exports">register()</a></li>237<li><a href="#app-listen-port-host">listen()</a></li>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 238–252why, one step back
238</ul></li>
239</ul>240 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 241 <p id="tagline">242 High performance, high class web development for243 <a href="http://nodejs.org">Node.js</a>244 </p>245 <ul id="menu">246 <li><a href="index.html">Home</a></li>247 <li><a href="guide.html">Guide</a></li>248 <li><a href="screencasts.html">Screencasts</a></li>249 <li><a href="applications.html">Applications</a></li>250 </ul>251<h3 id="Installation">Installation</h3>252

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 253why, one step back
253<pre><code>$ npm install express</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 254why, one step back
254

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 255why, one step back
255<h3 id="Creating-A-Server">Creating A Server</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 256why, one step back
256

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 257why, one step back
257<p> To create an instance of the <em>express.HTTPServer</em>, simply invoke the <em>createServer()</em> method. With our instance <em>app</em> we can then define routes based on the HTTP verbs, in this example <em>app.get()</em>.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 258–261why, one step back
258
259<pre><code>var app = require('express').createServer();260261app.get('/', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 262why, one step back
262 res.send('hello world');

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 263–264why, one step back
263});
264

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 265why, one step back
265app.listen(3000);</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 266why, one step back
266

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 267–271why, one step back
267<h3 id="Creating-An-HTTPS-Server">Creating An HTTPS Server</h3>
268269<p> To initialize a <em>express.HTTPSServer</em> we do the same as above, however we270 pass an options object, accepting <em>key</em>, <em>cert</em> and the others mentioned in node's <a href="http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer">https documentation</a>.</p>271

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 272why, one step back
272<pre><code> var app = require('express').createServer({ key: ... });</code></pre>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 273why, one step back
273

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 274–277why, one step back
274<h3 id="Configuration">Configuration</h3>
275276<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers277can use the <em>configure()</em> method to setup needs required by the current environment. When

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 278why, one step back
278<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 279–281why, one step back
279prior to the environment specific callback.</p>
280281<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 282why, one step back
282in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 283why, one step back
283Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 284why, one step back
284otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 285–286why, one step back
285
286<pre><code>app.configure(function(){

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 287–289why, one step back
287 app.use(express.methodOverride());
288 app.use(express.bodyParser());289 app.use(app.router);

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 290–292why, one step back
290});
291292app.configure('development', function(){

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 293–294why, one step back
293 app.use(express.static(__dirname + '/public'));
294 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 295–297why, one step back
295});
296297app.configure('production', function(){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 298why, one step back
298 var oneYear = 31557600000;

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 299why, one step back
299 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 300why, one step back
300 app.use(express.errorHandler());

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 301why, one step back
301});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 302–304why, one step back
302
303<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>304

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 305why, one step back
305<pre><code> app.configure(function(){

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 306–307why, one step back
306 app.set('views', __dirname + '/views');
307 app.set('views');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 308why, one step back
308 // =&gt; "/absolute/path/to/views"

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 309–314why, one step back
309
310 app.enable('some feature');311 // same as app.set('some feature', true);312313 app.disable('some feature');314 // same as app.set('some feature', false);

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 315–317why, one step back
315
316 app.enabled('some feature')317 // =&gt; false

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 318why, one step back
318 });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 319why, one step back
319

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 320why, one step back
320<p>To alter the environment we can set the <em>NODE</em>ENV_ environment variable, for example:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 321why, one step back
321

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 322why, one step back
322<pre><code>$ NODE_ENV=production node app.js</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 323–329why, one step back
323
324<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>325326<h3 id="Settings">Settings</h3>327328<p>Express supports the following settings out of the box:</p>329

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 330why, one step back
330<ul><li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li><li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li><li><em>view engine</em> Default view engine name for views rendered without extensions</li><li><em>view options</em> An object specifying global view options</li></ul>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 331–335why, one step back
331
332<h3 id="Routing">Routing</h3>333334<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.335For example we may want to render a user's account for the path <em>/user/12</em>, this

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 336why, one step back
336can be done by defining the route below. The values associated to the named placeholders

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 337–339why, one step back
337are available as <code>req.params</code>.</p>
338339<pre><code>app.get('/user/:id', function(req, res){

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 340–341why, one step back
340 res.send('user ' + req.params.id);
341});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 342–345why, one step back
342
343<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example344when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>345

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 346why, one step back
346<pre><code>\/user\/([^\/]+)\/?</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 347–352why, one step back
347
348<p>Regular expression literals may also be passed for complex uses. Since capture349groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>. So our first capture group would be <em>req.params[0]</em> and the second would follow as <em>req.params[1]</em>.</p>350351<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){352 res.send(req.params);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 353why, one step back
353});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 354–363why, one step back
354
355<p>Curl requests against the previously defined route:</p>356357<pre><code> $ curl http://dev:3000/user358 [null,null]359 $ curl http://dev:3000/users360 [null,null]361 $ curl http://dev:3000/users/1362 ["1",null]363 $ curl http://dev:3000/users/1..15

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 364why, one step back
364 ["1","15"]</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 365–398why, one step back
365
366<p>Below are some route examples, and the associated paths that they367may consume:</p>368369<pre><code> "/user/:id"370 /user/12371372 "/users/:id?"373 /users/5374 /users375376 "/files/*"377 /files/jquery.js378 /files/javascripts/jquery.js379380 "/file/*.*"381 /files/jquery.js382 /files/javascripts/jquery.js383384 "/user/:id/:operation?"385 /user/1386 /user/1/edit387388 "/products.:format"389 /products.json390 /products.xml391392 "/products.:format?"393 /products.json394 /products.xml395 /products396397 "/user/:id.:format?"398 /user/12

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 399why, one step back
399 /user/12.json</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 400why, one step back
400

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 401why, one step back
401<p>For example we can <strong>POST</strong> some json, and echo the json back using the <em>bodyParser</em> middleware which will parse json request bodies (as well as others), and place the result in <em>req.body</em>:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 402–405why, one step back
402
403<pre><code>var express = require('express')404 , app = express.createServer();405

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 406why, one step back
406app.use(express.bodyParser());

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 407–411why, one step back
407
408app.post('/', function(req, res){409 res.send(req.body);410});411

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 412why, one step back
412app.listen(3000);</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 413why, one step back
413

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 414why, one step back
414<p>Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use <em>'/user/:id(\d+)'</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 415–419why, one step back
415
416<h3 id="Passing-Route-Control">Passing Route Control</h3>417418<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,419the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 420why, one step back
420and middleware continue to be invoked in the order that they are added via <em>use()</em>. The same is true for several routes which have the same path defined, they will simply be executed in order until one does <em>not</em> call <em>next()</em> and decides to respond.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 421–422why, one step back
421
422<pre><code>app.get('/users/:id?', function(req, res, next){

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 423–428why, one step back
423 var id = req.params.id;
424 if (id) {425 // do something426 } else {427 next();428 }

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 429–431why, one step back
429});
430431app.get('/users', function(req, res){

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 432–433why, one step back
432 // do something else
433});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 434why, one step back
434

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 435why, one step back
435<p>The <em>app.all()</em> method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to <em>req.user</em>.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 436–466why, one step back
436
437<pre><code>var express = require('express')438 , app = express.createServer();439440var users = [{ name: 'tj' }];441442app.all('/user/:id/:op?', function(req, res, next){443 req.user = users[req.params.id];444 if (req.user) {445 next();446 } else {447 next(new Error('cannot find user ' + req.params.id));448 }449});450451app.get('/user/:id', function(req, res){452 res.send('viewing ' + req.user.name);453});454455app.get('/user/:id/edit', function(req, res){456 res.send('editing ' + req.user.name);457});458459app.put('/user/:id', function(req, res){460 res.send('updating ' + req.user.name);461});462463app.get('*', function(req, res){464 res.send('what???', 404);465});466

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 467why, one step back
467app.listen(3000); </code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 468–476why, one step back
468
469<h3 id="Middleware">Middleware</h3>470471<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be472passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>473474<pre><code> var express = require('express');475476var app = express.createServer(

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 477–479why, one step back
477 express.logger()
478 , express.bodyParser()479 );</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 480why, one step back
480

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 481why, one step back
481<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 482why, one step back
482

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 483why, one step back
483<pre><code>app.use(express.logger({ format: ':method :uri' }));</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 484–488why, one step back
484
485<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>486487<pre><code>var connect = require('connect');488app.use(connect.logger());

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 489why, one step back
489app.use(connect.bodyParser());</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 490–493why, one step back
490
491<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>492493<pre><code>app.use(express.logger());

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 494why, one step back
494app.use(express.bodyParser());</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 495–499why, one step back
495
496<h3 id="Route-Middleware">Route Middleware</h3>497498<p>Routes 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.</p>499

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 500why, one step back
500<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user. </p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 501–502why, one step back
501
502<pre><code>app.get('/user/:id', function(req, res, next){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 503–506why, one step back
503 loadUser(req.params.id, function(err, user){
504 if (err) return next(err);505 res.send('Viewing user ' + user.name);506 });

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 507why, one step back
507});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 508why, one step back
508

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 509why, one step back
509<p>To 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. </p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 510–511why, one step back
510
511<pre><code>function loadUser(req, res, next) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 512–519why, one step back
512 // You would fetch your user from the db
513 var user = users[req.params.id];514 if (user) {515 req.user = user;516 next();517 } else {518 next(new Error('Failed to load user ' + req.params.id));519 }

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 520–522why, one step back
520}
521522app.get('/user/:id', loadUser, function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 523why, one step back
523 res.send('Viewing user ' + req.user.name);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 524why, one step back
524});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 525–528why, one step back
525
526<p>Multiple 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.</p>527528<pre><code>function andRestrictToSelf(req, res, next) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 529–531why, one step back
529 req.authenticatedUser.id == req.user.id
530 ? next()531 : next(new Error('Unauthorized'));

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 532–534why, one step back
532}
533534app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 535why, one step back
535 res.send('Editing user ' + req.user.name);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 536why, one step back
536});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 537–540why, one step back
537
538<p>Keeping in mind that middleware are simply functions, we can define function that <em>returns</em> the middleware in order to create a more expressive and flexible solution as shown below.</p>539540<pre><code>function andRestrictTo(role) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 541–545why, one step back
541 return function(req, res, next) {
542 req.authenticatedUser.role == role543 ? next()544 : next(new Error('Unauthorized'));545 }

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 546–548why, one step back
546}
547548app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 549why, one step back
549 res.send('Deleted user ' + req.user.name);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 550why, one step back
550});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 551–562why, one step back
551
552<p>Commonly used "stacks" of middleware can be passed as an array (<em>applied recursively</em>), which can be mixed and matched to any degree.</p>553554<pre><code>var a = [middleware1, middleware2]555 , b = [middleware3, middleware4]556 , all = [a, b];557558app.get('/foo', a, function(){});559app.get('/bar', a, function(){});560561app.get('/', a, middleware3, middleware4, function(){});562app.get('/', a, b, function(){});

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 563why, one step back
563app.get('/', all, function(){});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 564–576why, one step back
564
565<p>For this example in full, view the <a href="http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js">route middleware example</a> in the repository.</p>566567<h3 id="HTTP-Methods">HTTP Methods</h3>568569<p>We have seen <em>app.get()</em> a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as <em>app.post()</em>, <em>app.del()</em>, etc.</p>570571<p> A common example for <em>POST</em> 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.</p>572573<pre><code> &lt;form method="post" action="/"&gt;574 &lt;input type="text" name="user[name]" /&gt;575 &lt;input type="text" name="user[email]" /&gt;576 &lt;input type="submit" value="Submit" /&gt;

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 577why, one step back
577 &lt;/form&gt;</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 578why, one step back
578

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 579why, one step back
579<p>By default Express does not know what to do with this request body, so we should add the <em>bodyParser</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> and <em>application/json</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 580why, one step back
580

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 581why, one step back
581<pre><code>app.use(express.bodyParser());</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 582–585why, one step back
582
583<p>Our route below will now have access to the <em>req.body.user</em> object which will contain the <em>name</em> and <em>email</em> properties when defined.</p>584585<pre><code>app.post('/', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 586–587why, one step back
586 console.log(req.body.user);
587 res.redirect('back');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 588why, one step back
588});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 589why, one step back
589

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 590why, one step back
590<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyParser</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 591why, one step back
591

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 592why, one step back
592<pre><code>app.use(express.bodyParser());

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 593why, one step back
593app.use(express.methodOverride());</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 594–606why, one step back
594
595<p>The 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 <em>PUT</em> and <em>DELETE</em> can still be accessed by clients which can use them directly, although <em>methodOverride</em> provides a great solution for forms. Below shows what the usage of <em>PUT</em> might look like:</p>596597<pre><code>&lt;form method="post" action="/"&gt;598 &lt;input type="hidden" name="_method" value="put" /&gt;599 &lt;input type="text" name="user[name]" /&gt;600 &lt;input type="text" name="user[email]" /&gt;601 &lt;input type="submit" value="Submit" /&gt; 602&lt;/form&gt;603604app.put('/', function(){605 console.log(req.body.user);606 res.redirect('back');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 607why, one step back
607});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 608–615why, one step back
608
609<h3 id="Error-Handling">Error Handling</h3>610611<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,612or passed to <em>next(err)</em>. Below is an example which serves different pages based on our613ad-hoc <em>NotFound</em> exception:</p>614615<pre><code>function NotFound(msg){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 616–618why, one step back
616 this.name = 'NotFound';
617 Error.call(this, msg);618 Error.captureStackTrace(this, arguments.callee);

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 619–620why, one step back
619}
620

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 621why, one step back
621NotFound.protoype.__proto__ = Error.prototype;

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 622–623why, one step back
622
623app.get('/404', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 624why, one step back
624 throw new NotFound;

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 625–627why, one step back
625});
626627app.get('/500', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 628why, one step back
628 throw new Error('keyboard cat!');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 629why, one step back
629});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 630–635why, one step back
630
631<p>We can call <em>app.error()</em> several times as shown below.632Here we check for an instanceof <em>NotFound</em> and show the633404 page, or we pass on to the next error handler.</p>634635<p>Note that these handlers can be defined anywhere, as they

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 636why, one step back
636will be placed below the route handlers on <em>listen()</em>. This

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 637–645why, one step back
637allows for definition within <em>configure()</em> blocks so we can
638handle exceptions in different ways based on the environment.</p>639640<pre><code>app.error(function(err, req, res, next){641 if (err instanceof NotFound) {642 res.render('404.jade');643 } else {644 next(err);645 }

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 646why, one step back
646});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 647–648why, one step back
647
648<p>Here we assume all errors as 500 for the simplicity of

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 649why, one step back
649this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the <em>error.code</em> of <em>ENOENT</em>, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 650–651why, one step back
650
651<pre><code>app.error(function(err, req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 652–654why, one step back
652 res.render('500.jade', {
653 error: err654 });

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 655why, one step back
655});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 656–657why, one step back
656
657<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 658why, one step back
658to report on exceptions. For example if we wish to output exceptions

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 659–660why, one step back
659in "development" mode to <em>stderr</em> we can use:</p>
660

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 661why, one step back
661<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 662–665why, one step back
662
663<p>Also during development we may want fancy html pages to show exceptions664that are passed or thrown, so we can set <em>showStack</em> to true:</p>665

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 666why, one step back
666<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 667–670why, one step back
667
668<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>669is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>670

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 671why, one step back
671<h3 id="Route-Param-Pre-conditions">Route Param Pre-conditions</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 672why, one step back
672

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 673why, one step back
673<p>Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for <em>/user/:id</em>, we might typically do something like below:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 674–679why, one step back
674
675<pre><code>app.get('/user/:userId', function(req, res, next){676 User.get(req.params.userId, function(err, user){677 if (err) return next(err);678 res.send('user ' + user.name);679 });

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 680why, one step back
680}); </code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 681why, one step back
681

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 682why, one step back
682<p>With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 683–690why, one step back
683
684<pre><code>app.param('userId', function(req, res, next, id){685 User.get(id, function(err, user){686 if (err) return next(err);687 if (!user) return next(new Error('failed to find user'));688 req.user = user;689 next();690 });

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 691why, one step back
691});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 692–696why, one step back
692
693<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>694695<pre><code>app.get('/user/:userId', function(req, res){696 res.send('user ' + req.user.name);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 697why, one step back
697});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 698–700why, one step back
698
699<p>For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to <em>next(err)</em>.</p>700

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 701why, one step back
701<pre><code>app.param('number', function(n){ return parseInt(n, 10); });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 702–704why, one step back
702
703<p>We may also apply the same callback to several placeholders, for example a route GET <em>/commits/:from-:to</em> are both numbers, so we may define them as an array:</p>704

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 705why, one step back
705<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 706–708why, one step back
706
707<h3 id="View-Rendering">View Rendering</h3>708

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 709why, one step back
709<p>View filenames take the form "&amp;lt;name&amp;gt;.&amp;lt;engine&amp;gt;", where &amp;lt;engine&amp;gt; is the name

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 710why, one step back
710of the module that will be required. For example the view <em>layout.ejs</em> will

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 711–712why, one step back
711tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.compile(str, options)</em>, and return a <em>Function</em> to comply with Express. To alter this behaviour
712<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 713why, one step back
713

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 714why, one step back
714<p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 715why, one step back
715and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 716why, one step back
716the <em>body</em> local variable in <em>layout.jade</em>.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 717–718why, one step back
717
718<pre><code>app.get('/', function(req, res){

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 719–720why, one step back
719 res.render('index.jade', { title: 'My Site' });
720});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 721–722why, one step back
721
722<p>The new <em>view engine</em> setting allows us to specify our default template engine,

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 723why, one step back
723so for example when using jade we could set:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 724why, one step back
724

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 725why, one step back
725<pre><code>app.set('view engine', 'jade');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 726–728why, one step back
726
727<p>Allowing us to render with:</p>728

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 729why, one step back
729<pre><code>res.render('index');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 730–732why, one step back
730
731<p>vs:</p>732

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 733why, one step back
733<pre><code>res.render('index.jade');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 734–737why, one step back
734
735<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still736mix and match template engines:</p>737

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 738why, one step back
738<pre><code>res.render('another-page.ejs');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 739–742why, one step back
739
740<p>Express also provides the <em>view options</em> setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:</p>741742<pre><code>app.set('view options', {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 743why, one step back
743 layout: false

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 744why, one step back
744});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 745why, one step back
745

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 746why, one step back
746<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 747why, one step back
747

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 748why, one step back
748<pre><code>res.render('myview.ejs', { layout: true });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 749–751why, one step back
749
750<p>When an alternate layout is required, we may also specify a path. For example if we have <em>view engine</em> set to <em>jade</em> and a file named <em>./views/mylayout.jade</em> we can simply pass:</p>751

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 752why, one step back
752<pre><code>res.render('page', { layout: 'mylayout' });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 753–755why, one step back
753
754<p>Otherwise we must specify the extension:</p>755

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 756why, one step back
756<pre><code>res.render('page', { layout: 'mylayout.jade' });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 757–759why, one step back
757
758<p>These paths may also be absolute:</p>759

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 760why, one step back
760<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 761–766why, one step back
761
762<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>763764<pre><code>app.set('view options', {765 open: '{{',766 close: '}}'

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 767why, one step back
767});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 768–770why, one step back
768
769<h3 id="View-Partials">View Partials</h3>770

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 771why, one step back
771<p>The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 772why, one step back
772in a view to display comments, we could use partial collection:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 773why, one step back
773

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 774why, one step back
774<pre><code>partial('comment', { collection: comments });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 775why, one step back
775

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 776why, one step back
776<p>If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 777why, one step back
777

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 778why, one step back
778<pre><code>partial('comment', comments);</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 779why, one step back
779

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 780why, one step back
780<p>When using the partial collection support a few "magic" locals are provided

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 781–782why, one step back
781for free:</p>
782

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 783why, one step back
783<ul><li><em>firstInCollection</em> true if this is the first object</li><li><em>indexInCollection</em> index of the object in the collection</li><li><em>lastInCollection</em> true if this is the last object</li><li><em>collectionLength</em> length of the collection</li></ul>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 784why, one step back
784

docsTj Holowaychukbefore adoption4609984

lines 785–786why, one step back
785<p>Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well. So for example if we were to render a blog post with <em>partial('blog/post', post)</em> it would generate the <em>post</em> local, but the view calling this function had the local <em>user</em>, it would be available to the <em>blog/post</em> view as well.</p>
786

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 787–788why, one step back
787<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>
788

view lookup docsTj Holowaychukbefore adoption8a62f8c

lines 789–795why, one step back
789<p><strong>NOTE:</strong> be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead.</p>
790791<h3 id="View-Lookup">View Lookup</h3>792793<p>View lookup is performed relative to the parent view, for example if we had a page view named <em>views/user/list.jade</em>, and within that view we did <em>partial('edit')</em> it would attempt to load <em>views/user/edit.jade</em>, whereas <em>partial('../messages')</em> would load <em>views/messages.jade</em>.</p>794795<p>The view system also allows for index templates, allowing you to have a directory of the same name. For example within a route we may have <em>res.render('users')</em> either <em>views/users.jade</em>, or <em>views/users/index.jade</em>.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 796why, one step back
796

more docsTj Holowaychukbefore adoption0b6a941

lines 797–798why, one step back
797<p>When utilizing index views as shown above, we may reference <em>views/users/index.jade</em> from a view in the same directory by <em>partial('users')</em>, and the view system will try <em>../users/index</em>, preventing us from needing to call <em>partial('index')</em>.</p>
798

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 799–802why, one step back
799<h3 id="Template-Engines">Template Engines</h3>
800801<p>Below are a few template engines commonly used with Express:</p>802

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 803why, one step back
803<ul><li><a href="http://github.com/visionmedia/haml.js">Haml</a> haml implementation</li><li><a href="http://jade-lang.com">Jade</a> haml.js successor</li><li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li><li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li><li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li></ul>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 804–806why, one step back
804
805<h3 id="Session-Support">Session Support</h3>806

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 807why, one step back
807<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieParser</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 808why, one step back
808

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 809why, one step back
809<pre><code>app.use(express.cookieParser());

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 810why, one step back
810app.use(express.session({ secret: "keyboard cat" }));</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 811–814why, one step back
811
812<p>By default the <em>session</em> middleware uses the memory store bundled with Connect, however many implementations exist. For example <a href="http://github.com/visionmedia/connect-redis">connect-redis</a> supplies a <a href="http://code.google.com/p/redis/">Redis</a> session store and can be used as shown below:</p>813814<pre><code>var RedisStore = require('connect-redis');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 815why, one step back
815app.use(express.cookieParser());

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 816why, one step back
816app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 817–820why, one step back
817
818<p>Now the <em>req.session</em> and <em>req.sessionStore</em> properties will be accessible to all routes and subsequent middleware. Properties on <em>req.session</em> are automatically saved on a response, so for example if we wish to shopping cart data:</p>819820<pre><code>var RedisStore = require('connect-redis');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 821–823why, one step back
821app.use(express.bodyParser());
822app.use(express.cookieParser());823app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 824–826why, one step back
824
825app.post('/add-to-cart', function(req, res){826 // Perhaps we posted several items with a form

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 827why, one step back
827 // (use the bodyParser() middleware for this)

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 828–840why, one step back
828 var items = req.body.items;
829 req.session.items = items;830 res.redirect('back');831});832833app.get('/add-to-cart', function(req, res){834 // When redirected back to GET /add-to-cart835 // we could check req.session.items &amp;&amp; req.session.items.length836 // to print out a message837 if (req.session.items &amp;&amp; req.session.items.length) {838 req.flash('info', 'You have %s items in your cart', req.session.items.length);839 }840 res.render('shopping-cart');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 841why, one step back
841});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 842why, one step back
842

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 843why, one step back
843<p>The <em>req.session</em> object also has methods such as <em>Session#touch()</em>, <em>Session#destroy()</em>, <em>Session#regenerate()</em> among others to maintain and manipulate sessions. For more information view the <a href="http://senchalabs.github.com/connect/middleware-session.html">Connect Session</a> documentation.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 844why, one step back
844

docsTj Holowaychukbefore adoption5581ca2

line 845why, one step back
845<h3 id="Migration-Guide">Migration Guide</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 846why, one step back
846

docsTj Holowaychukbefore adoptionc1a82bf

line 847why, one step back
847<p> Express 1.x developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application to work with Express 2.x, Connect 1.x, and Node 0.4.x.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 848why, one step back
848

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 849why, one step back
849<h3 id="req-header-key-defaultValue">req.header(key[, defaultValue])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 850–854why, one step back
850
851<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>852853<pre><code>req.header('Host');854req.header('host');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 855why, one step back
855req.header('Accept', '*/*');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 856why, one step back
856

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 857–864why, one step back
857<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>
858859<pre><code>// sent Referrer: http://google.com860861req.header('Referer');862// =&gt; "http://google.com"863864req.header('Referrer');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 865why, one step back
865// =&gt; "http://google.com"</code></pre>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 866why, one step back
866

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 867why, one step back
867<h3 id="req-accepts-type">req.accepts(type)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 868–888why, one step back
868
869<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>870871<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise872the given <em>type</em> is matched by an exact match, and then subtypes. You873may pass the subtype such as "html" which is then converted internally874to "text/html" using the mime lookup table.</p>875876<pre><code>// Accept: text/html877req.accepts('html');878// =&gt; true879880// Accept: text/*; application/json881req.accepts('html');882req.accepts('text/html');883req.accepts('text/plain');884req.accepts('application/json');885// =&gt; true886887req.accepts('image/png');888req.accepts('png');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 889why, one step back
889// =&gt; false</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 890why, one step back
890

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 891why, one step back
891<h3 id="req-is-type">req.is(type)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 892–906why, one step back
892
893<p>Check if the incoming request contains the <em>Content-Type</em>894header field, and it contains the give mime <em>type</em>.</p>895896<pre><code> // With Content-Type: text/html; charset=utf-8897 req.is('html');898 req.is('text/html');899 // =&gt; true900901 // When Content-Type is application/json902 req.is('json');903 req.is('application/json');904 // =&gt; true905906 req.is('html');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 907why, one step back
907 // =&gt; false</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 908–915why, one step back
908
909<p>Ad-hoc callbacks can also be registered with Express, to perform910assertions again the request, for example if we need an expressive911way to check if our incoming request is an image, we can register <em>"an image"</em>912callback:</p>913914<pre><code> app.is('an image', function(req){915 return 0 == req.headers['content-type'].indexOf('image');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 916why, one step back
916 });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 917–926why, one step back
917
918<p>Now within our route callbacks, we can use to to assert content types919such as <em>"image/jpeg"</em>, <em>"image/png"</em>, etc.</p>920921<pre><code> app.post('/image/upload', function(req, res, next){922 if (req.is('an image')) {923 // do something924 } else {925 next();926 }

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 927why, one step back
927 });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 928–933why, one step back
928
929<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you930can perform any request assertion you wish.</p>931932<p>Wildcard matches can also be made, simplifying our example above for <em>"an image"</em>, by asserting the <em>subtype</em> only:</p>933

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 934why, one step back
934<pre><code>req.is('image/*');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 935–937why, one step back
935
936<p>We may also assert the <em>type</em> as shown below, which would return true for <em>"application/json"</em>, and <em>"text/json"</em>.</p>937

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 938why, one step back
938<pre><code>req.is('*/json');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 939why, one step back
939

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 940why, one step back
940<h3 id="req-param-name-default">req.param(name[, default])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 941why, one step back
941

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 942why, one step back
942<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 943why, one step back
943

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 944why, one step back
944<ul><li>Checks route params (<em>req.params</em>), ex: /user/:id</li><li>Checks query string params (<em>req.query</em>), ex: ?id=12</li><li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li></ul>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 945–947why, one step back
945
946<p>To utilize urlencoded request bodies, <em>req.body</em>947should be an object. This can be done by using

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 948why, one step back
948the _express.bodyParser middleware.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 949why, one step back
949

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 950why, one step back
950<h3 id="req-flash-type-msg">req.flash(type[, msg])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 951–965why, one step back
951
952<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>953954<pre><code>req.flash('info', 'email sent');955req.flash('error', 'email delivery failed');956req.flash('info', 'email re-sent');957// =&gt; 2958959req.flash('info');960// =&gt; ['email sent', 'email re-sent']961962req.flash('info');963// =&gt; []964965req.flash();

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 966why, one step back
966// =&gt; { error: ['email delivery failed'], info: [] }</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 967–969why, one step back
967
968<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>969

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 970why, one step back
970<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 971–977why, one step back
971
972<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>973974<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header975to see if it was issued by an <em>XMLHttpRequest</em>:</p>976977<pre><code>req.xhr

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 978why, one step back
978req.isXMLHttpRequest</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 979why, one step back
979

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 980why, one step back
980<h3 id="res-header-key-val">res.header(key[, val])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 981–990why, one step back
981
982<p>Get or set the response header <em>key</em>.</p>983984<pre><code>res.header('Content-Length');985// =&gt; undefined986987res.header('Content-Length', 123);988// =&gt; 123989990res.header('Content-Length');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 991why, one step back
991// =&gt; 123</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 992why, one step back
992

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 993why, one step back
993<h3 id="res-charset">res.charset</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 994why, one step back
994

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 995–1012why, one step back
995<p>Sets the charset for subsequent <code>Content-Type</code> header fields. For example <code>res.send()</code> and <code>res.render()</code> default to "utf8", so we may explicitly set the charset before rendering a template:</p>
996997<pre><code>res.charset = 'ISO-8859-1';998res.render('users');</code></pre>9991000<p>or before responding with <code>res.send()</code>:</p>10011002<pre><code>res.charset = 'ISO-8859-1';1003res.send(str);</code></pre>10041005<p>or with node's <code>res.end()</code>:</p>10061007<pre><code>res.charset = 'ISO-8859-1';1008res.header('Content-Type', 'text/plain');1009res.end(str);</code></pre>10101011<h3 id="res-contentType-type">res.contentType(type)</h3>1012

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1013–1016why, one step back
1013<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>
10141015<pre><code> var filename = 'path/to/image.png';1016 res.contentType(filename);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1017why, one step back
1017 // Content-Type is now "image/png"</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1018why, one step back
1018

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1019why, one step back
1019<p>A literal <em>Content-Type</em> works as well:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1020why, one step back
1020

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 1021–1028why, one step back
1021<pre><code> res.contentType('application/json');</code></pre>
10221023<p>Or simply the extension without leading <code>.</code>:</p>10241025<pre><code> res.contentType('json');</code></pre>10261027<h3 id="res-attachment-filename">res.attachment([filename])</h3>1028

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1029–1030why, one step back
1029<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>
1030

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1031why, one step back
1031<pre><code> res.attachment('path/to/my/image.png');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1032why, one step back
1032

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1033why, one step back
1033<h3 id="res-sendfile-path-options-callback">res.sendfile(path[, options[, callback]])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1034why, one step back
1034

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1035why, one step back
1035<p>Used by <code>res.download()</code> to transfer an arbitrary file. </p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1036why, one step back
1036

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1037why, one step back
1037<pre><code>res.sendfile('path/to/my.file');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1038why, one step back
1038

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1039–1040why, one step back
1039<p>This method accepts an optional callback which is called when
1040an error occurs, or when the transfer is complete. By default failures call <code>next(err)</code>, however when a callback is supplied you must do this explicitly, or act on the error.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1041why, one step back
1041

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1042why, one step back
1042<pre><code>res.sendfile(path, function(err){

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1043why, one step back
1043 if (err) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1044why, one step back
1044 next(err);

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1045–1047why, one step back
1045 } else {
1046 console.log('transferred %s', path);1047 }

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1048why, one step back
1048});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1049why, one step back
1049

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1050why, one step back
1050<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1051why, one step back
1051

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1052–1053why, one step back
1052<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){
1053 // handle

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1054why, one step back
1054});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1055why, one step back
1055

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1056why, one step back
1056<h3 id="res-download-file-filename-callback">res.download(file[, filename[, callback]])</h3>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1057why, one step back
1057

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1058–1060why, one step back
1058<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>
10591060<pre><code>res.download('path/to/image.png');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1061why, one step back
1061res.download('path/to/image.png', 'foo.png');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1062–1065why, one step back
1062
1063<p>This is equivalent to:</p>10641065<pre><code>res.attachment(file);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1066why, one step back
1066res.sendfile(file);</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1067why, one step back
1067

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1068–1071why, one step back
1068<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>:</p>
10691070<pre><code>res.download(path, 'expenses.doc', function(err){1071 // handle

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1072why, one step back
1072});</code></pre>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1073why, one step back
1073

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1074why, one step back
1074<h3 id="res-send-body-status-headers-status-status">res.send(body|status[, headers|status[, status]])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1075why, one step back
1075

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1076–1077why, one step back
1076<p>The <em>res.send()</em> method is a high level response utility allowing you to pass
1077objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1078–1084why, one step back
1078
1079<pre><code> res.send(); // 2041080 res.send(new Buffer('wahoo'));1081 res.send({ some: 'json' });1082 res.send('&lt;p&gt;some html&lt;/p&gt;');1083 res.send('Sorry, cant find that', 404);1084 res.send('text', { 'Content-Type': 'text/plain' }, 201);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1085why, one step back
1085 res.send(404);</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1086–1090why, one step back
1086
1087<p>By default the <em>Content-Type</em> response header is set, however if explicitly1088assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1089it will not be set again.</p>1090

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1091why, one step back
1091<p>Note that this method <em>end()</em>s the response, so you will want to use node's <em>res.write()</em> for multiple writes or streaming.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1092why, one step back
1092

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1093why, one step back
1093<h3 id="res-redirect-url-status">res.redirect(url[, status])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1094–1100why, one step back
1094
1095<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>10961097<pre><code>res.redirect('/', 301);1098res.redirect('/account');1099res.redirect('http://google.com');1100res.redirect('home');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1101why, one step back
1101res.redirect('back');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1102–1106why, one step back
1102
1103<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1104The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1105the "home" setting and defaults to "/".</p>1106

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1107why, one step back
1107<h3 id="res-cookie-name-val-options">res.cookie(name, val[, options])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1108why, one step back
1108

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1109why, one step back
1109<p>Sets the given cookie <em>name</em> to <em>val</em>, with options <em>httpOnly</em>, <em>secure</em>, <em>expires</em> etc.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1110–1111why, one step back
1110
1111<pre><code>// "Remember me" for 15 minutes

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1112why, one step back
1112res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1113why, one step back
1113

docsTj Holowaychukbefore adoption131970b

lines 1114–1115why, one step back
1114<p>The <em>maxAge</em> property may be used to set <em>expires</em> relative to <em>Date.now()</em> in milliseconds, so our example above can now become:</p>
1115

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1116why, one step back
1116<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });</code></pre>

docsTj Holowaychukbefore adoption131970b

line 1117why, one step back
1117

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1118–1119why, one step back
1118<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>
1119

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1120why, one step back
1120<pre><code>app.use(express.cookieParser());

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1121–1122why, one step back
1121
1122app.get('/', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1123why, one step back
1123 // use req.cookies.rememberme

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1124why, one step back
1124});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1125why, one step back
1125

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1126why, one step back
1126<h3 id="res-clearCookie-name">res.clearCookie(name)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1127–1129why, one step back
1127
1128<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>1129

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1130why, one step back
1130<pre><code>res.clearCookie('rememberme');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1131why, one step back
1131

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1132why, one step back
1132<h3 id="res-render-view-options-fn">res.render(view[, options[, fn]])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1133–1137why, one step back
1133
1134<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1135When a callback function is given a response will <em>not</em> be made1136automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>1137

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1138why, one step back
1138<p>The <em>options</em> passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1139why, one step back
1139

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1140why, one step back
1140<pre><code>var user = { name: 'tj' };

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1141why, one step back
1141res.render('index', { layout: false, user: user });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1142why, one step back
1142

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1143why, one step back
1143<h3 id="res-partial-view-options">res.partial(view[, options])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1144–1147why, one step back
1144
1145<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1146to the view as a local variable.</p>1147

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 1148–1149why, one step back
1148<ul><li><em>object</em> the object named by <em>as</em> or derived from the view name</li><li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p><ul><li>as: 'something' will add the <em>something</em> local variable</li><li>as: this will use the collection value as the template context</li><li><p>as: global will merge the collection value's properties with <em>locals</em></p></li></ul></li><li><p><em>collection</em> Array of objects, the name is derived from the view name itself.
1149For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li></ul>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1150–1158why, one step back
1150
1151<p>The following are equivalent, and the name of collection value when passed1152to the partial will be <em>movie</em> as derived from the name.</p>11531154<pre><code>partial('theatre/movie.jade', { collection: movies });1155partial('theatre/movie.jade', movies);1156partial('movie.jade', { collection: movies });1157partial('movie.jade', movies);1158partial('movie', movies);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1159why, one step back
1159// In view: movie.director</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1160–1163why, one step back
1160
1161<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>11621163<pre><code>partial('movie', { collection: movies, as: 'video' });

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1164why, one step back
1164// In view: video.director</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1165–1169why, one step back
1165
1166<p>Also we can make our movie the value of <em>this</em> within our view so that instead1167of <em>movie.director</em> we could use <em>this.director</em>.</p>11681169<pre><code>partial('movie', { collection: movies, as: this });

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1170why, one step back
1170// In view: this.director</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1171why, one step back
1171

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1172why, one step back
1172<p>Another alternative is to "expand" the properties of the collection item into

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1173–1175why, one step back
1173pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>
11741175<pre><code>partial('movie', { collection: movies, as: global });

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1176why, one step back
1176// In view: director</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1177–1189why, one step back
1177
1178<p>This same logic applies to a single partial object usage:</p>11791180<pre><code>partial('movie', { object: movie, as: this });1181// In view: this.director11821183partial('movie', { object: movie, as: global });1184// In view: director11851186partial('movie', { object: movie, as: 'video' });1187// In view: video.director11881189partial('movie', { object: movie });

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1190why, one step back
1190// In view: movie.director</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1191–1193why, one step back
1191
1192<p>When a non-collection (does <em>not</em> have <em>.length</em>) is passed as the second argument, it is assumed to be the <em>object</em>, after which the object's local variable name is derived from the view name:</p>1193

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 1194–1196why, one step back
1194<pre><code>var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')
1195partial('movie', movie)1196// =&gt; In view: movie.director</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1197why, one step back
1197

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 1198–1208why, one step back
1198<p>The exception of this, is when a "plain" object, aka "{}" or "new Object" is passed, which is considered an object with local variable. For example some may expect a "movie" local with the following, however since it is a plain object "director" and "title" are simply locals:</p>
11991200<pre><code>var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1201partial('movie', movie)</code></pre>12021203<p>For cases like this where passing a plain object is desired, simply assign it to a key, or use the <code>object</code> key which will use the filename-derived variable name. The examples below are equivalent:</p>12041205<pre><code> partial('movie', { locals: { movie: movie }})1206 partial('movie', { movie: movie })1207 partial('movie', { object: movie })</code></pre>1208

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1209–1221why, one step back
1209<p>This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:</p>
12101211<pre><code>app.get('/users', function(req, res){1212 if (req.xhr) {1213 // respond with the each user in the collection1214 // passed to the "user" view1215 res.partial('user', users);1216 } else {1217 // respond with layout, and users page1218 // which internally does partial('user', users)1219 // along with other UI1220 res.render('users', { users: users });1221 }

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1222why, one step back
1222});</code></pre>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1223why, one step back
1223

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1224why, one step back
1224<h3 id="res-local-name-val">res.local(name[, val])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1225–1238why, one step back
1225
1226<p>Get or set the given local variable <em>name</em>. The locals built up for a response are applied to those given to the view rendering methods such as <code>res.render()</code>.</p>12271228<pre><code> app.all('/movie/:id', function(req, res, next){1229 Movie.get(req.params.id, function(err, movie){1230 // Assigns res.locals.movie = movie1231 res.local('movie', movie);1232 });1233 });12341235 app.get('/movie/:id', function(req, res){1236 // movie is already a local, however we1237 // can pass more if we wish1238 res.render('movie', { displayReviews: true });

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1239why, one step back
1239 });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1240why, one step back
1240

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1241why, one step back
1241<h3 id="res-local-obj">res.local(obj)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1242why, one step back
1242

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 1243–1251why, one step back
1243<p> Assign several locals with the given <em>obj</em>. The following are equivalent:</p>
12441245<pre><code> res.local('foo', bar);1246 res.local('bar', baz);12471248 res.locals({ foo: bar, bar, baz });</code></pre>12491250<h3 id="app-set-name-val">app.set(name[, val])</h3>1251

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1252–1256why, one step back
1252<p>Apply an application level setting <em>name</em> to <em>val</em>, or
1253get the value of <em>name</em> when <em>val</em> is not present:</p>12541255<pre><code>app.set('views', __dirname + '/views');1256app.set('views');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1257why, one step back
1257// =&gt; ...path...</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1258–1261why, one step back
1258
1259<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>12601261<pre><code>app.settings.views

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1262why, one step back
1262// =&gt; ...path...</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1263why, one step back
1263

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1264why, one step back
1264<h3 id="app-enable-name">app.enable(name)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1265–1272why, one step back
1265
1266<p>Enable the given setting <em>name</em>:</p>12671268<pre><code>app.enable('some arbitrary setting');1269app.set('some arbitrary setting');1270// =&gt; true12711272app.enabled('some arbitrary setting');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1273why, one step back
1273// =&gt; true</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1274why, one step back
1274

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1275why, one step back
1275<h3 id="app-enabled-name">app.enabled(name)</h3>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1276–1283why, one step back
1276
1277<p>Check if setting <em>name</em> is enabled:</p>12781279<pre><code>app.enabled('view cache');1280// =&gt; false12811282app.enable('view cache');1283app.enabled('view cache');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1284why, one step back
1284// =&gt; true</code></pre>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1285why, one step back
1285

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1286why, one step back
1286<h3 id="app-disable-name">app.disable(name)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1287–1294why, one step back
1287
1288<p>Disable the given setting <em>name</em>:</p>12891290<pre><code>app.disable('some setting');1291app.set('some setting');1292// =&gt; false12931294app.disabled('some setting');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1295why, one step back
1295// =&gt; false</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1296why, one step back
1296

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1297why, one step back
1297<h3 id="app-disabled-name">app.disabled(name)</h3>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1298–1307why, one step back
1298
1299<p>Check if setting <em>name</em> is disabled:</p>13001301<pre><code>app.enable('view cache');13021303app.disabled('view cache');1304// =&gt; false13051306app.disable('view cache');1307app.disabled('view cache');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1308why, one step back
1308// =&gt; true</code></pre>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1309why, one step back
1309

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1310why, one step back
1310<h3 id="app-configure-env-function-function">app.configure(env|function[, function])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1311–1319why, one step back
1311
1312<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>13131314<pre><code>app.configure(function(){1315 // executed for each env1316});13171318app.configure('development', function(){1319 // executed for 'development' only

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1320why, one step back
1320});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1321why, one step back
1321

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1322why, one step back
1322<h3 id="app-redirect-name-val">app.redirect(name, val)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1323why, one step back
1323

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1324why, one step back
1324<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1325why, one step back
1325

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1326why, one step back
1326<pre><code>app.redirect('google', 'http://google.com');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1327–1334why, one step back
1327
1328<p>Now in a route we may call:</p>13291330<p> res.redirect('google');</p>13311332<p>We may also map dynamic redirects:</p>13331334<pre><code>app.redirect('comments', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1335why, one step back
1335 return '/post/' + req.params.id + '/comments';

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1336why, one step back
1336});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1337–1342why, one step back
1337
1338<p>So now we may do the following, and the redirect will dynamically adjust to1339the context of the request. If we called this route with <em>GET /post/12</em> our1340redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>13411342<pre><code>app.get('/post/:id', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1343why, one step back
1343 res.redirect('comments');

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1344why, one step back
1344});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1345why, one step back
1345

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1346–1347why, one step back
1346<p>When mounted, <em>res.redirect()</em> will respect the mount-point. For example if a blog app is mounted at <em>/blog</em>, the following will redirect to <em>/blog/posts</em>:</p>
1347

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1348why, one step back
1348<pre><code>res.redirect('/posts');</code></pre>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1349why, one step back
1349

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1350why, one step back
1350<h3 id="app-error-function">app.error(function)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1351–1356why, one step back
1351
1352<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1353Note that we may set several error handlers by making several calls to this method, however the handler1354should call <em>next(err)</em> if it does not wish to deal with the exception:</p>13551356<pre><code>app.error(function(err, req, res, next){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1357why, one step back
1357 res.send(err.message, 500);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1358why, one step back
1358});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1359why, one step back
1359

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1360why, one step back
1360<h3 id="app-helpers-obj">app.helpers(obj)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1361–1363why, one step back
1361
1362<p>Registers static view helpers.</p>1363

regenerated docsTj Holowaychukbefore adoptiondd7158a

lines 1364–1368why, one step back
1364<p> app.helpers({
1365 name: function(first, last){ return first + ', ' + last }1366 , firstName: 'tj'1367 , lastName: 'holowaychuk'1368 });</p>

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1369why, one step back
1369

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1370–1372why, one step back
1370<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,
1371as well as the <em>name()</em> function exposed.</p>1372

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1373why, one step back
1373<pre><code>&lt;%= name(firstName, lastName) %&gt;</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1374why, one step back
1374

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1375why, one step back
1375<h3 id="app-dynamicHelpers-obj">app.dynamicHelpers(obj)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1376–1382why, one step back
1376
1377<p>Registers dynamic view helpers. Dynamic view helpers1378are simply functions which accept <em>req</em>, <em>res</em>, and are1379evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1380becomes the local variable it is associated with.</p>13811382<pre><code>app.dynamicHelpers({

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1383–1385why, one step back
1383 session: function(req, res){
1384 return req.session;1385 }

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1386why, one step back
1386});</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1387–1389why, one step back
1387
1388<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>1389

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1390why, one step back
1390<pre><code>&lt;%= session.name %&gt;</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1391why, one step back
1391

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1392why, one step back
1392<h3 id="app-mounted-fn">app.mounted(fn)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1393–1399why, one step back
1393
1394<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>13951396<pre><code>var app = express.createServer(),1397 blog = express.createServer();13981399blog.mounted(function(parent){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1400–1401why, one step back
1400 // parent is app
1401 // "this" is blog

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1402–1403why, one step back
1402});
1403

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1404why, one step back
1404app.use(blog);</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1405why, one step back
1405

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1406why, one step back
1406<h3 id="app-register-ext-exports">app.register(ext, exports)</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1407–1411why, one step back
1407
1408<p>Register the given template engine <em>exports</em>1409as <em>ext</em>. For example we may wish to map ".html"1410files to jade:</p>1411

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1412why, one step back
1412<pre><code> app.register('.html', require('jade'));</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1413–1418why, one step back
1413
1414<p>This is also useful for libraries that may not1415match extensions correctly. For example my haml.js1416library is installed from npm as "hamljs" so instead1417of layout.hamljs, we can register the engine as ".haml":</p>1418

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1419why, one step back
1419<pre><code> app.register('.haml', require('haml-js'));</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1420–1421why, one step back
1420
1421<p>For engines that do not comply with the Express

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1422–1425why, one step back
1422specification, we can also wrap their api this way. Below
1423we map <em>.md</em> to render markdown files, rendering the html once1424since it will not change on subsequent calls, and support local substitution1425in the form of "{name}".</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1426why, one step back
1426

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1427–1435why, one step back
1427<pre><code> app.register('.md', {
1428 compile: function(str, options){1429 var html = md.toHTML(str);1430 return function(locals){1431 return html.replace(/\{([^}]+)\}/g, function(_, name){1432 return locals[name];1433 });1434 };1435 }

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1436why, one step back
1436 });</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

line 1437why, one step back
1437

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1438why, one step back
1438<h3 id="app-listen-port-host">app.listen([port[, host]])</h3>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1439–1440why, one step back
1439
1440<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1441why, one step back
1441connections will be accepted via <em>INADDR</em>ANY_.</p>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1442–1444why, one step back
1442
1443<pre><code>app.listen();1444app.listen(3000);

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1445why, one step back
1445app.listen(3000, 'n.n.n.n');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1446–1448why, one step back
1446
1447<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>1448

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1449why, one step back
1449<pre><code>app.listen('/tmp/express.sock');</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1450–1459why, one step back
1450
1451<p>Then try it out:</p>14521453<pre><code>$ telnet /tmp/express.sock1454GET / HTTP/1.114551456HTTP/1.1 200 OK1457Content-Type: text/plain1458Content-Length: 111459

regenerated docsTj Holowaychukbefore adoptiondd7158a

line 1460why, one step back
1460Hello World</code></pre>

Updated jade submoduleTj Holowaychukbefore adoption242efc7

lines 1461–1464why, one step back
1461 </div>
1462 </div>1463 </body>1464</html>