Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,074 lines · 33.6 KiB · HTML

Last changed by

Removed manpage crap from siteTj Holowaychukbefore adoption0116efd

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

line 75why, one step back
75

Removed manpage crap from siteTj Holowaychukbefore adoption0116efd

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>

Toggling menusTj Holowaychukbefore adoption9719a24

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>

Toggling menusTj Holowaychukbefore adoption9719a24

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'>

Toggling menusTj Holowaychukbefore adoption9719a24

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>

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 339why, one step back
339

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

lines 356–368why, one step back
356});
357</code></pre>358359<p>Curl requests against the previously defined route:</p>360361<pre><code> $ curl http://dev:3000/user362 [null,null]363 $ curl http://dev:3000/users364 [null,null]365 $ curl http://dev:3000/users/1366 ["1",null]367 $ curl http://dev:3000/users/1..15368 ["1","15"]

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 369–404why, one step back
369</code></pre>
370371<p>Below are some route examples, and the associated paths that they372may consume:</p>373374<pre><code> "/user/:id"375 /user/12376377 "/users/:id?"378 /users/5379 /users380381 "/files/*"382 /files/jquery.js383 /files/javascripts/jquery.js384385 "/file/*.*"386 /files/jquery.js387 /files/javascripts/jquery.js388389 "/user/:id/:operation?"390 /user/1391 /user/1/edit392393 "/products.:format"394 /products.json395 /products.xml396397 "/products.:format?"398 /products.json399 /products.xml400 /products401</code></pre>402403<h3 id="Passing-Route-Control">Passing Route Control</h3>404

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

line 408why, one step back
408

Updated docsTj Holowaychukbefore adoptionb819366

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Toggling menusTj Holowaychukbefore adoption9719a24

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 452–478why, one step back
452<h3 id="Error-Handling">Error Handling</h3>
453454<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,455or passed to <em>next(err)</em>. Below is an example which serves different pages based on our456ad-hoc <em>NotFound</em> exception:</p>457458<pre><code>function NotFound(msg){459 this.name = 'NotFound';460 Error.call(this, msg);461 Error.captureStackTrace(this, arguments.callee);462}463464sys.inherits(NotFound, Error);465466app.get('/404', function(req, res){467 throw new NotFound;468});469470app.get('/500', function(req, res){471 throw new Error('keyboard cat!');472});473</code></pre>474475<p>We can call <em>app.error()</em> several times as shown below.476Here we check for an instanceof <em>NotFound</em> and show the477404 page, or we pass on to the next error handler.</p>478

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 525–526why, one step back
525tell 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
526<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 527–560why, one step back
527
528<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,529and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as530the <em>body</em> local variable in <em>layout.haml</em>.</p>531532<pre><code>app.get('/', function(req, res){533 res.render('index.haml', {534 locals: { title: 'My Site' }535 });536});537</code></pre>538539<p>The new <em>view engine</em> setting allows us to specify our default template engine,540so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>541542<pre><code>app.set('view engine', 'jade');543</code></pre>544545<p>Allowing us to render with:</p>546547<pre><code>res.render('index');548</code></pre>549550<p>vs:</p>551552<pre><code>res.render('index.jade');553</code></pre>554555<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still556mix and match template engines:</p>557558<pre><code>res.render('another-page.ejs');559</code></pre>560

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 561–580why, one step back
561<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>
562563<pre><code>app.set('view options', {564 layout: false565});566</code></pre>567568<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>569570<pre><code>res.render('myview.ejs', { layout: true });571</code></pre>572573<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>574575<pre><code>app.set('view options', {576 open: '{{',577 close: '}}'578});579</code></pre>580

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 581–607why, one step back
581<h3 id="View-Partials">View Partials</h3>
582583<p>The Express view system has built-in support for partials and collections, which are584sort of "mini" views representing a document fragment. For example rather than iterating585in a view to display comments, we would use a partial with collection support:</p>586587<pre><code>partial('comment.haml', { collection: comments });588</code></pre>589590<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,591however if we wished we could use an ejs partial, within a haml view for example.</p>592593<pre><code>partial('comment', { collection: comments });594</code></pre>595596<p>And once again even further, when rendering a collection we can simply pass597an array, if no other options are desired:</p>598599<pre><code>partial('comments', comments);600</code></pre>601602<p>When using the partial collection support a few "magic" variables are provided603for free:</p>604605<ul>606<li><em>firstInCollection</em> True if this is the first object</li>607<li><em>indexInCollection</em> Index of the object in the collection</li>

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added view helper docs. Closes #344Tj Holowaychukbefore adoptionc4b5208

line 611why, one step back
611

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 619–661why, one step back
619<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>
620</ul>621622623<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>624625<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>626627<pre><code>req.header('Host');628req.header('host');629req.header('Accept', '*/*');630</code></pre>631632<h3 id="req-accepts-type-">req.accepts(type)</h3>633634<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>635636<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise637the given <em>type</em> is matched by an exact match, and then subtypes. You638may pass the subtype such as "html" which is then converted internally639to "text/html" using the mime lookup table.</p>640641<pre><code>// Accept: text/html642req.accepts('html');643// =&gt; true644645// Accept: text/*; application/json646req.accepts('html');647req.accepts('text/html');648req.accepts('text/plain');649req.accepts('application/json');650// =&gt; true651652req.accepts('image/png');653req.accepts('png');654// =&gt; false655</code></pre>656657<h3 id="req-param-name-">req.param(name)</h3>658659<p>Return the value of param <em>name</em> when present.</p>660661<ul>

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 671–690why, one step back
671
672<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>673674<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>675676<pre><code>req.flash('info', 'email sent');677req.flash('error', 'email delivery failed');678req.flash('info', 'email re-sent');679// =&gt; 2680681req.flash('info');682// =&gt; ['email sent', 'email re-sent']683684req.flash('info');685// =&gt; []686687req.flash();688// =&gt; { error: ['email delivery failed'], info: [] }689</code></pre>690

Toggling menusTj Holowaychukbefore adoption9719a24

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 696–766why, one step back
696<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>
697698<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header699to see if it was issued by an <em>XMLHttpRequest</em>:</p>700701<pre><code>req.xhr702req.isXMLHttpRequest703</code></pre>704705<h3 id="res-header-key-val-">res.header(key[, val])</h3>706707<p>Get or set the response header <em>key</em>.</p>708709<pre><code>res.header('Content-Length');710// =&gt; undefined711712res.header('Content-Length', 123);713// =&gt; 123714715res.header('Content-Length');716// =&gt; 123717</code></pre>718719<h3 id="res-contentType-type-">res.contentType(type)</h3>720721<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>722723<pre><code> var filename = 'path/to/image.png';724 res.contentType(filename);725 // res.headers['Content-Type'] is now "image/png"726</code></pre>727728<h3 id="res-attachment-filename-">res.attachment([filename])</h3>729730<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>731732<pre><code> res.attachment('path/to/my/image.png');733</code></pre>734735<h3 id="res-sendfile-path-">res.sendfile(path)</h3>736737<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>738739<pre><code>res.sendfile('path/to/my.file');740</code></pre>741742<p>This is <em>not</em> a substitution for Connect's <em>staticProvider</em> middleware, it does not743support HTTP caching, and does not perform any security checks. This method is utilized744by <em>res.download()</em> to transfer static files, and allows you do to so from outside of745the public directory, so suitable security checks should be applied.</p>746747<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>748749<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>750751<pre><code>res.download('path/to/image.png');752res.download('path/to/image.png', 'foo.png');753</code></pre>754755<p>This is equivalent to:</p>756757<pre><code>res.attachment(file);758res.sendfile(file);759</code></pre>760761<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>762763<p>The <code>res.send()</code> method is a high level response utility allowing you to pass764objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status765code based responses. The following are all valid uses:</p>766

Toggling menusTj Holowaychukbefore adoption9719a24

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Toggling menusTj Holowaychukbefore adoption9719a24

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

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

Toggling menusTj Holowaychukbefore adoption9719a24

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 834–889why, one step back
834</ul>
835836837<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>838839<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available840to the view as a local variable.</p>841842<ul>843<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>844845<ul>846<li>as: 'something' will add the <em>something</em> local variable</li>847<li>as: this will use the collection value as the template context</li>848<li>as: global will merge the collection value's properties with <em>locals</em></li>849</ul>850</li>851<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.852For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>853</ul>854855856<p>The following are equivalent, and the name of collection value when passed857to the partial will be <em>movie</em> as derived from the name.</p>858859<pre><code>partial('movie.jade', { collection: movies });860partial('movie.jade', movies);861partial('movie', movies);862// In view: movie.director863</code></pre>864865<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>866867<pre><code>partial('movie', { collection: movies, as: 'video' });868// In view: video.director869</code></pre>870871<p>Also we can make our movie the value of <em>this</em> within our view so that instead872of <em>movie.director</em> we could use <em>this.director</em>.</p>873874<pre><code>partial('movie', { collection: movies, as: this });875// In view: this.director876</code></pre>877878<p>Another alternative is to "explode" the properties of the collection item into879pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>880881<pre><code>partials('movie', { collection: movies, as: global });882// In view: director883</code></pre>884885<h3 id="app-set-name-val-">app.set(name[, val])</h3>886887<p>Apply an application level setting <em>name</em> to <em>val</em>, or888get the value of <em>name</em> when <em>val</em> is not present:</p>889

Updated docsTj Holowaychukbefore adoption3234329

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 893–938why, one step back
893</code></pre>
894895<h3 id="app-enable-name-">app.enable(name)</h3>896897<p>Enable the given setting <em>name</em>:</p>898899<pre><code>app.enable('some arbitrary setting');900app.set('some arbitrary setting');901// =&gt; true902</code></pre>903904<h3 id="app-disable-name-">app.disable(name)</h3>905906<p>Disable the given setting <em>name</em>:</p>907908<pre><code>app.disable('some setting');909app.set('some setting');910// =&gt; false911</code></pre>912913<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>914915<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>916917<pre><code>app.configure(function(){918 // executed for each env919});920921app.configure('development', function(){922 // executed for 'development' only923});924</code></pre>925926<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>927928<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>929930<pre><code>app.redirect('google', 'http://google.com');931</code></pre>932933<p>Now in a route we may call:</p>934935<p> res.redirect('google');</p>936937<p>We may also map dynamic redirects:</p>938

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 941–962why, one step back
941});
942</code></pre>943944<p>So now we may do the following, and the redirect will dynamically adjust to945the context of the request. If we called this route with <em>GET /post/12</em> our946redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>947948<pre><code>app.get('/post/:id', function(req, res){949 res.redirect('comments');950});951</code></pre>952953<h3 id="app-error-function-">app.error(function)</h3>954955<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.956Note that we may set several error handlers by making several calls to this method, however the handler957should call <em>next(err)</em> if it does not wish to deal with the exception:</p>958959<pre><code>app.error(function(err, req, res, next){960 res.send(err.message, 500);961});962</code></pre>

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

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

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

lines 966–983why, one step back
966<p>Registers static view helpers.</p>
967968<pre><code>app.helpers({969 name: function(first, last){ return first + ', ' + last },970 firstName: 'tj',971 lastName: 'holowaychuk'972});973</code></pre>974975<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,976as well as the <em>name()</em> function exposed.</p>977978<pre><code>&lt;%= name(firstName, lastName) %>979</code></pre>980981<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>982983<p>Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

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

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

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

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

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 998–1012why, one step back
998</code></pre>
9991000<h3 id="app-mounted-fn-">app.mounted(fn)</h3>10011002<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>10031004<pre><code>var app = express.createServer(),1005 blog = express.createServer();10061007blog.mounted(function(parent){1008 // parent is app1009 // "this" is blog1010});10111012app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1013–1040why, one step back
1013</code></pre>
10141015<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>10161017<p>Register the given template engine <em>exports</em>1018as <em>ext</em>. For example we may wish to map ".html"1019files to jade:</p>10201021<pre><code> app.register('.html', require('jade'));1022</code></pre>10231024<p>This is also useful for libraries that may not1025match extensions correctly. For example my haml.js1026library is installed from npm as "hamljs" so instead1027of layout.hamljs, we can register the engine as ".haml":</p>10281029<pre><code> app.register('.haml', require('haml-js'));1030</code></pre>10311032<p>For engines that do not comply with the Express1033specification, we can also wrap their api this way.</p>10341035<pre><code> app.register('.foo', {1036 render: function(str, options) {1037 // perhaps their api is1038 // foo.toHTML(str, options);1039 }1040 });

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

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

Docs for session exampleTj Holowaychukbefore adoptionc53883b

lines 1042–1074why, one step back
1042
1043<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>10441045<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1046connections will be accepted via <em>INADDR_ANY</em>.</p>10471048<pre><code>app.listen();1049app.listen(3000);1050app.listen(3000, 'n.n.n.n');1051</code></pre>10521053<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>10541055<pre><code>app.listen('/tmp/express.sock');1056</code></pre>10571058<p>Then try it out:</p>10591060<pre><code>$ telnet /tmp/express.sock1061GET / HTTP/1.110621063HTTP/1.1 200 OK1064Content-Type: text/plain1065Content-Length: 1110661067Hello World1068</code></pre>10691070</div>1071 </div>1072 </div>1073 </body>1074</html>