Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,011 lines · 31.4 KiB · HTML

Last changed by

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

History of this file

Take it

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 1–99why, one step back
1<html>
2 <head>3 <title>Express - node web framework</title>4 <style>5 #tagline {6 margin-left: 75px;7 margin-bottom: 30px;8 color: rgba(255,255,255,0.7); }9 html {10 background: #1c1c1c url(images/bg.tile.jpg); }1112 body {13 margin: 0;14 padding-bottom: 30px;15 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";16 font-size: 14px;17 line-height: 1.5;18 -webkit-text-stroke: 1px rgba(0, 0, 0, 0.1);19 -moz-text-stroke: 1px rgba(0, 0, 0, 0.1);20 background: url(images/bg.jpg) 50% 0 no-repeat;21 color: #8b8b8b; }2223 * {24 outline: none; }2526 em {27 color: white; }2829 a img {30 border: none !important; }3132 a {33 font-weight: bold;34 text-decoration: none;35 color: white;36 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;37 -webkit-transition-duration: 0.15s;38 -webkit-transition-timing-function: ease-out; }39 a:hover {40 opacity: 0.8; }4142 h1, h2, h3 {43 margin: 45px 0 0 0;44 color: white;45 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4647 h3 {48 font-size: 18px; }4950 pre {51 margin: 20px 10px;52 padding: 25px 20px;53 background: rgba(0,0,0,0.5);54 border: 1px solid #323232;55 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);56 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);57 -webkit-border-radius: 5px;58 -moz-border-radius: 5px; }5960 code {61 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6263 ul {64 margin: 15px 0;65 padding: 0 0 0 35px; }66 ul li {67 margin: 0;68 padding: 2px 0;69 list-style: square; }7071 .sect {72 margin-left: 40px; }7374 #logo {75 display: block;76 margin-left: 30%;77 margin-bottom: 30px;78 width: 194px;79 height: 51px;80 background: url(images/logo.png) 0 0 no-repeat;81 text-indent: -99999px; }82 #logo:hover {83 opacity: 0.7; }84 #logo:active {85 opacity: 0.3; }8687 #ribbon {88 position: fixed;89 top: 0;90 right: 0;91 z-index: 2; }9293 #wrapper {94 width: 100%;95 min-height: 800px;96 background: url(images/top.png) 0 0 repeat-x; }9798 #container {99 margin: 0 auto;

Regenerated docs againTj Holowaychukbefore adoption8ead901

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 101–104why, one step back
101 width: 550px; }
102103 #toc {104 position: fixed;

Regenerated docs againTj Holowaychukbefore adoption8ead901

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 106–110why, one step back
106 left: 0;
107 margin: 0 0 0 15px;108 padding: 15px;109 height: 100%;110 background: rgba(0,0,0,0.2);

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 112–114why, one step back
112 border-right: 1px solid rgba(255,255,255,0.05);
113 }114 #toc li {

More view docsTj Holowaychukbefore adoption1c8ff48

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 116–178why, one step back
116 list-style: none;
117 }118 #toc li a {119 font-size: 11px;120 }121 #menu {122 margin-left: 65px;123 padding: 0;124 padding-bottom: 30px; }125 #menu li {126 display: inline;127 list-style: none; }128 #menu li a {129 display: block;130 float: left;131 margin: 0 2px;132 padding: 3px 15px;133 background: rgba(0,0,0,0.2);134 -webkit-border-radius: 8px;135 -moz-border-radius: 8px;136 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);137 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);138 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;139 -webkit-transition-duration: 0.15s;140 -webkit-transition-timing-function: ease-out; }141 #menu li a:hover,142 #menu li a.active {143 background: rgba(0,0,0,0.5); }144 #menu li a:active {145 background: rgba(0,0,0,0.1);146 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);147 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }148 </style>149 </head>150 <body>151 <a href='http://github.com/visionmedia/express'> 152 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 153 </a>154 <div id="wrapper">155 <div id="container"><ul id="toc">156<li><a href="#Installation">Installation</a></li>157<li><a href="#Creating-An-Application">Creating An Application</a></li>158<li><a href="#Configuration">Configuration</a></li>159<li><a href="#Settings">Settings</a></li>160<li><a href="#Routing">Routing</a></li>161<li><a href="#Passing-Route-Control">Passing Route Control</a></li>162<li><a href="#Middleware">Middleware</a></li>163<li><a href="#Error-Handling">Error Handling</a></li>164<li><a href="#View-Rendering">View Rendering</a></li>165<li><a href="#View-Partials">View Partials</a></li>166<li><a href="#Template-Engines">Template Engines</a></li>167<li><a href="#req-header-key-defaultValue-">req.header()</a></li>168<li><a href="#req-accepts-type-">req.accepts()</a></li>169<li><a href="#req-param-name-">req.param()</a></li>170<li><a href="#req-flash-type-msg-">req.flash()</a></li>171<li><a href="#req-isXMLHttpRequest">req.isXMLHttpRequest</a></li>172<li><a href="#res-header-key-val-">res.header()</a></li>173<li><a href="#res-contentType-type-">res.contentType()</a></li>174<li><a href="#res-attachment-filename-">res.attachment()</a></li>175<li><a href="#res-sendfile-path-">res.sendfile()</a></li>176<li><a href="#res-download-file-filename-">res.download()</a></li>177<li><a href="#res-send-body-status-headers-status-status-">res.send()</a></li>178<li><a href="#res-redirect-url-status-">res.redirect()</a></li>

More view docsTj Holowaychukbefore adoption1c8ff48

line 179why, one step back
179<li><a href="#res-render-view-options-fn-">res.render()</a></li>

In depth partial docsTj Holowaychukbefore adoption793943f

line 180why, one step back
180<li><a href="#res-partial-view-options-">res.partial()</a></li>

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 181–186why, one step back
181<li><a href="#app-set-name-val-">app.set()</a></li>
182<li><a href="#app-enable-name-">app.enable()</a></li>183<li><a href="#app-disable-name-">app.disable()</a></li>184<li><a href="#app-configure-env-function-function-">app.configure()</a></li>185<li><a href="#app-redirect-name-val-">app.redirect()</a></li>186<li><a href="#app-error-function-">app.error()</a></li>

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

line 187why, one step back
187<li><a href="#app-helpers-obj-">app.helpers()</a></li>

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

line 188why, one step back
188<li><a href="#app-dynamicHelpers-obj-">app.dynamicHelpers()</a></li>

Rebuilt docsTj Holowaychukbefore adoptionba88e48

line 189why, one step back
189<li><a href="#app-mounted-fn-">app.mounted()</a></li>

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

line 190why, one step back
190<li><a href="#app-register-ext-exports-">app.register()</a></li>

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 191–206why, one step back
191<li><a href="#app-listen-port-host-">app.listen()</a></li>
192</ul>193 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 194 <p id="tagline">195 High performance, high class web development for196 <a href="http://nodejs.org">Node.js</a>197 </p>198 <ul id="menu">199 <li><a href="index.html">Home</a></li>200 <li><a href="guide.html">Guide</a></li>201 <li><a href="contrib.html">Contributing</a></li>202 <li><a href="migrate.html">1.x Migration</a></li>203 </ul>204<div class='mp'>205<h3 id="Installation">Installation</h3>206

No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

line 208why, one step back
208

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 210–211why, one step back
210</code></pre>
211

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

line 213why, one step back
213

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

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 215–246why, one step back
215</code></pre>
216217<p>git clone, first update the submodules:</p>218219<pre><code>$ git submodule update --init220$ make install221$ make install-support222</code></pre>223224<h3 id="Creating-An-Application">Creating An Application</h3>225226<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however227follows the same idiom by providing <em>express.createServer()</em> as shown below. This means228that you can utilize Express server's transparently with other libraries.</p>229230<pre><code>var app = require('express').createServer();231232app.get('/', function(req, res){233 res.send('hello world');234});235236app.listen(3000);237</code></pre>238239<h3 id="Configuration">Configuration</h3>240241<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers242can use the <em>configure()</em> method to setup needs required by the current environment. When243<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment244prior to the environment specific callback.</p>245246<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 256–258why, one step back
256});
257258app.configure('development', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 260–262why, one step back
260});
261262app.configure('production', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 264–292why, one step back
264});
265</code></pre>266267<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>268269<pre><code>app.configure(function(){270 app.set('views', __dirname + '/views');271 app.set('views');272 // =&gt; "... views directory ..."273274 app.enable('some feature');275 // same as app.set('some feature', true);276277 app.disable('some feature');278 // same as app.set('some feature', false);279});280</code></pre>281282<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,283or more specifically <em>EXPRESS_ENV</em>, for example:</p>284285<pre><code>$ EXPRESS_ENV=production node app.js286</code></pre>287288<h3 id="Settings">Settings</h3>289290<p>Express supports the following settings out of the box:</p>291292<ul>

Updated docsTj Holowaychukbefore adoption4d32762

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

line 308why, one step back
308

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 311–319why, one step back
311});
312</code></pre>313314<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example315when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>316317<pre><code>\/user\/([^\/]+)\/?318</code></pre>319

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

line 322why, one step back
322

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

lines 325–337why, one step back
325});
326</code></pre>327328<p>Curl requests against the previously defined route:</p>329330<pre><code> $ curl http://dev:3000/user331 [null,null]332 $ curl http://dev:3000/users333 [null,null]334 $ curl http://dev:3000/users/1335 ["1",null]336 $ curl http://dev:3000/users/1..15337 ["1","15"]

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 338–373why, one step back
338</code></pre>
339340<p>Below are some route examples, and the associated paths that they341may consume:</p>342343<pre><code> "/user/:id"344 /user/12345346 "/users/:id?"347 /users/5348 /users349350 "/files/*"351 /files/jquery.js352 /files/javascripts/jquery.js353354 "/file/*.*"355 /files/jquery.js356 /files/javascripts/jquery.js357358 "/user/:id/:operation?"359 /user/1360 /user/1/edit361362 "/products.:format"363 /products.json364 /products.xml365366 "/products.:format?"367 /products.json368 /products.xml369 /products370</code></pre>371372<h3 id="Passing-Route-Control">Passing Route Control</h3>373

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

line 377why, one step back
377

Updated docsTj Holowaychukbefore adoptionb819366

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 381–386why, one step back
381 // do something
382 } else {383 next();384 }385});386

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 388–396why, one step back
388 // do something else
389});390</code></pre>391392<h3 id="Middleware">Middleware</h3>393394<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/extjs/Connect">Connect</a> can be395passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>396

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 398–399why, one step back
398
399var app = express.createServer(

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 400–401why, one step back
400 express.logger(),
401 express.bodyDecoder()

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 408–409why, one step back
408</code></pre>
409

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 410–420why, one step back
410<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>
411412<pre><code>var connect = require('connect');413app.use(connect.logger());414</code></pre>415416<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>417418<pre><code>app.use(express.logger());419</code></pre>420

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 421–447why, one step back
421<h3 id="Error-Handling">Error Handling</h3>
422423<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,424or passed to <em>next(err)</em>. Below is an example which serves different pages based on our425ad-hoc <em>NotFound</em> exception:</p>426427<pre><code>function NotFound(msg){428 this.name = 'NotFound';429 Error.call(this, msg);430 Error.captureStackTrace(this, arguments.callee);431}432433sys.inherits(NotFound, Error);434435app.get('/404', function(req, res){436 throw new NotFound;437});438439app.get('/500', function(req, res){440 throw new Error('keyboard cat!');441});442</code></pre>443444<p>We can call <em>app.error()</em> several times as shown below.445Here we check for an instanceof <em>NotFound</em> and show the446404 page, or we pass on to the next error handler.</p>447

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 453–477why, one step back
453<pre><code>app.error(function(err, req, res, next){
454 if (err instanceof NotFound) {455 res.render('404.jade');456 } else {457 next(err);458 }459});460</code></pre>461462<p>Here we assume all errors as 500 for the simplicity of463this demo, however you can choose whatever you like</p>464465<pre><code>app.error(function(err, req, res){466 res.render('500.jade', {467 locals: {468 error: err469 } 470 });471});472</code></pre>473474<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware475to report on exceptions. For example if we wish to output exceptions476in "development" mode to <em>stderr</em> we can use:</p>477

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 496–507why, one step back
496
497<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,498and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as499the <em>body</em> local variable in <em>layout.haml</em>.</p>500501<pre><code>app.get('/', function(req, res){502 res.render('index.haml', {503 locals: { title: 'My Site' }504 });505});506</code></pre>507

Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b

lines 508–529why, one step back
508<p>The new <em>view engine</em> setting allows us to specify our default template engine,
509so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>510511<pre><code>app.set('view engine', 'jade');512</code></pre>513514<p>Allowing us to render with:</p>515516<pre><code>res.render('index');517</code></pre>518519<p>vs:</p>520521<pre><code>res.render('index.jade');522</code></pre>523524<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still525mix and match template engines:</p>526527<pre><code>res.render('another-page.ejs');528</code></pre>529

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 530–549why, one step back
530<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>
531532<pre><code>app.set('view options', {533 layout: false534});535</code></pre>536537<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>538539<pre><code>res.render('myview.ejs', { layout: true });540</code></pre>541542<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>543544<pre><code>app.set('view options', {545 open: '{{',546 close: '}}'547});548</code></pre>549

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 550–570why, one step back
550<h3 id="View-Partials">View Partials</h3>
551552<p>The Express view system has built-in support for partials and collections, which are553sort of "mini" views representing a document fragment. For example rather than iterating554in a view to display comments, we would use a partial with collection support:</p>555556<pre><code>partial('comment.haml', { collection: comments });557</code></pre>558559<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,560however if we wished we could use an ejs partial, within a haml view for example.</p>561562<pre><code>partial('comment', { collection: comments });563</code></pre>564565<p>And once again even further, when rendering a collection we can simply pass566an array, if no other options are desired:</p>567568<pre><code>partial('comments', comments);569</code></pre>570

Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701

lines 571–576why, one step back
571<p>When using the partial collection support a few "magic" variables are provided
572for free:</p>573574<ul>575<li><em>firstInCollection</em> True if this is the first object</li>576<li><em>indexInCollection</em> Index of the object in the collection</li>

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701

lines 578–579why, one step back
578</ul>
579

Added view helper docs. Closes #344Tj Holowaychukbefore adoptionc4b5208

line 580why, one step back
580

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 581–585why, one step back
581<h3 id="Template-Engines">Template Engines</h3>
582583<p>Below are a few template engines commonly used with Express:</p>584585<ul>

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 588–630why, one step back
588<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>
589</ul>590591592<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>593594<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>595596<pre><code>req.header('Host');597req.header('host');598req.header('Accept', '*/*');599</code></pre>600601<h3 id="req-accepts-type-">req.accepts(type)</h3>602603<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>604605<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise606the given <em>type</em> is matched by an exact match, and then subtypes. You607may pass the subtype such as "html" which is then converted internally608to "text/html" using the mime lookup table.</p>609610<pre><code>// Accept: text/html611req.accepts('html');612// =&gt; true613614// Accept: text/*; application/json615req.accepts('html');616req.accepts('text/html');617req.accepts('text/plain');618req.accepts('application/json');619// =&gt; true620621req.accepts('image/png');622req.accepts('png');623// =&gt; false624</code></pre>625626<h3 id="req-param-name-">req.param(name)</h3>627628<p>Return the value of param <em>name</em> when present.</p>629630<ul>

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 640–705why, one step back
640
641<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>642643<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>644645<pre><code>req.flash('info', 'email sent');646req.flash('error', 'email delivery failed');647req.flash('info', 'email re-sent');648// =&gt; 2649650req.flash('info');651// =&gt; ['email sent', 'email re-sent']652653req.flash('info');654// =&gt; []655656req.flash();657// =&gt; { error: ['email delivery failed'], info: [] }658</code></pre>659660<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>661662<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header663to see if it was issued by an <em>XMLHttpRequest</em>:</p>664665<pre><code>req.xhr666req.isXMLHttpRequest667</code></pre>668669<h3 id="res-header-key-val-">res.header(key[, val])</h3>670671<p>Get or set the response header <em>key</em>.</p>672673<pre><code>res.header('Content-Length');674// =&gt; undefined675676res.header('Content-Length', 123);677// =&gt; 123678679res.header('Content-Length');680// =&gt; 123681</code></pre>682683<h3 id="res-contentType-type-">res.contentType(type)</h3>684685<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>686687<pre><code> var filename = 'path/to/image.png';688 res.contentType(filename);689 // res.headers['Content-Type'] is now "image/png"690</code></pre>691692<h3 id="res-attachment-filename-">res.attachment([filename])</h3>693694<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>695696<pre><code> res.attachment('path/to/my/image.png');697</code></pre>698699<h3 id="res-sendfile-path-">res.sendfile(path)</h3>700701<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>702703<pre><code>res.sendfile('path/to/my.file');704</code></pre>705

Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1

lines 706–709why, one step back
706<p>This is <em>not</em> a substitution for Connect's <em>staticProvider</em> middleware, it does not
707support HTTP caching, and does not perform any security checks. This method is utilized708by <em>res.download()</em> to transfer static files, and allows you do to so from outside of709the public directory, so suitable security checks should be applied.</p>

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 710–756why, one step back
710
711<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>712713<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>714715<pre><code>res.download('path/to/image.png');716res.download('path/to/image.png', 'foo.png');717</code></pre>718719<p>This is equivalent to:</p>720721<pre><code>res.attachment(file);722res.sendfile(file);723</code></pre>724725<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>726727<p>The <code>res.send()</code> method is a high level response utility allowing you to pass728objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status729code based responses. The following are all valid uses:</p>730731<pre><code> res.send(new Buffer('wahoo'));732 res.send({ some: 'json' });733 res.send('&lt;p&gt;some html&lt;/p&gt;');734 res.send('Sorry, cant find that', 404);735 res.send('text', { 'Content-Type': 'text/plain' }, 201);736 res.send(404);737</code></pre>738739<p>By default the <em>Content-Type</em> response header is set, however if explicitly740assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>741it will not be set again.</p>742743<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>744745<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>746747<pre><code>res.redirect('/', 301);748res.redirect('/account');749res.redirect('http://google.com');750res.redirect('home');751res.redirect('back');752</code></pre>753754<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.755The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes756the "home" setting and defaults to "/".</p>

More view docsTj Holowaychukbefore adoption1c8ff48

lines 757–772why, one step back
757
758<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>759760<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.761When a callback function is given a response will <em>not</em> be made762automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>763764<p> Most engines accept one or more of the following options,765 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>766767<ul>768<li><em>context|scope</em> Template evaluation context (<em>this</em>)</li>769<li><em>locals</em> Object containing local variables</li>770<li><em>debug</em> Output debugging information</li>771</ul>772

In depth partial docsTj Holowaychukbefore adoption793943f

lines 773–820why, one step back
773
774<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>775776<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available777to the view as a local variable.</p>778779<ul>780<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>781782<ul>783<li>as: 'something' will add the <em>something</em> local variable</li>784<li>as: this will use the collection value as the template context</li>785<li>as: global will merge the collection value's properties with <em>locals</em></li>786</ul>787</li>788<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.789For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>790</ul>791792793<p>The following are equivalent, and the name of collection value when passed794to the partial will be <em>movie</em> as derived from the name.</p>795796<pre><code>partial('movie.jade', { collection: movies });797partial('movie.jade', movies);798partial('movie', movies);799// In view: movie.director800</code></pre>801802<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>803804<pre><code>partial('movie', { collection: movies, as: 'video' });805// In view: video.director806</code></pre>807808<p>Also we can make our movie the value of <em>this</em> within our view so that instead809of <em>movie.director</em> we could use <em>this.director</em>.</p>810811<pre><code>partial('movie', { collection: movies, as: this });812// In view: this.director813</code></pre>814815<p>Another alternative is to "explode" the properties of the collection item into816pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>817818<pre><code>partials('movie', { collection: movies, as: global });819// In view: director820</code></pre>

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 821–826why, one step back
821
822<h3 id="app-set-name-val-">app.set(name[, val])</h3>823824<p>Apply an application level setting <em>name</em> to <em>val</em>, or825get the value of <em>name</em> when <em>val</em> is not present:</p>826

Updated docsTj Holowaychukbefore adoption3234329

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 830–875why, one step back
830</code></pre>
831832<h3 id="app-enable-name-">app.enable(name)</h3>833834<p>Enable the given setting <em>name</em>:</p>835836<pre><code>app.enable('some arbitrary setting');837app.set('some arbitrary setting');838// =&gt; true839</code></pre>840841<h3 id="app-disable-name-">app.disable(name)</h3>842843<p>Disable the given setting <em>name</em>:</p>844845<pre><code>app.disable('some setting');846app.set('some setting');847// =&gt; false848</code></pre>849850<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>851852<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>853854<pre><code>app.configure(function(){855 // executed for each env856});857858app.configure('development', function(){859 // executed for 'development' only860});861</code></pre>862863<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>864865<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>866867<pre><code>app.redirect('google', 'http://google.com');868</code></pre>869870<p>Now in a route we may call:</p>871872<p> res.redirect('google');</p>873874<p>We may also map dynamic redirects:</p>875

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 878–899why, one step back
878});
879</code></pre>880881<p>So now we may do the following, and the redirect will dynamically adjust to882the context of the request. If we called this route with <em>GET /post/12</em> our883redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>884885<pre><code>app.get('/post/:id', function(req, res){886 res.redirect('comments');887});888</code></pre>889890<h3 id="app-error-function-">app.error(function)</h3>891892<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.893Note that we may set several error handlers by making several calls to this method, however the handler894should call <em>next(err)</em> if it does not wish to deal with the exception:</p>895896<pre><code>app.error(function(err, req, res, next){897 res.send(err.message, 500);898});899</code></pre>

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 900–902why, one step back
900
901<h3 id="app-helpers-obj-">app.helpers(obj)</h3>902

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

lines 903–920why, one step back
903<p>Registers static view helpers.</p>
904905<pre><code>app.helpers({906 name: function(first, last){ return first + ', ' + last },907 firstName: 'tj',908 lastName: 'holowaychuk'909});910</code></pre>911912<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,913as well as the <em>name()</em> function exposed.</p>914915<pre><code>&lt;%= name(firstName, lastName) %>916</code></pre>917918<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>919920<p>Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

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

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 927–931why, one step back
927 return req.session;
928 }929});930</code></pre>931

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

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 935–949why, one step back
935</code></pre>
936937<h3 id="app-mounted-fn-">app.mounted(fn)</h3>938939<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>940941<pre><code>var app = express.createServer(),942 blog = express.createServer();943944blog.mounted(function(parent){945 // parent is app946 // "this" is blog947});948949app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 950–977why, one step back
950</code></pre>
951952<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>953954<p>Register the given template engine <em>exports</em>955as <em>ext</em>. For example we may wish to map ".html"956files to jade:</p>957958<pre><code> app.register('.html', require('jade'));959</code></pre>960961<p>This is also useful for libraries that may not962match extensions correctly. For example my haml.js963library is installed from npm as "hamljs" so instead964of layout.hamljs, we can register the engine as ".haml":</p>965966<pre><code> app.register('.haml', require('haml-js'));967</code></pre>968969<p>For engines that do not comply with the Express970specification, we can also wrap their api this way.</p>971972<pre><code> app.register('.foo', {973 render: function(str, options) {974 // perhaps their api is975 // foo.toHTML(str, options);976 }977 });

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

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

Added more req.flash() testsTj Holowaychukbefore adoption5279ade

lines 979–1011why, one step back
979
980<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>981982<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all983connections will be accepted via <em>INADDR_ANY</em>.</p>984985<pre><code>app.listen();986app.listen(3000);987app.listen(3000, 'n.n.n.n');988</code></pre>989990<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>991992<pre><code>app.listen('/tmp/express.sock');993</code></pre>994995<p>Then try it out:</p>996997<pre><code>$ telnet /tmp/express.sock998GET / HTTP/1.19991000HTTP/1.1 200 OK1001Content-Type: text/plain1002Content-Length: 1110031004Hello World1005</code></pre>10061007</div>1008 </div>1009 </div>1010 </body>1011</html>