Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,072 lines · 33.6 KiB · HTML

Last changed by

Toggling menusTj Holowaychukbefore adoption9719a24

History of this file

Take it

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Toggling menusTj Holowaychukbefore adoption9719a24

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 5–70why, 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;19 -webkit-text-stroke: 1px rgba(0, 0, 0, 0.1);20 -moz-text-stroke: 1px rgba(0, 0, 0, 0.1);21 background: url(images/bg.jpg) 50% 0 no-repeat;22 color: #8b8b8b; }2324 * {25 outline: none; }2627 em {28 color: white; }2930 a img {31 border: none !important; }3233 a {34 font-weight: bold;35 text-decoration: none;36 color: white;37 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;38 -webkit-transition-duration: 0.15s;39 -webkit-transition-timing-function: ease-out; }40 a:hover {41 opacity: 0.8; }4243 h1, h2, h3 {44 margin: 45px 0 0 0;45 color: white;46 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4748 h3 {49 font-size: 18px; }5051 pre {52 margin: 20px 10px;53 padding: 25px 20px;54 background: rgba(0,0,0,0.5);55 border: 1px solid #323232;56 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);57 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);58 -webkit-border-radius: 5px;59 -moz-border-radius: 5px; }6061 code {62 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6364 ul {65 margin: 15px 0;66 padding: 0 0 0 35px; }67 ul li {68 margin: 0;69 padding: 2px 0;70 list-style: square; }

Toggling menusTj Holowaychukbefore adoption9719a24

lines 71–74why, one step back
71 ul li ul {
72 margin: 0;73 padding-left: 12px;74 }

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Regenerated docs againTj Holowaychukbefore adoption8ead901

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 106–109why, one step back
106 width: 550px; }
107108 #toc {109 position: fixed;

Regenerated docs againTj Holowaychukbefore adoption8ead901

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 111–115why, one step back
111 left: 0;
112 margin: 0 0 0 15px;113 padding: 15px;114 height: 100%;115 background: rgba(0,0,0,0.2);

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Toggling menusTj Holowaychukbefore adoption9719a24

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Toggling menusTj Holowaychukbefore adoption9719a24

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 217–229why, one step back
217</ul>
218 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 219 <p id="tagline">220 High performance, high class web development for221 <a href="http://nodejs.org">Node.js</a>222 </p>223 <ul id="menu">224 <li><a href="index.html">Home</a></li>225 <li><a href="guide.html">Guide</a></li>226 <li><a href="contrib.html">Contributing</a></li>227 <li><a href="migrate.html">1.x Migration</a></li>228 </ul>229<div class='mp'>

Toggling menusTj Holowaychukbefore adoption9719a24

lines 230–233why, one step back
230<h2 id="Express">Express</h2>
231<p class="man-name">232 <code>guide</code>233</p>

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 234–235why, one step back
234<h3 id="Installation">Installation</h3>
235

No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9

line 236why, one step back
236<p>curl:</p>

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 237why, one step back
237

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

line 238why, one step back
238<pre><code>$ curl -# http://expressjs.com/install.sh | sh

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 239–240why, one step back
239</code></pre>
240

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

line 241why, one step back
241<p>npm:</p>

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 242why, one step back
242

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

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 244–275why, one step back
244</code></pre>
245246<p>git clone, first update the submodules:</p>247248<pre><code>$ git submodule update --init249$ make install250$ make install-support251</code></pre>252253<h3 id="Creating-An-Application">Creating An Application</h3>254255<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however256follows the same idiom by providing <em>express.createServer()</em> as shown below. This means257that you can utilize Express server's transparently with other libraries.</p>258259<pre><code>var app = require('express').createServer();260261app.get('/', function(req, res){262 res.send('hello world');263});264265app.listen(3000);266</code></pre>267268<h3 id="Configuration">Configuration</h3>269270<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers271can use the <em>configure()</em> method to setup needs required by the current environment. When272<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment273prior to the environment specific callback.</p>274275<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 285–287why, one step back
285});
286287app.configure('development', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 289–291why, one step back
289});
290291app.configure('production', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 293–321why, one step back
293});
294</code></pre>295296<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>297298<pre><code>app.configure(function(){299 app.set('views', __dirname + '/views');300 app.set('views');301 // =&gt; "... views directory ..."302303 app.enable('some feature');304 // same as app.set('some feature', true);305306 app.disable('some feature');307 // same as app.set('some feature', false);308});309</code></pre>310311<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,312or more specifically <em>EXPRESS_ENV</em>, for example:</p>313314<pre><code>$ EXPRESS_ENV=production node app.js315</code></pre>316317<h3 id="Settings">Settings</h3>318319<p>Express supports the following settings out of the box:</p>320321<ul>

Updated docsTj Holowaychukbefore adoption4d32762

line 322why, one step back
322<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 323why, one step back
323<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 337why, one step back
337

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 340–348why, one step back
340});
341</code></pre>342343<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>345346<pre><code>\/user\/([^\/]+)\/?347</code></pre>348

Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b

line 349why, one step back
349<p>Regular expression literals may also be passed for complex uses. Since capture

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 351why, one step back
351

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b

lines 354–366why, one step back
354});
355</code></pre>356357<p>Curl requests against the previously defined route:</p>358359<pre><code> $ curl http://dev:3000/user360 [null,null]361 $ curl http://dev:3000/users362 [null,null]363 $ curl http://dev:3000/users/1364 ["1",null]365 $ curl http://dev:3000/users/1..15366 ["1","15"]

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 367–402why, one step back
367</code></pre>
368369<p>Below are some route examples, and the associated paths that they370may consume:</p>371372<pre><code> "/user/:id"373 /user/12374375 "/users/:id?"376 /users/5377 /users378379 "/files/*"380 /files/jquery.js381 /files/javascripts/jquery.js382383 "/file/*.*"384 /files/jquery.js385 /files/javascripts/jquery.js386387 "/user/:id/:operation?"388 /user/1389 /user/1/edit390391 "/products.:format"392 /products.json393 /products.xml394395 "/products.:format?"396 /products.json397 /products.xml398 /products399</code></pre>400401<h3 id="Passing-Route-Control">Passing Route Control</h3>402

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 406why, one step back
406

Updated docsTj Holowaychukbefore adoptionb819366

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 410–415why, one step back
410 // do something
411 } else {412 next();413 }414});415

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 417–422why, one step back
417 // do something else
418});419</code></pre>420421<h3 id="Middleware">Middleware</h3>422

Toggling menusTj Holowaychukbefore adoption9719a24

line 423why, one step back
423<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 424–425why, one step back
424passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>
425

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 426why, one step back
426<pre><code>var express = require('express');

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 427–428why, one step back
427
428var app = express.createServer(

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 429–430why, one step back
429 express.logger(),
430 express.bodyDecoder()

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 431–435why, one step back
431);
432</code></pre>433434<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>435

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 437–438why, one step back
437</code></pre>
438

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 439–449why, one step back
439<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>
440441<pre><code>var connect = require('connect');442app.use(connect.logger());443</code></pre>444445<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>446447<pre><code>app.use(express.logger());448</code></pre>449

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 450–476why, one step back
450<h3 id="Error-Handling">Error Handling</h3>
451452<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,453or passed to <em>next(err)</em>. Below is an example which serves different pages based on our454ad-hoc <em>NotFound</em> exception:</p>455456<pre><code>function NotFound(msg){457 this.name = 'NotFound';458 Error.call(this, msg);459 Error.captureStackTrace(this, arguments.callee);460}461462sys.inherits(NotFound, Error);463464app.get('/404', function(req, res){465 throw new NotFound;466});467468app.get('/500', function(req, res){469 throw new Error('keyboard cat!');470});471</code></pre>472473<p>We can call <em>app.error()</em> several times as shown below.474Here we check for an instanceof <em>NotFound</em> and show the475404 page, or we pass on to the next error handler.</p>476

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 482–506why, one step back
482<pre><code>app.error(function(err, req, res, next){
483 if (err instanceof NotFound) {484 res.render('404.jade');485 } else {486 next(err);487 }488});489</code></pre>490491<p>Here we assume all errors as 500 for the simplicity of492this demo, however you can choose whatever you like</p>493494<pre><code>app.error(function(err, req, res){495 res.render('500.jade', {496 locals: {497 error: err498 } 499 });500});501</code></pre>502503<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware504to report on exceptions. For example if we wish to output exceptions505in "development" mode to <em>stderr</em> we can use:</p>506

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 523–524why, one step back
523tell 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
524<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>

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 525–558why, one step back
525
526<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,527and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as528the <em>body</em> local variable in <em>layout.haml</em>.</p>529530<pre><code>app.get('/', function(req, res){531 res.render('index.haml', {532 locals: { title: 'My Site' }533 });534});535</code></pre>536537<p>The new <em>view engine</em> setting allows us to specify our default template engine,538so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>539540<pre><code>app.set('view engine', 'jade');541</code></pre>542543<p>Allowing us to render with:</p>544545<pre><code>res.render('index');546</code></pre>547548<p>vs:</p>549550<pre><code>res.render('index.jade');551</code></pre>552553<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still554mix and match template engines:</p>555556<pre><code>res.render('another-page.ejs');557</code></pre>558

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 559–578why, one step back
559<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>
560561<pre><code>app.set('view options', {562 layout: false563});564</code></pre>565566<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>567568<pre><code>res.render('myview.ejs', { layout: true });569</code></pre>570571<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>572573<pre><code>app.set('view options', {574 open: '{{',575 close: '}}'576});577</code></pre>578

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 579–605why, one step back
579<h3 id="View-Partials">View Partials</h3>
580581<p>The Express view system has built-in support for partials and collections, which are582sort of "mini" views representing a document fragment. For example rather than iterating583in a view to display comments, we would use a partial with collection support:</p>584585<pre><code>partial('comment.haml', { collection: comments });586</code></pre>587588<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,589however if we wished we could use an ejs partial, within a haml view for example.</p>590591<pre><code>partial('comment', { collection: comments });592</code></pre>593594<p>And once again even further, when rendering a collection we can simply pass595an array, if no other options are desired:</p>596597<pre><code>partial('comments', comments);598</code></pre>599600<p>When using the partial collection support a few "magic" variables are provided601for free:</p>602603<ul>604<li><em>firstInCollection</em> True if this is the first object</li>605<li><em>indexInCollection</em> Index of the object in the collection</li>

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 607–608why, one step back
607</ul>
608

Added view helper docs. Closes #344Tj Holowaychukbefore adoptionc4b5208

line 609why, one step back
609

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 610–614why, one step back
610<h3 id="Template-Engines">Template Engines</h3>
611612<p>Below are a few template engines commonly used with Express:</p>613614<ul>

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 617–659why, one step back
617<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>
618</ul>619620621<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>622623<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>624625<pre><code>req.header('Host');626req.header('host');627req.header('Accept', '*/*');628</code></pre>629630<h3 id="req-accepts-type-">req.accepts(type)</h3>631632<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>633634<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise635the given <em>type</em> is matched by an exact match, and then subtypes. You636may pass the subtype such as "html" which is then converted internally637to "text/html" using the mime lookup table.</p>638639<pre><code>// Accept: text/html640req.accepts('html');641// =&gt; true642643// Accept: text/*; application/json644req.accepts('html');645req.accepts('text/html');646req.accepts('text/plain');647req.accepts('application/json');648// =&gt; true649650req.accepts('image/png');651req.accepts('png');652// =&gt; false653</code></pre>654655<h3 id="req-param-name-">req.param(name)</h3>656657<p>Return the value of param <em>name</em> when present.</p>658659<ul>

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 669–688why, one step back
669
670<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>671672<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>673674<pre><code>req.flash('info', 'email sent');675req.flash('error', 'email delivery failed');676req.flash('info', 'email re-sent');677// =&gt; 2678679req.flash('info');680// =&gt; ['email sent', 'email re-sent']681682req.flash('info');683// =&gt; []684685req.flash();686// =&gt; { error: ['email delivery failed'], info: [] }687</code></pre>688

Toggling menusTj Holowaychukbefore adoption9719a24

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 694–764why, one step back
694<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>
695696<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header697to see if it was issued by an <em>XMLHttpRequest</em>:</p>698699<pre><code>req.xhr700req.isXMLHttpRequest701</code></pre>702703<h3 id="res-header-key-val-">res.header(key[, val])</h3>704705<p>Get or set the response header <em>key</em>.</p>706707<pre><code>res.header('Content-Length');708// =&gt; undefined709710res.header('Content-Length', 123);711// =&gt; 123712713res.header('Content-Length');714// =&gt; 123715</code></pre>716717<h3 id="res-contentType-type-">res.contentType(type)</h3>718719<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>720721<pre><code> var filename = 'path/to/image.png';722 res.contentType(filename);723 // res.headers['Content-Type'] is now "image/png"724</code></pre>725726<h3 id="res-attachment-filename-">res.attachment([filename])</h3>727728<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>729730<pre><code> res.attachment('path/to/my/image.png');731</code></pre>732733<h3 id="res-sendfile-path-">res.sendfile(path)</h3>734735<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>736737<pre><code>res.sendfile('path/to/my.file');738</code></pre>739740<p>This is <em>not</em> a substitution for Connect's <em>staticProvider</em> middleware, it does not741support HTTP caching, and does not perform any security checks. This method is utilized742by <em>res.download()</em> to transfer static files, and allows you do to so from outside of743the public directory, so suitable security checks should be applied.</p>744745<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>746747<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>748749<pre><code>res.download('path/to/image.png');750res.download('path/to/image.png', 'foo.png');751</code></pre>752753<p>This is equivalent to:</p>754755<pre><code>res.attachment(file);756res.sendfile(file);757</code></pre>758759<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>760761<p>The <code>res.send()</code> method is a high level response utility allowing you to pass762objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status763code based responses. The following are all valid uses:</p>764

Toggling menusTj Holowaychukbefore adoption9719a24

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 767–792why, one step back
767 res.send({ some: 'json' });
768 res.send('&lt;p&gt;some html&lt;/p&gt;');769 res.send('Sorry, cant find that', 404);770 res.send('text', { 'Content-Type': 'text/plain' }, 201);771 res.send(404);772</code></pre>773774<p>By default the <em>Content-Type</em> response header is set, however if explicitly775assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>776it will not be set again.</p>777778<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>779780<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>781782<pre><code>res.redirect('/', 301);783res.redirect('/account');784res.redirect('http://google.com');785res.redirect('home');786res.redirect('back');787</code></pre>788789<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.790The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes791the "home" setting and defaults to "/".</p>792

Toggling menusTj Holowaychukbefore adoption9719a24

lines 793–816why, one step back
793<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>
794795<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>796797<pre><code>// "Remember me" for 15 minutes 798res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });799</code></pre>800801<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>802803<pre><code>app.use(express.cookieDecoder());804805app.get('/', function(req, res){806 // use req.cookies.rememberme807});808</code></pre>809810<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>811812<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>813814<pre><code>res.clearCookie('rememberme');815</code></pre>816

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 817–829why, one step back
817<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>
818819<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.820When a callback function is given a response will <em>not</em> be made821automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>822823<p> Most engines accept one or more of the following options,824 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>825826<ul>827<li><em>context|scope</em> Template evaluation context (<em>this</em>)</li>828<li><em>locals</em> Object containing local variables</li>829<li><em>debug</em> Output debugging information</li>

Toggling menusTj Holowaychukbefore adoption9719a24

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 832–887why, one step back
832</ul>
833834835<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>836837<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available838to the view as a local variable.</p>839840<ul>841<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>842843<ul>844<li>as: 'something' will add the <em>something</em> local variable</li>845<li>as: this will use the collection value as the template context</li>846<li>as: global will merge the collection value's properties with <em>locals</em></li>847</ul>848</li>849<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.850For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>851</ul>852853854<p>The following are equivalent, and the name of collection value when passed855to the partial will be <em>movie</em> as derived from the name.</p>856857<pre><code>partial('movie.jade', { collection: movies });858partial('movie.jade', movies);859partial('movie', movies);860// In view: movie.director861</code></pre>862863<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>864865<pre><code>partial('movie', { collection: movies, as: 'video' });866// In view: video.director867</code></pre>868869<p>Also we can make our movie the value of <em>this</em> within our view so that instead870of <em>movie.director</em> we could use <em>this.director</em>.</p>871872<pre><code>partial('movie', { collection: movies, as: this });873// In view: this.director874</code></pre>875876<p>Another alternative is to "explode" the properties of the collection item into877pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>878879<pre><code>partials('movie', { collection: movies, as: global });880// In view: director881</code></pre>882883<h3 id="app-set-name-val-">app.set(name[, val])</h3>884885<p>Apply an application level setting <em>name</em> to <em>val</em>, or886get the value of <em>name</em> when <em>val</em> is not present:</p>887

Updated docsTj Holowaychukbefore adoption3234329

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 891–936why, one step back
891</code></pre>
892893<h3 id="app-enable-name-">app.enable(name)</h3>894895<p>Enable the given setting <em>name</em>:</p>896897<pre><code>app.enable('some arbitrary setting');898app.set('some arbitrary setting');899// =&gt; true900</code></pre>901902<h3 id="app-disable-name-">app.disable(name)</h3>903904<p>Disable the given setting <em>name</em>:</p>905906<pre><code>app.disable('some setting');907app.set('some setting');908// =&gt; false909</code></pre>910911<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>912913<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>914915<pre><code>app.configure(function(){916 // executed for each env917});918919app.configure('development', function(){920 // executed for 'development' only921});922</code></pre>923924<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>925926<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>927928<pre><code>app.redirect('google', 'http://google.com');929</code></pre>930931<p>Now in a route we may call:</p>932933<p> res.redirect('google');</p>934935<p>We may also map dynamic redirects:</p>936

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 939–960why, one step back
939});
940</code></pre>941942<p>So now we may do the following, and the redirect will dynamically adjust to943the context of the request. If we called this route with <em>GET /post/12</em> our944redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>945946<pre><code>app.get('/post/:id', function(req, res){947 res.redirect('comments');948});949</code></pre>950951<h3 id="app-error-function-">app.error(function)</h3>952953<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.954Note that we may set several error handlers by making several calls to this method, however the handler955should call <em>next(err)</em> if it does not wish to deal with the exception:</p>956957<pre><code>app.error(function(err, req, res, next){958 res.send(err.message, 500);959});960</code></pre>

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 961–963why, one step back
961
962<h3 id="app-helpers-obj-">app.helpers(obj)</h3>963

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

lines 964–981why, one step back
964<p>Registers static view helpers.</p>
965966<pre><code>app.helpers({967 name: function(first, last){ return first + ', ' + last },968 firstName: 'tj',969 lastName: 'holowaychuk'970});971</code></pre>972973<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,974as well as the <em>name()</em> function exposed.</p>975976<pre><code>&lt;%= name(firstName, lastName) %>977</code></pre>978979<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>980981<p>Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

line 983why, one step back
983evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 984–985why, one step back
984becomes the local variable it is associated with.</p>
985

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

line 986why, one step back
986<pre><code>app.dynamicHelpers({

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 988–992why, one step back
988 return req.session;
989 }990});991</code></pre>992

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

lines 993–995why, one step back
993<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>
994995<pre><code>&lt;%= session.name %&gt;

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 996–1010why, one step back
996</code></pre>
997998<h3 id="app-mounted-fn-">app.mounted(fn)</h3>9991000<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>10011002<pre><code>var app = express.createServer(),1003 blog = express.createServer();10041005blog.mounted(function(parent){1006 // parent is app1007 // "this" is blog1008});10091010app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1011–1038why, one step back
1011</code></pre>
10121013<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>10141015<p>Register the given template engine <em>exports</em>1016as <em>ext</em>. For example we may wish to map ".html"1017files to jade:</p>10181019<pre><code> app.register('.html', require('jade'));1020</code></pre>10211022<p>This is also useful for libraries that may not1023match extensions correctly. For example my haml.js1024library is installed from npm as "hamljs" so instead1025of layout.hamljs, we can register the engine as ".haml":</p>10261027<pre><code> app.register('.haml', require('haml-js'));1028</code></pre>10291030<p>For engines that do not comply with the Express1031specification, we can also wrap their api this way.</p>10321033<pre><code> app.register('.foo', {1034 render: function(str, options) {1035 // perhaps their api is1036 // foo.toHTML(str, options);1037 }1038 });

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

line 1039why, one step back
1039</code></pre>

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 1040–1072why, one step back
1040
1041<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>10421043<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1044connections will be accepted via <em>INADDR_ANY</em>.</p>10451046<pre><code>app.listen();1047app.listen(3000);1048app.listen(3000, 'n.n.n.n');1049</code></pre>10501051<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>10521053<pre><code>app.listen('/tmp/express.sock');1054</code></pre>10551056<p>Then try it out:</p>10571058<pre><code>$ telnet /tmp/express.sock1059GET / HTTP/1.110601061HTTP/1.1 200 OK1062Content-Type: text/plain1063Content-Length: 1110641065Hello World1066</code></pre>10671068</div>1069 </div>1070 </div>1071 </body>1072</html>