Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,037 lines · 32.1 KiB · HTML

Last changed by

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

History of this file

Take it

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Move menu up after scrolling. Closes #352Tj Holowaychukbefore adoptionce23e5f

lines 4–16why, one step back
4 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
5 <script>6 $(function(){7 var done;8 $(document).scroll(function(event){9 if (!done) {10 $('#toc').animate({11 top: 012 });13 }14 });15 });16 </script>

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 17–139why, one step back
17 <style>
18 #header {19 position: absolute;20 top: 10px;21 left: 0;22 padding: 12px 0;23 text-indent: 40px;24 width: 100%;25 border-top: 1px solid rgba(0,0,0,0.7);26 border-bottom: 1px solid rgba(0,0,0,0.7);27 background: rgba(255,255,255,0.1) url(http://www.sencha.com/favicon.ico) no-repeat 15px 50%;28 text-align: left;29 color: #fff;30 }31 #tagline {32 margin-left: 75px;33 margin-bottom: 30px;34 color: rgba(255,255,255,0.7); }35 html {36 background: #1c1c1c url(images/bg.tile.jpg); }3738 body {39 margin: 0;40 padding-bottom: 30px;41 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";42 font-size: 14px;43 line-height: 1.5;44 -webkit-text-stroke: 1px rgba(0, 0, 0, 0.1);45 -moz-text-stroke: 1px rgba(0, 0, 0, 0.1);46 background: url(images/bg.jpg) 50% 0 no-repeat;47 color: #8b8b8b; }4849 * {50 outline: none; }5152 em {53 color: white; }5455 a img {56 border: none !important; }5758 a {59 font-weight: bold;60 text-decoration: none;61 color: white;62 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;63 -webkit-transition-duration: 0.15s;64 -webkit-transition-timing-function: ease-out; }65 a:hover {66 opacity: 0.8; }6768 h1, h2, h3 {69 margin: 45px 0 0 0;70 color: white;71 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }7273 h3 {74 font-size: 18px; }7576 pre {77 margin: 20px 10px;78 padding: 25px 20px;79 background: rgba(0,0,0,0.5);80 border: 1px solid #323232;81 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);82 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);83 -webkit-border-radius: 5px;84 -moz-border-radius: 5px; }8586 code {87 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }8889 ul {90 margin: 15px 0;91 padding: 0 0 0 35px; }92 ul li {93 margin: 0;94 padding: 2px 0;95 list-style: square; }9697 .sect {98 margin-left: 40px; }99100 #logo {101 display: block;102 margin-left: 30%;103 margin-bottom: 30px;104 width: 194px;105 height: 51px;106 background: url(images/logo.png) 0 0 no-repeat;107 text-indent: -99999px; }108 #logo:hover {109 opacity: 0.7; }110 #logo:active {111 opacity: 0.3; }112113 #ribbon {114 position: fixed;115 top: 0;116 right: 0;117 z-index: 2; }118119 #wrapper {120 width: 100%;121 min-height: 800px;122 background: url(images/top.png) 0 0 repeat-x; }123124 #container {125 margin: 0 auto;126 padding-top: 110px;127 width: 550px; }128129 #toc {130 position: fixed;131 top: 60px;132 left: 0;133 margin: 0 0 0 15px;134 padding: 15px;135 height: 100%;136 background: rgba(0,0,0,0.2);137 border-right: 1px solid rgba(255,255,255,0.05);138 }139 #toc li {

More view docsTj Holowaychukbefore adoption1c8ff48

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 141–189why, one step back
141 list-style: none;
142 }143 #toc li a {144 font-size: 11px;145 }146 #menu {147 margin-left: 65px;148 padding: 0;149 padding-bottom: 30px; }150 #menu li {151 display: inline;152 list-style: none; }153 #menu li a {154 display: block;155 float: left;156 margin: 0 2px;157 padding: 3px 15px;158 background: rgba(0,0,0,0.2);159 -webkit-border-radius: 8px;160 -moz-border-radius: 8px;161 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);162 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);163 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;164 -webkit-transition-duration: 0.15s;165 -webkit-transition-timing-function: ease-out; }166 #menu li a:hover,167 #menu li a.active {168 background: rgba(0,0,0,0.5); }169 #menu li a:active {170 background: rgba(0,0,0,0.1);171 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);172 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }173 </style>174 </head>175 <body>176 <a href='http://github.com/visionmedia/express'> 177 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 178 </a>179 <div id="header"><strong>Sencha</strong> labs</div>180 <div id="wrapper">181 <div id="container"><ul id="toc">182<li><a href="#Installation">Installation</a></li>183<li><a href="#Creating-An-Application">Creating An Application</a></li>184<li><a href="#Configuration">Configuration</a></li>185<li><a href="#Settings">Settings</a></li>186<li><a href="#Routing">Routing</a></li>187<li><a href="#Passing-Route-Control">Passing Route Control</a></li>188<li><a href="#Middleware">Middleware</a></li>189<li><a href="#Error-Handling">Error Handling</a></li>

Added more view docsTj Holowaychukbefore adoption2f96506

lines 190–192why, one step back
190<li><a href="#View-Rendering">View Rendering</a></li>
191<li><a href="#View-Partials">View Partials</a></li>192<li><a href="#Template-Engines">Template Engines</a></li>

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 193–204why, one step back
193<li><a href="#req-header-key-defaultValue-">req.header()</a></li>
194<li><a href="#req-accepts-type-">req.accepts()</a></li>195<li><a href="#req-param-name-">req.param()</a></li>196<li><a href="#req-flash-type-msg-">req.flash()</a></li>197<li><a href="#req-isXMLHttpRequest">req.isXMLHttpRequest</a></li>198<li><a href="#res-header-key-val-">res.header()</a></li>199<li><a href="#res-contentType-type-">res.contentType()</a></li>200<li><a href="#res-attachment-filename-">res.attachment()</a></li>201<li><a href="#res-sendfile-path-">res.sendfile()</a></li>202<li><a href="#res-download-file-filename-">res.download()</a></li>203<li><a href="#res-send-body-status-headers-status-status-">res.send()</a></li>204<li><a href="#res-redirect-url-status-">res.redirect()</a></li>

More view docsTj Holowaychukbefore adoption1c8ff48

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

In depth partial docsTj Holowaychukbefore adoption793943f

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 207–212why, one step back
207<li><a href="#app-set-name-val-">app.set()</a></li>
208<li><a href="#app-enable-name-">app.enable()</a></li>209<li><a href="#app-disable-name-">app.disable()</a></li>210<li><a href="#app-configure-env-function-function-">app.configure()</a></li>211<li><a href="#app-redirect-name-val-">app.redirect()</a></li>212<li><a href="#app-error-function-">app.error()</a></li>

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

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

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

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Server#listen() docsTj Holowaychukbefore adoptionf3803c4

line 217why, one step back
217<li><a href="#app-listen-port-host-">app.listen()</a></li>

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

line 234why, one step back
234

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 236–237why, one step back
236</code></pre>
237

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

line 239why, one step back
239

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

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Updated install docsTj Holowaychukbefore adoption193c4a9

line 243why, one step back
243<p>git clone, first update the submodules:</p>

Error handling docsTj Holowaychukbefore adoption9fbb9fa

line 244why, one step back
244

Updated install docsTj Holowaychukbefore adoption193c4a9

lines 245–247why, one step back
245<pre><code>$ git submodule update --init
246$ make install247$ make install-support

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 248–272why, one step back
248</code></pre>
249250<h3 id="Creating-An-Application">Creating An Application</h3>251252<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however253follows the same idiom by providing <em>express.createServer()</em> as shown below. This means254that you can utilize Express server's transparently with other libraries.</p>255256<pre><code>var app = require('express').createServer();257258app.get('/', function(req, res){259 res.send('hello world');260});261262app.listen(3000);263</code></pre>264265<h3 id="Configuration">Configuration</h3>266267<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers268can use the <em>configure()</em> method to setup needs required by the current environment. When269<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment270prior to the environment specific callback.</p>271272<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 282–284why, one step back
282});
283284app.configure('development', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 286–288why, one step back
286});
287288app.configure('production', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 290–318why, one step back
290});
291</code></pre>292293<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>294295<pre><code>app.configure(function(){296 app.set('views', __dirname + '/views');297 app.set('views');298 // =&gt; "... views directory ..."299300 app.enable('some feature');301 // same as app.set('some feature', true);302303 app.disable('some feature');304 // same as app.set('some feature', false);305});306</code></pre>307308<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,309or more specifically <em>EXPRESS_ENV</em>, for example:</p>310311<pre><code>$ EXPRESS_ENV=production node app.js312</code></pre>313314<h3 id="Settings">Settings</h3>315316<p>Express supports the following settings out of the box:</p>317318<ul>

Updated docsTj Holowaychukbefore adoption4d32762

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

line 334why, one step back
334

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

line 348why, one step back
348

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

lines 351–363why, one step back
351});
352</code></pre>353354<p>Curl requests against the previously defined route:</p>355356<pre><code> $ curl http://dev:3000/user357 [null,null]358 $ curl http://dev:3000/users359 [null,null]360 $ curl http://dev:3000/users/1361 ["1",null]362 $ curl http://dev:3000/users/1..15363 ["1","15"]

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 364–399why, one step back
364</code></pre>
365366<p>Below are some route examples, and the associated paths that they367may consume:</p>368369<pre><code> "/user/:id"370 /user/12371372 "/users/:id?"373 /users/5374 /users375376 "/files/*"377 /files/jquery.js378 /files/javascripts/jquery.js379380 "/file/*.*"381 /files/jquery.js382 /files/javascripts/jquery.js383384 "/user/:id/:operation?"385 /user/1386 /user/1/edit387388 "/products.:format"389 /products.json390 /products.xml391392 "/products.:format?"393 /products.json394 /products.xml395 /products396</code></pre>397398<h3 id="Passing-Route-Control">Passing Route Control</h3>399

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

line 403why, one step back
403

Updated docsTj Holowaychukbefore adoptionb819366

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 407–412why, one step back
407 // do something
408 } else {409 next();410 }411});412

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 424–425why, one step back
424
425var app = express.createServer(

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 426–427why, one step back
426 express.logger(),
427 express.bodyDecoder()

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 434–435why, one step back
434</code></pre>
435

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 447–473why, one step back
447<h3 id="Error-Handling">Error Handling</h3>
448449<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,450or passed to <em>next(err)</em>. Below is an example which serves different pages based on our451ad-hoc <em>NotFound</em> exception:</p>452453<pre><code>function NotFound(msg){454 this.name = 'NotFound';455 Error.call(this, msg);456 Error.captureStackTrace(this, arguments.callee);457}458459sys.inherits(NotFound, Error);460461app.get('/404', function(req, res){462 throw new NotFound;463});464465app.get('/500', function(req, res){466 throw new Error('keyboard cat!');467});468</code></pre>469470<p>We can call <em>app.error()</em> several times as shown below.471Here we check for an instanceof <em>NotFound</em> and show the472404 page, or we pass on to the next error handler.</p>473

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 479–498why, one step back
479<pre><code>app.error(function(err, req, res, next){
480 if (err instanceof NotFound) {481 res.render('404.jade');482 } else {483 next(err);484 }485});486</code></pre>487488<p>Here we assume all errors as 500 for the simplicity of489this demo, however you can choose whatever you like</p>490491<pre><code>app.error(function(err, req, res){492 res.render('500.jade', {493 locals: {494 error: err495 } 496 });497});498</code></pre>

Added more view docsTj Holowaychukbefore adoption2f96506

line 499why, one step back
499

More error handling docsTj Holowaychukbefore adoptioncea401c

lines 500–503why, one step back
500<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware
501to report on exceptions. For example if we wish to output exceptions502in "development" mode to <em>stderr</em> we can use:</p>503

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

More error handling docsTj Holowaychukbefore adoptioncea401c

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

More error handling docsTj Holowaychukbefore adoptioncea401c

lines 511–515why, one step back
511</code></pre>
512513<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>514is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>515

Added more view docsTj Holowaychukbefore adoption2f96506

lines 516–519why, one step back
516<h3 id="View-Rendering">View Rendering</h3>
517518<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name519of the module that will be required. For example the view <em>layout.ejs</em> will

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 520–521why, one step back
520tell 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
521<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 view docsTj Holowaychukbefore adoption2f96506

lines 522–533why, one step back
522
523<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,524and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as525the <em>body</em> local variable in <em>layout.haml</em>.</p>526527<pre><code>app.get('/', function(req, res){528 res.render('index.haml', {529 locals: { title: 'My Site' }530 });531});532</code></pre>533

Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b

lines 534–555why, one step back
534<p>The new <em>view engine</em> setting allows us to specify our default template engine,
535so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>536537<pre><code>app.set('view engine', 'jade');538</code></pre>539540<p>Allowing us to render with:</p>541542<pre><code>res.render('index');543</code></pre>544545<p>vs:</p>546547<pre><code>res.render('index.jade');548</code></pre>549550<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still551mix and match template engines:</p>552553<pre><code>res.render('another-page.ejs');554</code></pre>555

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 556–575why, one step back
556<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>
557558<pre><code>app.set('view options', {559 layout: false560});561</code></pre>562563<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>564565<pre><code>res.render('myview.ejs', { layout: true });566</code></pre>567568<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>569570<pre><code>app.set('view options', {571 open: '{{',572 close: '}}'573});574</code></pre>575

Added more view docsTj Holowaychukbefore adoption2f96506

lines 576–596why, one step back
576<h3 id="View-Partials">View Partials</h3>
577578<p>The Express view system has built-in support for partials and collections, which are579sort of "mini" views representing a document fragment. For example rather than iterating580in a view to display comments, we would use a partial with collection support:</p>581582<pre><code>partial('comment.haml', { collection: comments });583</code></pre>584585<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,586however if we wished we could use an ejs partial, within a haml view for example.</p>587588<pre><code>partial('comment', { collection: comments });589</code></pre>590591<p>And once again even further, when rendering a collection we can simply pass592an array, if no other options are desired:</p>593594<pre><code>partial('comments', comments);595</code></pre>596

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

lines 597–605why, one step back
597<p>When using the partial collection support a few "magic" variables are provided
598for free:</p>599600<ul>601<li><em>firstInCollection</em> True if this is the first object</li>602<li><em>indexInCollection</em> Index of the object in the collection</li>603<li>_lastInCollection _ True if this is the last object</li>604</ul>605

Added view helper docs. Closes #344Tj Holowaychukbefore adoptionc4b5208

line 606why, one step back
606

Added more view docsTj Holowaychukbefore adoption2f96506

lines 607–616why, one step back
607<h3 id="Template-Engines">Template Engines</h3>
608609<p>Below are a few template engines commonly used with Express:</p>610611<ul>612<li><a href="http://github.com/visionmedia/jade">Jade</a> haml.js successor</li>613<li><a href="http://github.com/visionmedia/haml.js">Haml</a> indented templates</li>614<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>615</ul>616

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 617–656why, one step back
617
618<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>619620<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>621622<pre><code>req.header('Host');623req.header('host');624req.header('Accept', '*/*');625</code></pre>626627<h3 id="req-accepts-type-">req.accepts(type)</h3>628629<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>630631<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise632the given <em>type</em> is matched by an exact match, and then subtypes. You633may pass the subtype such as "html" which is then converted internally634to "text/html" using the mime lookup table.</p>635636<pre><code>// Accept: text/html637req.accepts('html');638// =&gt; true639640// Accept: text/*; application/json641req.accepts('html');642req.accepts('text/html');643req.accepts('text/plain');644req.accepts('application/json');645// =&gt; true646647req.accepts('image/png');648req.accepts('png');649// =&gt; false650</code></pre>651652<h3 id="req-param-name-">req.param(name)</h3>653654<p>Return the value of param <em>name</em> when present.</p>655656<ul>

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 666–731why, one step back
666
667<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>668669<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>670671<pre><code>req.flash('info', 'email sent');672req.flash('error', 'email delivery failed');673req.flash('info', 'email re-sent');674// =&gt; 2675676req.flash('info');677// =&gt; ['email sent', 'email re-sent']678679req.flash('info');680// =&gt; []681682req.flash();683// =&gt; { error: ['email delivery failed'], info: [] }684</code></pre>685686<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>687688<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header689to see if it was issued by an <em>XMLHttpRequest</em>:</p>690691<pre><code>req.xhr692req.isXMLHttpRequest693</code></pre>694695<h3 id="res-header-key-val-">res.header(key[, val])</h3>696697<p>Get or set the response header <em>key</em>.</p>698699<pre><code>res.header('Content-Length');700// =&gt; undefined701702res.header('Content-Length', 123);703// =&gt; 123704705res.header('Content-Length');706// =&gt; 123707</code></pre>708709<h3 id="res-contentType-type-">res.contentType(type)</h3>710711<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>712713<pre><code> var filename = 'path/to/image.png';714 res.contentType(filename);715 // res.headers['Content-Type'] is now "image/png"716</code></pre>717718<h3 id="res-attachment-filename-">res.attachment([filename])</h3>719720<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>721722<pre><code> res.attachment('path/to/my/image.png');723</code></pre>724725<h3 id="res-sendfile-path-">res.sendfile(path)</h3>726727<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>728729<pre><code>res.sendfile('path/to/my.file');730</code></pre>731

Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 736–782why, one step back
736
737<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>738739<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>740741<pre><code>res.download('path/to/image.png');742res.download('path/to/image.png', 'foo.png');743</code></pre>744745<p>This is equivalent to:</p>746747<pre><code>res.attachment(file);748res.sendfile(file);749</code></pre>750751<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>752753<p>The <code>res.send()</code> method is a high level response utility allowing you to pass754objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status755code based responses. The following are all valid uses:</p>756757<pre><code> res.send(new Buffer('wahoo'));758 res.send({ some: 'json' });759 res.send('&lt;p&gt;some html&lt;/p&gt;');760 res.send('Sorry, cant find that', 404);761 res.send('text', { 'Content-Type': 'text/plain' }, 201);762 res.send(404);763</code></pre>764765<p>By default the <em>Content-Type</em> response header is set, however if explicitly766assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>767it will not be set again.</p>768769<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>770771<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>772773<pre><code>res.redirect('/', 301);774res.redirect('/account');775res.redirect('http://google.com');776res.redirect('home');777res.redirect('back');778</code></pre>779780<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.781The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes782the "home" setting and defaults to "/".</p>

More view docsTj Holowaychukbefore adoption1c8ff48

lines 783–798why, one step back
783
784<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>785786<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.787When a callback function is given a response will <em>not</em> be made788automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>789790<p> Most engines accept one or more of the following options,791 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>792793<ul>794<li><em>context|scope</em> Template evaluation context (<em>this</em>)</li>795<li><em>locals</em> Object containing local variables</li>796<li><em>debug</em> Output debugging information</li>797</ul>798

In depth partial docsTj Holowaychukbefore adoption793943f

lines 799–846why, one step back
799
800<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>801802<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available803to the view as a local variable.</p>804805<ul>806<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>807808<ul>809<li>as: 'something' will add the <em>something</em> local variable</li>810<li>as: this will use the collection value as the template context</li>811<li>as: global will merge the collection value's properties with <em>locals</em></li>812</ul>813</li>814<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.815For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>816</ul>817818819<p>The following are equivalent, and the name of collection value when passed820to the partial will be <em>movie</em> as derived from the name.</p>821822<pre><code>partial('movie.jade', { collection: movies });823partial('movie.jade', movies);824partial('movie', movies);825// In view: movie.director826</code></pre>827828<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>829830<pre><code>partial('movie', { collection: movies, as: 'video' });831// In view: video.director832</code></pre>833834<p>Also we can make our movie the value of <em>this</em> within our view so that instead835of <em>movie.director</em> we could use <em>this.director</em>.</p>836837<pre><code>partial('movie', { collection: movies, as: this });838// In view: this.director839</code></pre>840841<p>Another alternative is to "explode" the properties of the collection item into842pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>843844<pre><code>partials('movie', { collection: movies, as: global });845// In view: director846</code></pre>

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Updated docsTj Holowaychukbefore adoption3234329

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 856–901why, one step back
856</code></pre>
857858<h3 id="app-enable-name-">app.enable(name)</h3>859860<p>Enable the given setting <em>name</em>:</p>861862<pre><code>app.enable('some arbitrary setting');863app.set('some arbitrary setting');864// =&gt; true865</code></pre>866867<h3 id="app-disable-name-">app.disable(name)</h3>868869<p>Disable the given setting <em>name</em>:</p>870871<pre><code>app.disable('some setting');872app.set('some setting');873// =&gt; false874</code></pre>875876<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>877878<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>879880<pre><code>app.configure(function(){881 // executed for each env882});883884app.configure('development', function(){885 // executed for 'development' only886});887</code></pre>888889<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>890891<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>892893<pre><code>app.redirect('google', 'http://google.com');894</code></pre>895896<p>Now in a route we may call:</p>897898<p> res.redirect('google');</p>899900<p>We may also map dynamic redirects:</p>901

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 904–917why, one step back
904});
905</code></pre>906907<p>So now we may do the following, and the redirect will dynamically adjust to908the context of the request. If we called this route with <em>GET /post/12</em> our909redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>910911<pre><code>app.get('/post/:id', function(req, res){912 res.redirect('comments');913});914</code></pre>915916<h3 id="app-error-function-">app.error(function)</h3>917

More error docsTj Holowaychukbefore adoption6227f5c

lines 918–920why, one step back
918<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.
919Note that we may set several error handlers by making several calls to this method, however the handler920should call <em>next(err)</em> if it does not wish to deal with the exception:</p>

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 921–924why, one step back
921
922<pre><code>app.error(function(err, req, res, next){923 res.send(err.message, 500);924});

Server#listen() docsTj Holowaychukbefore adoptionf3803c4

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 926–928why, one step back
926
927<h3 id="app-helpers-obj-">app.helpers(obj)</h3>928

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

lines 929–946why, one step back
929<p>Registers static view helpers.</p>
930931<pre><code>app.helpers({932 name: function(first, last){ return first + ', ' + last },933 firstName: 'tj',934 lastName: 'holowaychuk'935});936</code></pre>937938<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,939as well as the <em>name()</em> function exposed.</p>940941<pre><code>&lt;%= name(firstName, lastName) %>942</code></pre>943944<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>945946<p>Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

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

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

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

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

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

Updated docsTj Holowaychukbefore adoptiond691ecb

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 953–957why, one step back
953 return req.session;
954 }955});956</code></pre>957

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

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 961–975why, one step back
961</code></pre>
962963<h3 id="app-mounted-fn-">app.mounted(fn)</h3>964965<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>966967<pre><code>var app = express.createServer(),968 blog = express.createServer();969970blog.mounted(function(parent){971 // parent is app972 // "this" is blog973});974975app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 976–1003why, one step back
976</code></pre>
977978<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>979980<p>Register the given template engine <em>exports</em>981as <em>ext</em>. For example we may wish to map ".html"982files to jade:</p>983984<pre><code> app.register('.html', require('jade'));985</code></pre>986987<p>This is also useful for libraries that may not988match extensions correctly. For example my haml.js989library is installed from npm as "hamljs" so instead990of layout.hamljs, we can register the engine as ".haml":</p>991992<pre><code> app.register('.haml', require('haml-js'));993</code></pre>994995<p>For engines that do not comply with the Express996specification, we can also wrap their api this way.</p>997998<pre><code> app.register('.foo', {999 render: function(str, options) {1000 // perhaps their api is1001 // foo.toHTML(str, options);1002 }1003 });

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

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

Server#listen() docsTj Holowaychukbefore adoptionf3803c4

lines 1005–1013why, one step back
1005
1006<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>10071008<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1009connections will be accepted via <em>INADDR_ANY</em>.</p>10101011<pre><code>app.listen();1012app.listen(3000);1013app.listen(3000, 'n.n.n.n');

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 1014–1015why, one step back
1014</code></pre>
1015

Unix domain socket docsTj Holowaychukbefore adoption2fa7907

lines 1016–1032why, one step back
1016<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>
10171018<pre><code>app.listen('/tmp/express.sock');1019</code></pre>10201021<p>Then try it out:</p>10221023<pre><code>$ telnet /tmp/express.sock1024GET / HTTP/1.110251026HTTP/1.1 200 OK1027Content-Type: text/plain1028Content-Length: 1110291030Hello World1031</code></pre>1032

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 1033–1037why, one step back
1033</div>
1034 </div>1035 </div>1036 </body>1037</html>