Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,083 lines · 34.0 KiB · HTML

Last changed by

Updated docsTj Holowaychukbefore adoptionf0eab06

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>

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>

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; }

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 75why, one step back
75

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 78–106why, one step back
78 .sect {
79 margin-left: 40px; }8081 #logo {82 display: block;83 margin-left: 30%;84 margin-bottom: 30px;85 width: 194px;86 height: 51px;87 background: url(images/logo.png) 0 0 no-repeat;88 text-indent: -99999px; }89 #logo:hover {90 opacity: 0.7; }91 #logo:active {92 opacity: 0.3; }9394 #ribbon {95 position: fixed;96 top: 0;97 right: 0;98 z-index: 2; }99100 #wrapper {101 width: 100%;102 min-height: 800px;103 background: url(images/top.png) 0 0 repeat-x; }104105 #container {106 margin: 0 auto;

Regenerated docs againTj Holowaychukbefore adoption8ead901

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Regenerated docs againTj Holowaychukbefore adoption8ead901

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 236–237why, one step back
236<h3 id="Installation">Installation</h3>
237

No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 239why, one step back
239

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 241–242why, one step back
241</code></pre>
242

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 244why, one step back
244

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

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 246–277why, one step back
246</code></pre>
247248<p>git clone, first update the submodules:</p>249250<pre><code>$ git submodule update --init251$ make install252$ make install-support253</code></pre>254255<h3 id="Creating-An-Application">Creating An Application</h3>256257<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however258follows the same idiom by providing <em>express.createServer()</em> as shown below. This means259that you can utilize Express server's transparently with other libraries.</p>260261<pre><code>var app = require('express').createServer();262263app.get('/', function(req, res){264 res.send('hello world');265});266267app.listen(3000);268</code></pre>269270<h3 id="Configuration">Configuration</h3>271272<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers273can use the <em>configure()</em> method to setup needs required by the current environment. When274<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment275prior to the environment specific callback.</p>276277<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 295–323why, one step back
295});
296</code></pre>297298<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>299300<pre><code>app.configure(function(){301 app.set('views', __dirname + '/views');302 app.set('views');303 // =&gt; "... views directory ..."304305 app.enable('some feature');306 // same as app.set('some feature', true);307308 app.disable('some feature');309 // same as app.set('some feature', false);310});311</code></pre>312313<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,314or more specifically <em>EXPRESS_ENV</em>, for example:</p>315316<pre><code>$ EXPRESS_ENV=production node app.js317</code></pre>318319<h3 id="Settings">Settings</h3>320321<p>Express supports the following settings out of the box:</p>322323<ul>

Updated docsTj Holowaychukbefore adoption4d32762

line 324why, one step back
324<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 325why, one step back
325<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 326–327why, one step back
326<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>
327<li><em>view engine</em> Default view engine name for views rendered without extensions</li>

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Updated docsTj Holowaychukbefore adoptionf0eab06

line 330why, one step back
330<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>

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 340why, one step back
340

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 343–351why, one step back
343});
344</code></pre>345346<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example347when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>348349<pre><code>\/user\/([^\/]+)\/?350</code></pre>351

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

line 353why, one step back
353groups 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 354why, one step back
354

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

lines 357–369why, one step back
357});
358</code></pre>359360<p>Curl requests against the previously defined route:</p>361362<pre><code> $ curl http://dev:3000/user363 [null,null]364 $ curl http://dev:3000/users365 [null,null]366 $ curl http://dev:3000/users/1367 ["1",null]368 $ curl http://dev:3000/users/1..15369 ["1","15"]

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 370–405why, one step back
370</code></pre>
371372<p>Below are some route examples, and the associated paths that they373may consume:</p>374375<pre><code> "/user/:id"376 /user/12377378 "/users/:id?"379 /users/5380 /users381382 "/files/*"383 /files/jquery.js384 /files/javascripts/jquery.js385386 "/file/*.*"387 /files/jquery.js388 /files/javascripts/jquery.js389390 "/user/:id/:operation?"391 /user/1392 /user/1/edit393394 "/products.:format"395 /products.json396 /products.xml397398 "/products.:format?"399 /products.json400 /products.xml401 /products402</code></pre>403404<h3 id="Passing-Route-Control">Passing Route Control</h3>405

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 409why, one step back
409

Updated docsTj Holowaychukbefore adoptionb819366

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 413–418why, one step back
413 // do something
414 } else {415 next();416 }417});418

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 420–425why, one step back
420 // do something else
421});422</code></pre>423424<h3 id="Middleware">Middleware</h3>425

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 426why, one step back
426<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 427–428why, one step back
427passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>
428

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 430–431why, one step back
430
431var app = express.createServer(

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 432–433why, one step back
432 express.logger(),
433 express.bodyDecoder()

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 440–441why, one step back
440</code></pre>
441

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 442–452why, one step back
442<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>
443444<pre><code>var connect = require('connect');445app.use(connect.logger());446</code></pre>447448<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>449450<pre><code>app.use(express.logger());451</code></pre>452

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 453–479why, one step back
453<h3 id="Error-Handling">Error Handling</h3>
454455<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,456or passed to <em>next(err)</em>. Below is an example which serves different pages based on our457ad-hoc <em>NotFound</em> exception:</p>458459<pre><code>function NotFound(msg){460 this.name = 'NotFound';461 Error.call(this, msg);462 Error.captureStackTrace(this, arguments.callee);463}464465sys.inherits(NotFound, Error);466467app.get('/404', function(req, res){468 throw new NotFound;469});470471app.get('/500', function(req, res){472 throw new Error('keyboard cat!');473});474</code></pre>475476<p>We can call <em>app.error()</em> several times as shown below.477Here we check for an instanceof <em>NotFound</em> and show the478404 page, or we pass on to the next error handler.</p>479

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 485–509why, one step back
485<pre><code>app.error(function(err, req, res, next){
486 if (err instanceof NotFound) {487 res.render('404.jade');488 } else {489 next(err);490 }491});492</code></pre>493494<p>Here we assume all errors as 500 for the simplicity of495this demo, however you can choose whatever you like</p>496497<pre><code>app.error(function(err, req, res){498 res.render('500.jade', {499 locals: {500 error: err501 } 502 });503});504</code></pre>505506<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware507to report on exceptions. For example if we wish to output exceptions508in "development" mode to <em>stderr</em> we can use:</p>509

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 526–527why, one step back
526tell 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
527<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 528–561why, one step back
528
529<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,530and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as531the <em>body</em> local variable in <em>layout.haml</em>.</p>532533<pre><code>app.get('/', function(req, res){534 res.render('index.haml', {535 locals: { title: 'My Site' }536 });537});538</code></pre>539540<p>The new <em>view engine</em> setting allows us to specify our default template engine,541so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>542543<pre><code>app.set('view engine', 'jade');544</code></pre>545546<p>Allowing us to render with:</p>547548<pre><code>res.render('index');549</code></pre>550551<p>vs:</p>552553<pre><code>res.render('index.jade');554</code></pre>555556<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still557mix and match template engines:</p>558559<pre><code>res.render('another-page.ejs');560</code></pre>561

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 562–581why, one step back
562<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>
563564<pre><code>app.set('view options', {565 layout: false566});567</code></pre>568569<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>570571<pre><code>res.render('myview.ejs', { layout: true });572</code></pre>573574<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>575576<pre><code>app.set('view options', {577 open: '{{',578 close: '}}'579});580</code></pre>581

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 610–611why, one step back
610</ul>
611

Added view helper docs. Closes #344Tj Holowaychukbefore adoptionc4b5208

line 612why, one step back
612

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 613–617why, one step back
613<h3 id="Template-Engines">Template Engines</h3>
614615<p>Below are a few template engines commonly used with Express:</p>616617<ul>

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 620–662why, one step back
620<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>
621</ul>622623624<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>625626<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>627628<pre><code>req.header('Host');629req.header('host');630req.header('Accept', '*/*');631</code></pre>632633<h3 id="req-accepts-type-">req.accepts(type)</h3>634635<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>636637<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise638the given <em>type</em> is matched by an exact match, and then subtypes. You639may pass the subtype such as "html" which is then converted internally640to "text/html" using the mime lookup table.</p>641642<pre><code>// Accept: text/html643req.accepts('html');644// =&gt; true645646// Accept: text/*; application/json647req.accepts('html');648req.accepts('text/html');649req.accepts('text/plain');650req.accepts('application/json');651// =&gt; true652653req.accepts('image/png');654req.accepts('png');655// =&gt; false656</code></pre>657658<h3 id="req-param-name-">req.param(name)</h3>659660<p>Return the value of param <em>name</em> when present.</p>661662<ul>

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 672–691why, one step back
672
673<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>674675<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>676677<pre><code>req.flash('info', 'email sent');678req.flash('error', 'email delivery failed');679req.flash('info', 'email re-sent');680// =&gt; 2681682req.flash('info');683// =&gt; ['email sent', 'email re-sent']684685req.flash('info');686// =&gt; []687688req.flash();689// =&gt; { error: ['email delivery failed'], info: [] }690</code></pre>691

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 697–742why, one step back
697<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>
698699<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header700to see if it was issued by an <em>XMLHttpRequest</em>:</p>701702<pre><code>req.xhr703req.isXMLHttpRequest704</code></pre>705706<h3 id="res-header-key-val-">res.header(key[, val])</h3>707708<p>Get or set the response header <em>key</em>.</p>709710<pre><code>res.header('Content-Length');711// =&gt; undefined712713res.header('Content-Length', 123);714// =&gt; 123715716res.header('Content-Length');717// =&gt; 123718</code></pre>719720<h3 id="res-contentType-type-">res.contentType(type)</h3>721722<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>723724<pre><code> var filename = 'path/to/image.png';725 res.contentType(filename);726 // res.headers['Content-Type'] is now "image/png"727</code></pre>728729<h3 id="res-attachment-filename-">res.attachment([filename])</h3>730731<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>732733<pre><code> res.attachment('path/to/my/image.png');734</code></pre>735736<h3 id="res-sendfile-path-">res.sendfile(path)</h3>737738<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>739740<pre><code>res.sendfile('path/to/my.file');741</code></pre>742

Updated docsTj Holowaychukbefore adoptionf0eab06

lines 743–754why, one step back
743<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>
744745<pre><code>res.sendfile(path, function(err, path){746 if (err) {747 // handle the error748 } else {749 console.log('transferred %s', path);750 }751});752</code></pre>753754<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>

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 755–775why, one step back
755
756<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>757758<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>759760<pre><code>res.download('path/to/image.png');761res.download('path/to/image.png', 'foo.png');762</code></pre>763764<p>This is equivalent to:</p>765766<pre><code>res.attachment(file);767res.sendfile(file);768</code></pre>769770<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>771772<p>The <code>res.send()</code> method is a high level response utility allowing you to pass773objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status774code based responses. The following are all valid uses:</p>775

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 778–803why, one step back
778 res.send({ some: 'json' });
779 res.send('&lt;p&gt;some html&lt;/p&gt;');780 res.send('Sorry, cant find that', 404);781 res.send('text', { 'Content-Type': 'text/plain' }, 201);782 res.send(404);783</code></pre>784785<p>By default the <em>Content-Type</em> response header is set, however if explicitly786assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>787it will not be set again.</p>788789<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>790791<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>792793<pre><code>res.redirect('/', 301);794res.redirect('/account');795res.redirect('http://google.com');796res.redirect('home');797res.redirect('back');798</code></pre>799800<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.801The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes802the "home" setting and defaults to "/".</p>803

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 804–827why, one step back
804<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>
805806<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>807808<pre><code>// "Remember me" for 15 minutes 809res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });810</code></pre>811812<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>813814<pre><code>app.use(express.cookieDecoder());815816app.get('/', function(req, res){817 // use req.cookies.rememberme818});819</code></pre>820821<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>822823<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>824825<pre><code>res.clearCookie('rememberme');826</code></pre>827

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 843–898why, one step back
843</ul>
844845846<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>847848<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available849to the view as a local variable.</p>850851<ul>852<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>853854<ul>855<li>as: 'something' will add the <em>something</em> local variable</li>856<li>as: this will use the collection value as the template context</li>857<li>as: global will merge the collection value's properties with <em>locals</em></li>858</ul>859</li>860<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.861For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>862</ul>863864865<p>The following are equivalent, and the name of collection value when passed866to the partial will be <em>movie</em> as derived from the name.</p>867868<pre><code>partial('movie.jade', { collection: movies });869partial('movie.jade', movies);870partial('movie', movies);871// In view: movie.director872</code></pre>873874<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>875876<pre><code>partial('movie', { collection: movies, as: 'video' });877// In view: video.director878</code></pre>879880<p>Also we can make our movie the value of <em>this</em> within our view so that instead881of <em>movie.director</em> we could use <em>this.director</em>.</p>882883<pre><code>partial('movie', { collection: movies, as: this });884// In view: this.director885</code></pre>886887<p>Another alternative is to "explode" the properties of the collection item into888pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>889890<pre><code>partials('movie', { collection: movies, as: global });891// In view: director892</code></pre>893894<h3 id="app-set-name-val-">app.set(name[, val])</h3>895896<p>Apply an application level setting <em>name</em> to <em>val</em>, or897get the value of <em>name</em> when <em>val</em> is not present:</p>898

Updated docsTj Holowaychukbefore adoption3234329

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 902–947why, one step back
902</code></pre>
903904<h3 id="app-enable-name-">app.enable(name)</h3>905906<p>Enable the given setting <em>name</em>:</p>907908<pre><code>app.enable('some arbitrary setting');909app.set('some arbitrary setting');910// =&gt; true911</code></pre>912913<h3 id="app-disable-name-">app.disable(name)</h3>914915<p>Disable the given setting <em>name</em>:</p>916917<pre><code>app.disable('some setting');918app.set('some setting');919// =&gt; false920</code></pre>921922<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>923924<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>925926<pre><code>app.configure(function(){927 // executed for each env928});929930app.configure('development', function(){931 // executed for 'development' only932});933</code></pre>934935<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>936937<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>938939<pre><code>app.redirect('google', 'http://google.com');940</code></pre>941942<p>Now in a route we may call:</p>943944<p> res.redirect('google');</p>945946<p>We may also map dynamic redirects:</p>947

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 972–974why, one step back
972
973<h3 id="app-helpers-obj-">app.helpers(obj)</h3>974

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

lines 975–992why, one step back
975<p>Registers static view helpers.</p>
976977<pre><code>app.helpers({978 name: function(first, last){ return first + ', ' + last },979 firstName: 'tj',980 lastName: 'holowaychuk'981});982</code></pre>983984<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,985as well as the <em>name()</em> function exposed.</p>986987<pre><code>&lt;%= name(firstName, lastName) %>988</code></pre>989990<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>991992<p>Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

line 994why, one step back
994evaluated 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 995–996why, one step back
995becomes the local variable it is associated with.</p>
996

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 999–1003why, one step back
999 return req.session;
1000 }1001});1002</code></pre>1003

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

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 1007–1021why, one step back
1007</code></pre>
10081009<h3 id="app-mounted-fn-">app.mounted(fn)</h3>10101011<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>10121013<pre><code>var app = express.createServer(),1014 blog = express.createServer();10151016blog.mounted(function(parent){1017 // parent is app1018 // "this" is blog1019});10201021app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1022–1049why, one step back
1022</code></pre>
10231024<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>10251026<p>Register the given template engine <em>exports</em>1027as <em>ext</em>. For example we may wish to map ".html"1028files to jade:</p>10291030<pre><code> app.register('.html', require('jade'));1031</code></pre>10321033<p>This is also useful for libraries that may not1034match extensions correctly. For example my haml.js1035library is installed from npm as "hamljs" so instead1036of layout.hamljs, we can register the engine as ".haml":</p>10371038<pre><code> app.register('.haml', require('haml-js'));1039</code></pre>10401041<p>For engines that do not comply with the Express1042specification, we can also wrap their api this way.</p>10431044<pre><code> app.register('.foo', {1045 render: function(str, options) {1046 // perhaps their api is1047 // foo.toHTML(str, options);1048 }1049 });

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

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 1051–1083why, one step back
1051
1052<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>10531054<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1055connections will be accepted via <em>INADDR_ANY</em>.</p>10561057<pre><code>app.listen();1058app.listen(3000);1059app.listen(3000, 'n.n.n.n');1060</code></pre>10611062<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>10631064<pre><code>app.listen('/tmp/express.sock');1065</code></pre>10661067<p>Then try it out:</p>10681069<pre><code>$ telnet /tmp/express.sock1070GET / HTTP/1.110711072HTTP/1.1 200 OK1073Content-Type: text/plain1074Content-Length: 1110751076Hello World1077</code></pre>10781079</div>1080 </div>1081 </div>1082 </body>1083</html>