Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,271 lines · 42.3 KiB · HTML

Last changed by

Regenerated docsTj Holowaychukbefore adoption0faac20

History of this file

Take it

The walk stopped after 200 commits: lines older than 6e40914 point at it.

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 1–3why, one step back
1<html>
2 <head>3 <title>Express - node web framework</title>

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 4why, one step back
4 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 5–18why, one step back
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;

antialiased textTj Holowaychukbefore adoption8d80f23

line 19why, one step back
19 -webkit-font-smoothing: antialiased;

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 20–41why, one step back
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; }41

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

line 42why, one step back
42 h1, h2, h3, h4 {

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 43–48why, one step back
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; }

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 49–52why, one step back
49 h4 {
50 margin-left: 10px;51 font-size: 14px;52 }

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 53–73why, one step back
53
54 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; }

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 74–77why, one step back
74 ul li ul {
75 margin: 0;76 padding-left: 12px;77 }

No more http git submodulesTj Holowaychukbefore adoption6e40914

line 78why, one step back
78

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 79–80why, one step back
79 .man-name, #Express { display:none; }
80

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 81–109why, one step back
81 .sect {
82 margin-left: 40px; }8384 #logo {85 display: block;86 margin-left: 30%;87 margin-bottom: 30px;88 width: 194px;89 height: 51px;90 background: url(images/logo.png) 0 0 no-repeat;91 text-indent: -99999px; }92 #logo:hover {93 opacity: 0.7; }94 #logo:active {95 opacity: 0.3; }9697 #ribbon {98 position: fixed;99 top: 0;100 right: 0;101 z-index: 2; }102103 #wrapper {104 width: 100%;105 min-height: 800px;106 background: url(images/top.png) 0 0 repeat-x; }107108 #container {109 margin: 0 auto;

Regenerated docs againTj Holowaychukbefore adoption8ead901

line 110why, one step back
110 padding-top: 80px;

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 111–114why, one step back
111 width: 550px; }
112113 #toc {114 position: fixed;

Regenerated docs againTj Holowaychukbefore adoption8ead901

line 115why, one step back
115 top: 0;

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 116–120why, one step back
116 left: 0;
117 margin: 0 0 0 15px;118 padding: 15px;119 height: 100%;120 background: rgba(0,0,0,0.2);

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

line 121why, one step back
121 overflow: auto;

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 122–158why, one step back
122 border-right: 1px solid rgba(255,255,255,0.05);
123 }124 #toc li {125 padding: 0;126 list-style: none;127 }128 #toc li a {129 font-size: 11px;130 }131 #menu {132 margin-left: 65px;133 padding: 0;134 padding-bottom: 30px; }135 #menu li {136 display: inline;137 list-style: none; }138 #menu li a {139 display: block;140 float: left;141 margin: 0 2px;142 padding: 3px 15px;143 background: rgba(0,0,0,0.2);144 -webkit-border-radius: 8px;145 -moz-border-radius: 8px;146 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);147 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);148 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;149 -webkit-transition-duration: 0.15s;150 -webkit-transition-timing-function: ease-out; }151 #menu li a:hover,152 #menu li a.active {153 background: rgba(0,0,0,0.5); }154 #menu li a:active {155 background: rgba(0,0,0,0.1);156 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);157 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }158 </style>

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 159–170why, one step back
159 <script>
160 $(function(){161 $('.section').hide();162 $('.toggle, a.section-title').toggle(function(){163 $(this).siblings('ul').fadeIn(300);164 return false;165 }, function(){166 $(this).siblings('ul').fadeOut(300);167 return false;168 });169 });170 </script>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 171–183why, one step back
171 </head>
172 <body>173 <a href='http://github.com/visionmedia/express'> 174 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 175 </a>176 <div id="wrapper">177 <div id="container"><ul id="toc">178<li><a href="#Installation">Installation</a></li>179<li><a href="#Creating-An-Application">Creating An Application</a></li>180<li><a href="#Configuration">Configuration</a></li>181<li><a href="#Settings">Settings</a></li>182<li><a href="#Routing">Routing</a></li>183<li><a href="#Passing-Route-Control">Passing Route Control</a></li>

Regenerated docsTj Holowaychukbefore adoption090debe

line 184why, one step back
184<li><a href="#Middleware">Middleware</a></li>

Regenerated docsTj Holowaychukbefore adoption334a18a

line 185why, one step back
185<li><a href="#Route-Middleware">Route Middleware</a></li>

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

line 186why, one step back
186<li><a href="#HTTP-Methods">HTTP Methods</a></li>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 187–190why, one step back
187<li><a href="#Error-Handling">Error Handling</a></li>
188<li><a href="#View-Rendering">View Rendering</a></li>189<li><a href="#View-Partials">View Partials</a></li>190<li><a href="#Template-Engines">Template Engines</a></li>

Rebuilt docsTj Holowaychukbefore adoption2724ce3

line 191why, one step back
191<li><a href="#Session-Support">Session Support</a></li>

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 192–224why, one step back
192<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">
193<li><a href="#req-header-key-defaultValue-">header()</a></li>194<li><a href="#req-accepts-type-">accepts()</a></li>195<li><a href="#req-param-name-">param()</a></li>196<li><a href="#req-flash-type-msg-">flash()</a></li>197<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>198</ul></li>199<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">200<li><a href="#res-header-key-val-">header()</a></li>201<li><a href="#res-contentType-type-">contentType()</a></li>202<li><a href="#res-attachment-filename-">attachment()</a></li>203<li><a href="#res-sendfile-path-">sendfile()</a></li>204<li><a href="#res-download-file-filename-">download()</a></li>205<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>206<li><a href="#res-redirect-url-status-">redirect()</a></li>207<li><a href="#res-cookie-name-val-options-">cookie()</a></li>208<li><a href="#res-clearCookie-name-">clearCookie()</a></li>209<li><a href="#res-render-view-options-fn-">render()</a></li>210<li><a href="#res-partial-view-options-">partial()</a></li>211</ul></li>212<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">213<li><a href="#app-set-name-val-">set()</a></li>214<li><a href="#app-enable-name-">enable()</a></li>215<li><a href="#app-disable-name-">disable()</a></li>216<li><a href="#app-configure-env-function-function-">configure()</a></li>217<li><a href="#app-redirect-name-val-">redirect()</a></li>218<li><a href="#app-error-function-">error()</a></li>219<li><a href="#app-helpers-obj-">helpers()</a></li>220<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>221<li><a href="#app-mounted-fn-">mounted()</a></li>222<li><a href="#app-register-ext-exports-">register()</a></li>223<li><a href="#app-listen-port-host-">listen()</a></li>224</ul></li>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 225–237why, one step back
225</ul>
226 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 227 <p id="tagline">228 High performance, high class web development for229 <a href="http://nodejs.org">Node.js</a>230 </p>231 <ul id="menu">232 <li><a href="index.html">Home</a></li>233 <li><a href="guide.html">Guide</a></li>234 <li><a href="contrib.html">Contributing</a></li>235 <li><a href="migrate.html">1.x Migration</a></li>236 </ul>237<div class='mp'>

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 238–241why, one step back
238<h2 id="Express">Express</h2>
239<p class="man-name">240 <code>guide</code>241</p>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 242–250why, one step back
242<h3 id="Installation">Installation</h3>
243244<p>curl:</p>245246<pre><code>$ curl -# http://expressjs.com/install.sh | sh247</code></pre>248249<p>npm:</p>250

Added "Apps using express" section, PM me to add to the listTj Holowaychukbefore adoption7328842

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

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 252–283why, one step back
252</code></pre>
253254<p>git clone, first update the submodules:</p>255256<pre><code>$ git submodule update --init257$ make install258$ make install-support259</code></pre>260261<h3 id="Creating-An-Application">Creating An Application</h3>262263<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however264follows the same idiom by providing <em>express.createServer()</em> as shown below. This means265that you can utilize Express server's transparently with other libraries.</p>266267<pre><code>var app = require('express').createServer();268269app.get('/', function(req, res){270 res.send('hello world');271});272273app.listen(3000);274</code></pre>275276<h3 id="Configuration">Configuration</h3>277278<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers279can use the <em>configure()</em> method to setup needs required by the current environment. When280<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment281prior to the environment specific callback.</p>282283<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

lines 284–286why, one step back
284in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.
285Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,286otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>

No more http git submodulesTj Holowaychukbefore adoption6e40914

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 289–290why, one step back
289 app.use(express.methodOverride());
290 app.use(express.bodyDecoder());

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

line 291why, one step back
291 app.use(app.router);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 292why, one step back
292 app.use(express.staticProvider(__dirname + '/public'));

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 293–295why, one step back
293});
294295app.configure('development', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

No more http git submodulesTj Holowaychukbefore adoption6e40914

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 301–318why, one step back
301});
302</code></pre>303304<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>305306<pre><code>app.configure(function(){307 app.set('views', __dirname + '/views');308 app.set('views');309 // =&gt; "... views directory ..."310311 app.enable('some feature');312 // same as app.set('some feature', true);313314 app.disable('some feature');315 // same as app.set('some feature', false);316});317</code></pre>318

Rebuilt docsTj Holowaychukbefore adoption2724ce3

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

No more http git submodulesTj Holowaychukbefore adoption6e40914

line 320why, one step back
320

Rebuilt docsTj Holowaychukbefore adoption2724ce3

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

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 322–329why, one step back
322</code></pre>
323324<h3 id="Settings">Settings</h3>325326<p>Express supports the following settings out of the box:</p>327328<ul>329<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>

New "home" docsTj Holowaychukbefore adoption1e7a12f

line 330why, one step back
330<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 331–332why, one step back
331<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>
332<li><em>view engine</em> Default view engine name for views rendered without extensions</li>

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 333–334why, one step back
333<li><em>view options</em> An object specifying global view options</li>
334<li><em>partials</em> Root view partials directory defaulting to <em>views</em>/partials.</li>

Updated docsTj Holowaychukbefore adoptionf0eab06

line 335why, one step back
335<li><em>stream threshold</em> Bytesize indicating when a file should be streamed for <em>res.sendfile()</em> using <em>fs.ReadStream()</em> and <em>sys.pump()</em>.</li>

No more http git submodulesTj Holowaychukbefore adoption6e40914

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

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 343–344why, one step back
343can be done by defining the route below. The values associated to the named placeholders
344are available as <code>req.params</code>.</p>

No more http git submodulesTj Holowaychukbefore adoption6e40914

line 345why, one step back
345

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 346–347why, one step back
346<pre><code>app.get('/user/:id', function(req, res){
347 res.send('user ' + req.params.id);

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 348–357why, one step back
348});
349</code></pre>350351<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example352when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>353354<pre><code>\/user\/([^\/]+)\/?355</code></pre>356357<p>Regular expression literals may also be passed for complex uses. Since capture

Updated docsTj Holowaychukbefore adoptiond691ecb

line 358why, one step back
358groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>.</p>

No more http git submodulesTj Holowaychukbefore adoption6e40914

line 359why, one step back
359

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 360–361why, one step back
360<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){
361 res.send(req.params);

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 362–410why, one step back
362});
363</code></pre>364365<p>Curl requests against the previously defined route:</p>366367<pre><code> $ curl http://dev:3000/user368 [null,null]369 $ curl http://dev:3000/users370 [null,null]371 $ curl http://dev:3000/users/1372 ["1",null]373 $ curl http://dev:3000/users/1..15374 ["1","15"]375</code></pre>376377<p>Below are some route examples, and the associated paths that they378may consume:</p>379380<pre><code> "/user/:id"381 /user/12382383 "/users/:id?"384 /users/5385 /users386387 "/files/*"388 /files/jquery.js389 /files/javascripts/jquery.js390391 "/file/*.*"392 /files/jquery.js393 /files/javascripts/jquery.js394395 "/user/:id/:operation?"396 /user/1397 /user/1/edit398399 "/products.:format"400 /products.json401 /products.xml402403 "/products.:format?"404 /products.json405 /products.xml406 /products407</code></pre>408409<h3 id="Passing-Route-Control">Passing Route Control</h3>410

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 411–412why, one step back
411<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,
412the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,

Regenerated docsTj Holowaychukbefore adoption334a18a

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

No more http git submodulesTj Holowaychukbefore adoption6e40914

line 414why, one step back
414

Updated docsTj Holowaychukbefore adoptionb819366

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

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 416–417why, one step back
416 var id = req.params.id;
417 if (id) {

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 418–423why, one step back
418 // do something
419 } else {420 next();421 }422});423

Updated docsTj Holowaychukbefore adoptiond691ecb

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

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 425–427why, one step back
425 // do something else
426});427</code></pre>

Regenerated docsTj Holowaychukbefore adoption334a18a

line 428why, one step back
428

Regenerated docsTj Holowaychukbefore adoption090debe

lines 429–457why, one step back
429<h3 id="Middleware">Middleware</h3>
430431<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be432passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>433434<pre><code> var express = require('express');435436var app = express.createServer(437 express.logger(),438 express.bodyDecoder()439 );440</code></pre>441442<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>443444<pre><code>app.use(express.logger({ format: ':method :uri' }));445</code></pre>446447<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>448449<pre><code>var connect = require('connect');450app.use(connect.logger());451</code></pre>452453<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>454455<pre><code>app.use(express.logger());456</code></pre>457

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 458–461why, one step back
458<h3 id="Route-Middleware">Route Middleware</h3>
459460<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>461

Regenerated docsTj Holowaychukbefore adoption0faac20

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

Regenerated docsTj Holowaychukbefore adoption334a18a

line 463why, one step back
463

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 464–469why, one step back
464<pre><code>app.get('/user/:id', function(req, res, next){
465 loadUser(req.params.id, function(err, user){466 if (err) return next(err);467 res.send('Viewing user ' + user.name);468 });469});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 470–473why, one step back
470</code></pre>
471472<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>473

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 474–483why, one step back
474<pre><code>function loadUser(req, res, next) {
475 // You would fetch your user from the db476 var user = users[req.params.id];477 if (user) {478 req.user = user;479 next();480 } else {481 next(new Error('Failed to load user ' + req.params.id));482 }483}

Regenerated docsTj Holowaychukbefore adoption334a18a

line 484why, one step back
484

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 485–487why, one step back
485app.get('/user/:id', loadUser, function(req, res){
486 res.send('Viewing user ' + req.user.name);487});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 488–491why, one step back
488</code></pre>
489490<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>491

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 492–496why, one step back
492<pre><code>function andRestrictToSelf(req, res, next) {
493 req.authenticatedUser.id == req.user.id494 ? next()495 : next(new Error('Unauthorized'));496}

Regenerated docsTj Holowaychukbefore adoption334a18a

line 497why, one step back
497

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 498–500why, one step back
498app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){
499 res.send('Editing user ' + req.user.name);500});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 501–504why, one step back
501</code></pre>
502503<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>504

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 505–511why, one step back
505<pre><code>function andRestrictTo(role) {
506 return function(req, res, next) {507 req.authenticatedUser.role == role508 ? next()509 : next(new Error('Unauthorized'));510 }511}

Regenerated docsTj Holowaychukbefore adoption334a18a

line 512why, one step back
512

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 513–515why, one step back
513app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){
514 res.send('Deleted user ' + req.user.name);515});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 516–519why, one step back
516</code></pre>
517518<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>519

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 520–522why, one step back
520<pre><code>var a = [middleware1, middleware2]
521 , b = [middleware3, middleware4]522 , all = [a, b];

Regenerated docsTj Holowaychukbefore adoption334a18a

line 523why, one step back
523

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 524–525why, one step back
524app.get('/foo', a, function(){});
525app.get('/bar', a, function(){});

Regenerated docsTj Holowaychukbefore adoption334a18a

line 526why, one step back
526

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 527–530why, one step back
527app.get('/', a, middleware3, middleware4, function(){});
528app.get('/', a, b, function(){});529app.get('/', all, function(){});530</code></pre>

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 531–532why, one step back
531
532<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>

No more http git submodulesTj Holowaychukbefore adoption6e40914

line 533why, one step back
533

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 534–580why, one step back
534<h3 id="HTTP-Methods">HTTP Methods</h3>
535536<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>537538<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>539540<p> <form method="post" action="/" /></p>541542<pre><code> &lt;input type="text" name="user[name]" /&gt;543 &lt;input type="text" name="user[email]" /&gt;544 &lt;input type="submit" value="Submit" /&gt;545</code></pre>546547<p> </p>548549<p>By default Express does not know what to do with this request body, so we should add the <em>bodyDecoder</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>550551<pre><code>app.use(express.bodyDecoder());552</code></pre>553554<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>555556<pre><code>app.post('/', function(req, res){557 console.log(req.body.user);558 res.redirect('back');559});560</code></pre>561562<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>bodyDecoder</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>563564<pre><code>app.use(express.bodyDecoder());565app.use(express.methodOverride());566</code></pre>567568<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>569570<pre><code>&lt;form method="post" action="/"&gt;571 &lt;input type="hidden" name="_method" value="put" /&gt;572 &lt;input type="text" name="user[name]" /&gt;573 &lt;input type="text" name="user[email]" /&gt;574 &lt;input type="submit" value="Submit" /&gt; 575&lt;/form&gt;576577app.put('/', function(){578 console.log(req.body.user);579 res.redirect('back');580});

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 581–582why, one step back
581</code></pre>
582

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 583–609why, one step back
583<h3 id="Error-Handling">Error Handling</h3>
584585<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,586or passed to <em>next(err)</em>. Below is an example which serves different pages based on our587ad-hoc <em>NotFound</em> exception:</p>588589<pre><code>function NotFound(msg){590 this.name = 'NotFound';591 Error.call(this, msg);592 Error.captureStackTrace(this, arguments.callee);593}594595sys.inherits(NotFound, Error);596597app.get('/404', function(req, res){598 throw new NotFound;599});600601app.get('/500', function(req, res){602 throw new Error('keyboard cat!');603});604</code></pre>605606<p>We can call <em>app.error()</em> several times as shown below.607Here we check for an instanceof <em>NotFound</em> and show the608404 page, or we pass on to the next error handler.</p>609

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 610–614why, one step back
610<p>Note that these handlers can be defined anywhere, as they
611will be placed below the route handlers on <em>listen()</em>. This612allows for definition within <em>configure()</em> blocks so we can613handle exceptions in different ways based on the environment.</p>614

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 615–639why, one step back
615<pre><code>app.error(function(err, req, res, next){
616 if (err instanceof NotFound) {617 res.render('404.jade');618 } else {619 next(err);620 }621});622</code></pre>623624<p>Here we assume all errors as 500 for the simplicity of625this demo, however you can choose whatever you like</p>626627<pre><code>app.error(function(err, req, res){628 res.render('500.jade', {629 locals: {630 error: err631 } 632 });633});634</code></pre>635636<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware637to report on exceptions. For example if we wish to output exceptions638in "development" mode to <em>stderr</em> we can use:</p>639

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 641–645why, one step back
641</code></pre>
642643<p>Also during development we may want fancy html pages to show exceptions644that are passed or thrown, so we can set <em>showStack</em> to true:</p>645

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 647–655why, one step back
647</code></pre>
648649<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>650is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>651652<h3 id="View-Rendering">View Rendering</h3>653654<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name655of the module that will be required. For example the view <em>layout.ejs</em> will

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 656–657why, one step back
656tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.render(str, options)</em> to comply with Express, however
657<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.</p>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 658–691why, one step back
658
659<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,660and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as661the <em>body</em> local variable in <em>layout.haml</em>.</p>662663<pre><code>app.get('/', function(req, res){664 res.render('index.haml', {665 locals: { title: 'My Site' }666 });667});668</code></pre>669670<p>The new <em>view engine</em> setting allows us to specify our default template engine,671so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>672673<pre><code>app.set('view engine', 'jade');674</code></pre>675676<p>Allowing us to render with:</p>677678<pre><code>res.render('index');679</code></pre>680681<p>vs:</p>682683<pre><code>res.render('index.jade');684</code></pre>685686<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still687mix and match template engines:</p>688689<pre><code>res.render('another-page.ejs');690</code></pre>691

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 692–703why, one step back
692<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>
693694<pre><code>app.set('view options', {695 layout: false696});697</code></pre>698699<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>700701<pre><code>res.render('myview.ejs', { layout: true });702</code></pre>703

Rebuilt docsTj Holowaychukbefore adoption2724ce3

lines 704–718why, one step back
704<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>
705706<pre><code>res.render('page', { layout: 'mylayout' });707</code></pre>708709<p>Otherwise we must specify the extension:</p>710711<pre><code>res.render('page', { layout: 'mylayout.jade' });712</code></pre>713714<p>These paths may also be absolute:</p>715716<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });717</code></pre>718

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 719–726why, one step back
719<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>
720721<pre><code>app.set('view options', {722 open: '{{',723 close: '}}'724});725</code></pre>726

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 727–753why, one step back
727<h3 id="View-Partials">View Partials</h3>
728729<p>The Express view system has built-in support for partials and collections, which are730sort of "mini" views representing a document fragment. For example rather than iterating731in a view to display comments, we would use a partial with collection support:</p>732733<pre><code>partial('comment.haml', { collection: comments });734</code></pre>735736<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,737however if we wished we could use an ejs partial, within a haml view for example.</p>738739<pre><code>partial('comment', { collection: comments });740</code></pre>741742<p>And once again even further, when rendering a collection we can simply pass743an array, if no other options are desired:</p>744745<pre><code>partial('comments', comments);746</code></pre>747748<p>When using the partial collection support a few "magic" variables are provided749for free:</p>750751<ul>752<li><em>firstInCollection</em> True if this is the first object</li>753<li><em>indexInCollection</em> Index of the object in the collection</li>

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

line 754why, one step back
754<li><em>lastInCollection</em> True if this is the last object</li>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 755–762why, one step back
755</ul>
756757758<h3 id="Template-Engines">Template Engines</h3>759760<p>Below are a few template engines commonly used with Express:</p>761762<ul>

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

lines 763–764why, one step back
763<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>
764<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 765–767why, one step back
765<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>
766</ul>767

Rebuilt docsTj Holowaychukbefore adoption2724ce3

lines 768–782why, one step back
768
769<h3 id="Session-Support">Session Support</h3>770771<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieDecoder</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>772773<pre><code>app.use(express.cookieDecoder());774app.use(express.session());775</code></pre>776777<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>778779<pre><code>var RedisStore = require('connect-redis');780app.use(express.cookieDecoder());781app.use(express.session({ store: new RedisStore }));782</code></pre>

No more http git submodulesTj Holowaychukbefore adoption6e40914

line 783why, one step back
783

Regenerated guideTj Holowaychukbefore adoptionf179979

lines 784–811why, one step back
784<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>
785786<pre><code>var RedisStore = require('connect-redis');787app.use(express.cookieDecoder());788app.use(express.session({ store: new RedisStore }));789app.use(express.bodyDecoder());790791app.post('/add-to-cart', function(req, res){792 // Perhaps we posted several items with a form793 // (use the bodyDecoder() middleware for this)794 var items = req.body.items;795 req.session.items = items;796 res.redirect('back');797});798799app.get('/add-to-cart', function(req, res){800 // When redirected back to GET /add-to-cart801 // we could check req.session.items &amp;&amp; req.session.items.length802 // to print out a message803 if (req.session.items &amp;&amp; req.session.items.length) {804 req.flash('info', 'You have %s items in your cart', req.session.items.length);805 }806 res.render('shopping-cart');807});808</code></pre>809810<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/session.html">Connect Session</a> documentation.</p>811

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 812–850why, one step back
812<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>
813814<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>815816<pre><code>req.header('Host');817req.header('host');818req.header('Accept', '*/*');819</code></pre>820821<h3 id="req-accepts-type-">req.accepts(type)</h3>822823<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>824825<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise826the given <em>type</em> is matched by an exact match, and then subtypes. You827may pass the subtype such as "html" which is then converted internally828to "text/html" using the mime lookup table.</p>829830<pre><code>// Accept: text/html831req.accepts('html');832// =&gt; true833834// Accept: text/*; application/json835req.accepts('html');836req.accepts('text/html');837req.accepts('text/plain');838req.accepts('application/json');839// =&gt; true840841req.accepts('image/png');842req.accepts('png');843// =&gt; false844</code></pre>845846<h3 id="req-param-name-">req.param(name)</h3>847848<p>Return the value of param <em>name</em> when present.</p>849850<ul>

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 851–853why, one step back
851<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>
852<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>853<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>

No more http git submodulesTj Holowaychukbefore adoption6e40914

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 859why, one step back
859the <em>express.bodyDecoder</em> middleware.</p>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 860–879why, one step back
860
861<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>862863<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>864865<pre><code>req.flash('info', 'email sent');866req.flash('error', 'email delivery failed');867req.flash('info', 'email re-sent');868// =&gt; 2869870req.flash('info');871// =&gt; ['email sent', 'email re-sent']872873req.flash('info');874// =&gt; []875876req.flash();877// =&gt; { error: ['email delivery failed'], info: [] }878</code></pre>879

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 880–884why, one step back
880<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>
881882<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);883</code></pre>884

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 885–930why, one step back
885<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>
886887<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header888to see if it was issued by an <em>XMLHttpRequest</em>:</p>889890<pre><code>req.xhr891req.isXMLHttpRequest892</code></pre>893894<h3 id="res-header-key-val-">res.header(key[, val])</h3>895896<p>Get or set the response header <em>key</em>.</p>897898<pre><code>res.header('Content-Length');899// =&gt; undefined900901res.header('Content-Length', 123);902// =&gt; 123903904res.header('Content-Length');905// =&gt; 123906</code></pre>907908<h3 id="res-contentType-type-">res.contentType(type)</h3>909910<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>911912<pre><code> var filename = 'path/to/image.png';913 res.contentType(filename);914 // res.headers['Content-Type'] is now "image/png"915</code></pre>916917<h3 id="res-attachment-filename-">res.attachment([filename])</h3>918919<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>920921<pre><code> res.attachment('path/to/my/image.png');922</code></pre>923924<h3 id="res-sendfile-path-">res.sendfile(path)</h3>925926<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>927928<pre><code>res.sendfile('path/to/my.file');929</code></pre>930

Updated docsTj Holowaychukbefore adoptionf0eab06

lines 931–942why, one step back
931<p>This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has <strong>not</strong> been streamed, <em>next(err)</em> will be called on an exception.</p>
932933<pre><code>res.sendfile(path, function(err, path){934 if (err) {935 // handle the error936 } else {937 console.log('transferred %s', path);938 }939});940</code></pre>941942<p>When the filesize exceeds the <em>stream threshold</em> (defaulting to 32k), the file will be streamed using <em>fs.ReadStream</em> and <em>sys.pump()</em>.</p>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 943–963why, one step back
943
944<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>945946<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>947948<pre><code>res.download('path/to/image.png');949res.download('path/to/image.png', 'foo.png');950</code></pre>951952<p>This is equivalent to:</p>953954<pre><code>res.attachment(file);955res.sendfile(file);956</code></pre>957958<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>959960<p>The <code>res.send()</code> method is a high level response utility allowing you to pass961objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status962code based responses. The following are all valid uses:</p>963

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 964–965why, one step back
964<pre><code> res.send(); // 204
965 res.send(new Buffer('wahoo'));

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 966–991why, one step back
966 res.send({ some: 'json' });
967 res.send('&lt;p&gt;some html&lt;/p&gt;');968 res.send('Sorry, cant find that', 404);969 res.send('text', { 'Content-Type': 'text/plain' }, 201);970 res.send(404);971</code></pre>972973<p>By default the <em>Content-Type</em> response header is set, however if explicitly974assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>975it will not be set again.</p>976977<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>978979<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>980981<pre><code>res.redirect('/', 301);982res.redirect('/account');983res.redirect('http://google.com');984res.redirect('home');985res.redirect('back');986</code></pre>987988<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.989The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes990the "home" setting and defaults to "/".</p>991

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 992–1015why, one step back
992<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>
993994<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>995996<pre><code>// "Remember me" for 15 minutes 997res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });998</code></pre>9991000<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>10011002<pre><code>app.use(express.cookieDecoder());10031004app.get('/', function(req, res){1005 // use req.cookies.rememberme1006});1007</code></pre>10081009<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>10101011<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>10121013<pre><code>res.clearCookie('rememberme');1014</code></pre>1015

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 1016–1025why, one step back
1016<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>
10171018<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1019When a callback function is given a response will <em>not</em> be made1020automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>10211022<p> Most engines accept one or more of the following options,1023 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>10241025<ul>

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

line 1026why, one step back
1026<li><em>scope</em> Template evaluation context (value of <em>this</em>)</li>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 1027–1028why, one step back
1027<li><em>locals</em> Object containing local variables</li>
1028<li><em>debug</em> Output debugging information</li>

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1029–1030why, one step back
1029<li><em>status</em> Response status code, defaults to 200</li>
1030<li><em>headers</em> Response headers object</li>

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 1031–1086why, one step back
1031</ul>
103210331034<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>10351036<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1037to the view as a local variable.</p>10381039<ul>1040<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>10411042<ul>1043<li>as: 'something' will add the <em>something</em> local variable</li>1044<li>as: this will use the collection value as the template context</li>1045<li>as: global will merge the collection value's properties with <em>locals</em></li>1046</ul>1047</li>1048<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1049For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1050</ul>105110521053<p>The following are equivalent, and the name of collection value when passed1054to the partial will be <em>movie</em> as derived from the name.</p>10551056<pre><code>partial('movie.jade', { collection: movies });1057partial('movie.jade', movies);1058partial('movie', movies);1059// In view: movie.director1060</code></pre>10611062<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>10631064<pre><code>partial('movie', { collection: movies, as: 'video' });1065// In view: video.director1066</code></pre>10671068<p>Also we can make our movie the value of <em>this</em> within our view so that instead1069of <em>movie.director</em> we could use <em>this.director</em>.</p>10701071<pre><code>partial('movie', { collection: movies, as: this });1072// In view: this.director1073</code></pre>10741075<p>Another alternative is to "explode" the properties of the collection item into1076pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>10771078<pre><code>partials('movie', { collection: movies, as: global });1079// In view: director1080</code></pre>10811082<h3 id="app-set-name-val-">app.set(name[, val])</h3>10831084<p>Apply an application level setting <em>name</em> to <em>val</em>, or1085get the value of <em>name</em> when <em>val</em> is not present:</p>1086

Updated docsTj Holowaychukbefore adoption3234329

lines 1087–1089why, one step back
1087<pre><code>app.set('views', __dirname + '/views');
1088app.set('views');1089// =&gt; ...path...

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 1090–1135why, one step back
1090</code></pre>
10911092<h3 id="app-enable-name-">app.enable(name)</h3>10931094<p>Enable the given setting <em>name</em>:</p>10951096<pre><code>app.enable('some arbitrary setting');1097app.set('some arbitrary setting');1098// =&gt; true1099</code></pre>11001101<h3 id="app-disable-name-">app.disable(name)</h3>11021103<p>Disable the given setting <em>name</em>:</p>11041105<pre><code>app.disable('some setting');1106app.set('some setting');1107// =&gt; false1108</code></pre>11091110<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>11111112<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>11131114<pre><code>app.configure(function(){1115 // executed for each env1116});11171118app.configure('development', function(){1119 // executed for 'development' only1120});1121</code></pre>11221123<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>11241125<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>11261127<pre><code>app.redirect('google', 'http://google.com');1128</code></pre>11291130<p>Now in a route we may call:</p>11311132<p> res.redirect('google');</p>11331134<p>We may also map dynamic redirects:</p>1135

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 1136–1137why, one step back
1136<pre><code>app.redirect('comments', function(req, res){
1137 return '/post/' + req.params.id + '/comments';

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 1138–1180why, one step back
1138});
1139</code></pre>11401141<p>So now we may do the following, and the redirect will dynamically adjust to1142the context of the request. If we called this route with <em>GET /post/12</em> our1143redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>11441145<pre><code>app.get('/post/:id', function(req, res){1146 res.redirect('comments');1147});1148</code></pre>11491150<h3 id="app-error-function-">app.error(function)</h3>11511152<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1153Note that we may set several error handlers by making several calls to this method, however the handler1154should call <em>next(err)</em> if it does not wish to deal with the exception:</p>11551156<pre><code>app.error(function(err, req, res, next){1157 res.send(err.message, 500);1158});1159</code></pre>11601161<h3 id="app-helpers-obj-">app.helpers(obj)</h3>11621163<p>Registers static view helpers.</p>11641165<pre><code>app.helpers({1166 name: function(first, last){ return first + ', ' + last },1167 firstName: 'tj',1168 lastName: 'holowaychuk'1169});1170</code></pre>11711172<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1173as well as the <em>name()</em> function exposed.</p>11741175<pre><code>&lt;%= name(firstName, lastName) %>1176</code></pre>11771178<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>11791180<p>Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

line 1181why, one step back
1181are simply functions which accept <em>req</em>, <em>res</em>, and are

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 1182–1185why, one step back
1182evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function
1183becomes the local variable it is associated with.</p>11841185<pre><code>app.dynamicHelpers({

Updated docsTj Holowaychukbefore adoptiond691ecb

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

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 1187–1194why, one step back
1187 return req.session;
1188 }1189});1190</code></pre>11911192<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>11931194<pre><code>&lt;%= session.name %&gt;

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 1195–1209why, one step back
1195</code></pre>
11961197<h3 id="app-mounted-fn-">app.mounted(fn)</h3>11981199<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>12001201<pre><code>var app = express.createServer(),1202 blog = express.createServer();12031204blog.mounted(function(parent){1205 // parent is app1206 // "this" is blog1207});12081209app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1210–1237why, one step back
1210</code></pre>
12111212<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>12131214<p>Register the given template engine <em>exports</em>1215as <em>ext</em>. For example we may wish to map ".html"1216files to jade:</p>12171218<pre><code> app.register('.html', require('jade'));1219</code></pre>12201221<p>This is also useful for libraries that may not1222match extensions correctly. For example my haml.js1223library is installed from npm as "hamljs" so instead1224of layout.hamljs, we can register the engine as ".haml":</p>12251226<pre><code> app.register('.haml', require('haml-js'));1227</code></pre>12281229<p>For engines that do not comply with the Express1230specification, we can also wrap their api this way.</p>12311232<pre><code> app.register('.foo', {1233 render: function(str, options) {1234 // perhaps their api is1235 // foo.toHTML(str, options);1236 }1237 });

No more http git submodulesTj Holowaychukbefore adoption6e40914

lines 1238–1271why, one step back
1238</code></pre>
12391240<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>12411242<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1243connections will be accepted via <em>INADDR_ANY</em>.</p>12441245<pre><code>app.listen();1246app.listen(3000);1247app.listen(3000, 'n.n.n.n');1248</code></pre>12491250<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>12511252<pre><code>app.listen('/tmp/express.sock');1253</code></pre>12541255<p>Then try it out:</p>12561257<pre><code>$ telnet /tmp/express.sock1258GET / HTTP/1.112591260HTTP/1.1 200 OK1261Content-Type: text/plain1262Content-Length: 1112631264Hello World1265</code></pre>12661267</div>1268 </div>1269 </div>1270 </body>1271</html>