Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,345 lines · 44.9 KiB · HTML

Last changed by

Merge branch 'is'Tj Holowaychukbefore adoption7a71380

History of this file

Take it

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 5–18why, 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;

antialiased textTj Holowaychukbefore adoption8d80f23

line 19why, one step back
19 -webkit-font-smoothing: antialiased;

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 20–41why, one step back
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; }41

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

line 42why, one step back
42 h1, h2, h3, h4 {

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 43–48why, one step back
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; }

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 49–52why, one step back
49 h4 {
50 margin-left: 10px;51 font-size: 14px;52 }

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 53–73why, one step back
53
54 pre {55 margin: 20px 10px;56 padding: 25px 20px;57 background: rgba(0,0,0,0.5);58 border: 1px solid #323232;59 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);60 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -webkit-border-radius: 5px;62 -moz-border-radius: 5px; }6364 code {65 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6667 ul {68 margin: 15px 0;69 padding: 0 0 0 35px; }70 ul li {71 margin: 0;72 padding: 2px 0;73 list-style: square; }

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 74–77why, one step back
74 ul li ul {
75 margin: 0;76 padding-left: 12px;77 }

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 78why, one step back
78

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 81–82why, one step back
81 .sect {
82 margin-left: 40px; }

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

lines 83–86why, one step back
83 img {
84 margin-left: 20px;85 margin-bottom: 15px;86 }

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 87–113why, one step back
87
88 #logo {89 display: block;90 margin-left: 30%;91 margin-bottom: 30px;92 width: 194px;93 height: 51px;94 background: url(images/logo.png) 0 0 no-repeat;95 text-indent: -99999px; }96 #logo:hover {97 opacity: 0.7; }98 #logo:active {99 opacity: 0.3; }100101 #ribbon {102 position: fixed;103 top: 0;104 right: 0;105 z-index: 2; }106107 #wrapper {108 width: 100%;109 min-height: 800px;110 background: url(images/top.png) 0 0 repeat-x; }111112 #container {113 margin: 0 auto;

Regenerated docs againTj Holowaychukbefore adoption8ead901

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 115–118why, one step back
115 width: 550px; }
116117 #toc {118 position: fixed;

Regenerated docs againTj Holowaychukbefore adoption8ead901

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 120–124why, one step back
120 left: 0;
121 margin: 0 0 0 15px;122 padding: 15px;123 height: 100%;124 background: rgba(0,0,0,0.2);

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 163–174why, one step back
163 <script>
164 $(function(){165 $('.section').hide();166 $('.toggle, a.section-title').toggle(function(){167 $(this).siblings('ul').fadeIn(300);168 return false;169 }, function(){170 $(this).siblings('ul').fadeOut(300);171 return false;172 });173 });174 </script>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 175–187why, one step back
175 </head>
176 <body>177 <a href='http://github.com/visionmedia/express'> 178 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 179 </a>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>

Regenerated docsTj Holowaychukbefore adoption090debe

line 188why, one step back
188<li><a href="#Middleware">Middleware</a></li>

Regenerated docsTj Holowaychukbefore adoption334a18a

line 189why, one step back
189<li><a href="#Route-Middleware">Route Middleware</a></li>

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

line 190why, one step back
190<li><a href="#HTTP-Methods">HTTP Methods</a></li>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

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

Rebuilt docsTj Holowaychukbefore adoption2724ce3

line 195why, one step back
195<li><a href="#Session-Support">Session Support</a></li>

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

line 196why, one step back
196<li><a href="#Migration-Guide">Migration Guide</a></li>

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 197–199why, one step back
197<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">
198<li><a href="#req-header-key-defaultValue-">header()</a></li>199<li><a href="#req-accepts-type-">accepts()</a></li>

Added req.is() docsTj Holowaychukbefore adoption806aefa

line 200why, one step back
200<li><a href="#req-is-type-">is()</a></li>

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 201–230why, one step back
201<li><a href="#req-param-name-">param()</a></li>
202<li><a href="#req-flash-type-msg-">flash()</a></li>203<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>204</ul></li>205<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">206<li><a href="#res-header-key-val-">header()</a></li>207<li><a href="#res-contentType-type-">contentType()</a></li>208<li><a href="#res-attachment-filename-">attachment()</a></li>209<li><a href="#res-sendfile-path-">sendfile()</a></li>210<li><a href="#res-download-file-filename-">download()</a></li>211<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>212<li><a href="#res-redirect-url-status-">redirect()</a></li>213<li><a href="#res-cookie-name-val-options-">cookie()</a></li>214<li><a href="#res-clearCookie-name-">clearCookie()</a></li>215<li><a href="#res-render-view-options-fn-">render()</a></li>216<li><a href="#res-partial-view-options-">partial()</a></li>217</ul></li>218<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">219<li><a href="#app-set-name-val-">set()</a></li>220<li><a href="#app-enable-name-">enable()</a></li>221<li><a href="#app-disable-name-">disable()</a></li>222<li><a href="#app-configure-env-function-function-">configure()</a></li>223<li><a href="#app-redirect-name-val-">redirect()</a></li>224<li><a href="#app-error-function-">error()</a></li>225<li><a href="#app-helpers-obj-">helpers()</a></li>226<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>227<li><a href="#app-mounted-fn-">mounted()</a></li>228<li><a href="#app-register-ext-exports-">register()</a></li>229<li><a href="#app-listen-port-host-">listen()</a></li>230</ul></li>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 231–240why, one step back
231</ul>
232 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 233 <p id="tagline">234 High performance, high class web development for235 <a href="http://nodejs.org">Node.js</a>236 </p>237 <ul id="menu">238 <li><a href="index.html">Home</a></li>239 <li><a href="guide.html">Guide</a></li>240 <li><a href="contrib.html">Contributing</a></li>

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

line 241why, one step back
241 <li><a href="applications.html">Applications</a></li>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 242–243why, one step back
242 </ul>
243<div class='mp'>

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 244–247why, one step back
244<h2 id="Express">Express</h2>
245<p class="man-name">246 <code>guide</code>247</p>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 248–294why, one step back
248<h3 id="Installation">Installation</h3>
249250<p>curl:</p>251252<pre><code>$ curl -# http://expressjs.com/install.sh | sh253</code></pre>254255<p>npm:</p>256257<pre><code>$ npm install express258</code></pre>259260<p>git clone, first update the submodules:</p>261262<pre><code>$ git submodule update --init263$ make install264$ make install-support265</code></pre>266267<h3 id="Creating-An-Application">Creating An Application</h3>268269<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however270follows the same idiom by providing <em>express.createServer()</em> as shown below. This means271that you can utilize Express server's transparently with other libraries.</p>272273<pre><code>var app = require('express').createServer();274275app.get('/', function(req, res){276 res.send('hello world');277});278279app.listen(3000);280</code></pre>281282<h3 id="Configuration">Configuration</h3>283284<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers285can use the <em>configure()</em> method to setup needs required by the current environment. When286<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment287prior to the environment specific callback.</p>288289<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces290in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.291Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,292otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>293294<pre><code>app.configure(function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 299–301why, one step back
299});
300301app.configure('development', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 303–305why, one step back
303});
304305app.configure('production', function(){

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 307–324why, one step back
307});
308</code></pre>309310<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>311312<pre><code>app.configure(function(){313 app.set('views', __dirname + '/views');314 app.set('views');315 // =&gt; "... views directory ..."316317 app.enable('some feature');318 // same as app.set('some feature', true);319320 app.disable('some feature');321 // same as app.set('some feature', false);322});323</code></pre>324

Rebuilt docsTj Holowaychukbefore adoption2724ce3

line 325why, one step back
325<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 326why, one step back
326

Rebuilt docsTj Holowaychukbefore adoption2724ce3

line 327why, one step back
327<pre><code>$ NODE_ENV=production node app.js

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 328–329why, one step back
328</code></pre>
329

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 330–331why, one step back
330<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>
331

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 332–340why, one step back
332<h3 id="Settings">Settings</h3>
333334<p>Express supports the following settings out of the box:</p>335336<ul>337<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>338<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>339<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>340<li><em>view engine</em> Default view engine name for views rendered without extensions</li>

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Updated docsTj Holowaychukbefore adoptionf0eab06

line 343why, one step back
343<li><em>stream threshold</em> Bytesize indicating when a file should be streamed for <em>res.sendfile()</em> using <em>fs.ReadStream()</em> and <em>sys.pump()</em>.</li>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 344–420why, one step back
344</ul>
345346347<h3 id="Routing">Routing</h3>348349<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.350For example we may want to render a user's account for the path <em>/user/12</em>, this351can be done by defining the route below. The values associated to the named placeholders352are available as <code>req.params</code>.</p>353354<pre><code>app.get('/user/:id', function(req, res){355 res.send('user ' + req.params.id);356});357</code></pre>358359<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example360when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>361362<pre><code>\/user\/([^\/]+)\/?363</code></pre>364365<p>Regular expression literals may also be passed for complex uses. Since capture366groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>.</p>367368<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){369 res.send(req.params);370});371</code></pre>372373<p>Curl requests against the previously defined route:</p>374375<pre><code> $ curl http://dev:3000/user376 [null,null]377 $ curl http://dev:3000/users378 [null,null]379 $ curl http://dev:3000/users/1380 ["1",null]381 $ curl http://dev:3000/users/1..15382 ["1","15"]383</code></pre>384385<p>Below are some route examples, and the associated paths that they386may consume:</p>387388<pre><code> "/user/:id"389 /user/12390391 "/users/:id?"392 /users/5393 /users394395 "/files/*"396 /files/jquery.js397 /files/javascripts/jquery.js398399 "/file/*.*"400 /files/jquery.js401 /files/javascripts/jquery.js402403 "/user/:id/:operation?"404 /user/1405 /user/1/edit406407 "/products.:format"408 /products.json409 /products.xml410411 "/products.:format?"412 /products.json413 /products.xml414 /products415</code></pre>416417<h3 id="Passing-Route-Control">Passing Route Control</h3>418419<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,420the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,

Regenerated docsTj Holowaychukbefore adoption334a18a

line 421why, one step back
421and middleware continue to be invoked. The same is true for several routes which have the same path defined, they will simply be executed in order until one does <em>not</em> call <em>next()</em>.</p>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 422why, one step back
422

Updated docsTj Holowaychukbefore adoptionb819366

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 424–435why, one step back
424 var id = req.params.id;
425 if (id) {426 // do something427 } else {428 next();429 }430});431432app.get('/users', function(req, res){433 // do something else434});435</code></pre>

Regenerated docsTj Holowaychukbefore adoption334a18a

line 436why, one step back
436

Regenerated docsTj Holowaychukbefore adoption090debe

lines 437–465why, one step back
437<h3 id="Middleware">Middleware</h3>
438439<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be440passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>441442<pre><code> var express = require('express');443444var app = express.createServer(445 express.logger(),446 express.bodyDecoder()447 );448</code></pre>449450<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>451452<pre><code>app.use(express.logger({ format: ':method :uri' }));453</code></pre>454455<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>456457<pre><code>var connect = require('connect');458app.use(connect.logger());459</code></pre>460461<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>462463<pre><code>app.use(express.logger());464</code></pre>465

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 466–469why, one step back
466<h3 id="Route-Middleware">Route Middleware</h3>
467468<p>Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.</p>469

Regenerated docsTj Holowaychukbefore adoption0faac20

line 470why, one step back
470<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>

Regenerated docsTj Holowaychukbefore adoption334a18a

line 471why, one step back
471

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 472–473why, one step back
472<pre><code>app.get('/user/:id', function(req, res, next){
473 loadUser(req.params.id, function(err, user){

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 474–475why, one step back
474 if (err) return next(err);
475 res.send('Viewing user ' + user.name);

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 476–477why, one step back
476 });
477});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 478–481why, one step back
478</code></pre>
479480<p>To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time.</p>481

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 482–491why, one step back
482<pre><code>function loadUser(req, res, next) {
483 // You would fetch your user from the db484 var user = users[req.params.id];485 if (user) {486 req.user = user;487 next();488 } else {489 next(new Error('Failed to load user ' + req.params.id));490 }491}

Regenerated docsTj Holowaychukbefore adoption334a18a

line 492why, one step back
492

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 493–495why, one step back
493app.get('/user/:id', loadUser, function(req, res){
494 res.send('Viewing user ' + req.user.name);495});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 496–499why, one step back
496</code></pre>
497498<p>Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.</p>499

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 500–501why, one step back
500<pre><code>function andRestrictToSelf(req, res, next) {
501 req.authenticatedUser.id == req.user.id

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 502–503why, one step back
502 ? next()
503 : next(new Error('Unauthorized'));

Regenerated docsTj Holowaychukbefore adoption0faac20

line 504why, one step back
504}

Regenerated docsTj Holowaychukbefore adoption334a18a

line 505why, one step back
505

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 506–508why, one step back
506app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){
507 res.send('Editing user ' + req.user.name);508});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 509–512why, one step back
509</code></pre>
510511<p>Keeping in mind that middleware are simply functions, we can define function that <em>returns</em> the middleware in order to create a more expressive and flexible solution as shown below.</p>512

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 513–515why, one step back
513<pre><code>function andRestrictTo(role) {
514 return function(req, res, next) {515 req.authenticatedUser.role == role

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 516–517why, one step back
516 ? next()
517 : next(new Error('Unauthorized'));

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 518–519why, one step back
518 }
519}

Regenerated docsTj Holowaychukbefore adoption334a18a

line 520why, one step back
520

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 521–523why, one step back
521app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){
522 res.send('Deleted user ' + req.user.name);523});

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 524–527why, one step back
524</code></pre>
525526<p>Commonly used "stacks" of middleware can be passed as an array (<em>applied recursively</em>), which can be mixed and matched to any degree.</p>527

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 528–530why, one step back
528<pre><code>var a = [middleware1, middleware2]
529 , b = [middleware3, middleware4]530 , all = [a, b];

Regenerated docsTj Holowaychukbefore adoption334a18a

line 531why, one step back
531

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 532–533why, one step back
532app.get('/foo', a, function(){});
533app.get('/bar', a, function(){});

Regenerated docsTj Holowaychukbefore adoption334a18a

line 534why, one step back
534

Regenerated docsTj Holowaychukbefore adoption0faac20

lines 535–538why, one step back
535app.get('/', a, middleware3, middleware4, function(){});
536app.get('/', a, b, function(){});537app.get('/', all, function(){});538</code></pre>

Regenerated docsTj Holowaychukbefore adoption334a18a

lines 539–540why, one step back
539
540<p>For this example in full, view the <a href="http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js">route middleware example</a> in the repository.</p>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 541why, one step back
541

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 542–547why, one step back
542<h3 id="HTTP-Methods">HTTP Methods</h3>
543544<p>We have seen <em>app.get()</em> a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as <em>app.post()</em>, <em>app.del()</em>, etc.</p>545546<p> A common example for <em>POST</em> usage, is when "submitting" a form. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it.</p>547

Regenerated guideTj Holowaychukbefore adoptionab3337d

lines 548–552why, one step back
548<pre><code> &lt;form method="post" action="/"&gt;
549 &lt;input type="text" name="user[name]" /&gt;550 &lt;input type="text" name="user[email]" /&gt;551 &lt;input type="submit" value="Submit" /&gt;552 &lt;/form&gt;

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 553–586why, one step back
553</code></pre>
554555<p>By default Express does not know what to do with this request body, so we should add the <em>bodyDecoder</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>556557<pre><code>app.use(express.bodyDecoder());558</code></pre>559560<p>Our route below will now have access to the <em>req.body.user</em> object which will contain the <em>name</em> and <em>email</em> properties when defined.</p>561562<pre><code>app.post('/', function(req, res){563 console.log(req.body.user);564 res.redirect('back');565});566</code></pre>567568<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyDecoder</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>569570<pre><code>app.use(express.bodyDecoder());571app.use(express.methodOverride());572</code></pre>573574<p>The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as <em>PUT</em> and <em>DELETE</em> can still be accessed by clients which can use them directly, although <em>methodOverride</em> provides a great solution for forms. Below shows what the usage of <em>PUT</em> might look like:</p>575576<pre><code>&lt;form method="post" action="/"&gt;577 &lt;input type="hidden" name="_method" value="put" /&gt;578 &lt;input type="text" name="user[name]" /&gt;579 &lt;input type="text" name="user[email]" /&gt;580 &lt;input type="submit" value="Submit" /&gt; 581&lt;/form&gt;582583app.put('/', function(){584 console.log(req.body.user);585 res.redirect('back');586});

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 587–588why, one step back
587</code></pre>
588

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 589–615why, one step back
589<h3 id="Error-Handling">Error Handling</h3>
590591<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,592or passed to <em>next(err)</em>. Below is an example which serves different pages based on our593ad-hoc <em>NotFound</em> exception:</p>594595<pre><code>function NotFound(msg){596 this.name = 'NotFound';597 Error.call(this, msg);598 Error.captureStackTrace(this, arguments.callee);599}600601sys.inherits(NotFound, Error);602603app.get('/404', function(req, res){604 throw new NotFound;605});606607app.get('/500', function(req, res){608 throw new Error('keyboard cat!');609});610</code></pre>611612<p>We can call <em>app.error()</em> several times as shown below.613Here we check for an instanceof <em>NotFound</em> and show the614404 page, or we pass on to the next error handler.</p>615

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 621–645why, one step back
621<pre><code>app.error(function(err, req, res, next){
622 if (err instanceof NotFound) {623 res.render('404.jade');624 } else {625 next(err);626 }627});628</code></pre>629630<p>Here we assume all errors as 500 for the simplicity of631this demo, however you can choose whatever you like</p>632633<pre><code>app.error(function(err, req, res){634 res.render('500.jade', {635 locals: {636 error: err637 } 638 });639});640</code></pre>641642<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware643to report on exceptions. For example if we wish to output exceptions644in "development" mode to <em>stderr</em> we can use:</p>645

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 664–697why, one step back
664
665<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,666and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as667the <em>body</em> local variable in <em>layout.haml</em>.</p>668669<pre><code>app.get('/', function(req, res){670 res.render('index.haml', {671 locals: { title: 'My Site' }672 });673});674</code></pre>675676<p>The new <em>view engine</em> setting allows us to specify our default template engine,677so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>678679<pre><code>app.set('view engine', 'jade');680</code></pre>681682<p>Allowing us to render with:</p>683684<pre><code>res.render('index');685</code></pre>686687<p>vs:</p>688689<pre><code>res.render('index.jade');690</code></pre>691692<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still693mix and match template engines:</p>694695<pre><code>res.render('another-page.ejs');696</code></pre>697

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 698–709why, one step back
698<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>
699700<pre><code>app.set('view options', {701 layout: false702});703</code></pre>704705<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>706707<pre><code>res.render('myview.ejs', { layout: true });708</code></pre>709

Rebuilt docsTj Holowaychukbefore adoption2724ce3

lines 710–724why, one step back
710<p>When an alternate layout is required, we may also specify a path. For example if we have <em>view engine</em> set to <em>jade</em> and a file named <em>./views/mylayout.jade</em> we can simply pass:</p>
711712<pre><code>res.render('page', { layout: 'mylayout' });713</code></pre>714715<p>Otherwise we must specify the extension:</p>716717<pre><code>res.render('page', { layout: 'mylayout.jade' });718</code></pre>719720<p>These paths may also be absolute:</p>721722<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });723</code></pre>724

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 725–732why, one step back
725<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>
726727<pre><code>app.set('view options', {728 open: '{{',729 close: '}}'730});731</code></pre>732

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 733–750why, one step back
733<h3 id="View-Partials">View Partials</h3>
734735<p>The Express view system has built-in support for partials and collections, which are736sort of "mini" views representing a document fragment. For example rather than iterating737in a view to display comments, we would use a partial with collection support:</p>738739<pre><code>partial('comment.haml', { collection: comments });740</code></pre>741742<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,743however if we wished we could use an ejs partial, within a haml view for example.</p>744745<pre><code>partial('comment', { collection: comments });746</code></pre>747748<p>And once again even further, when rendering a collection we can simply pass749an array, if no other options are desired:</p>750

Regenerated docsTj Holowaychukbefore adoption2a40cec

line 751why, one step back
751<pre><code>partial('comment', comments);

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 752–759why, one step back
752</code></pre>
753754<p>When using the partial collection support a few "magic" variables are provided755for free:</p>756757<ul>758<li><em>firstInCollection</em> True if this is the first object</li>759<li><em>indexInCollection</em> Index of the object in the collection</li>

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Regenerated docsTj Holowaychukbefore adoption2a40cec

line 761why, one step back
761<li><em>collectionLength</em> Length of the collection</li>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 762–764why, one step back
762</ul>
763764

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 765–766why, one step back
765<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>
766

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 767–771why, one step back
767<h3 id="Template-Engines">Template Engines</h3>
768769<p>Below are a few template engines commonly used with Express:</p>770771<ul>

Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 774why, one step back
774<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>

Regenerated docsTj Holowaychukbefore adoption2a40cec

line 775why, one step back
775<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 776–777why, one step back
776</ul>
777

Rebuilt docsTj Holowaychukbefore adoption2724ce3

lines 778–792why, one step back
778
779<h3 id="Session-Support">Session Support</h3>780781<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieDecoder</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>782783<pre><code>app.use(express.cookieDecoder());784app.use(express.session());785</code></pre>786787<p>By default the <em>session</em> middleware uses the memory store bundled with Connect, however many implementations exist. For example <a href="http://github.com/visionmedia/connect-redis">connect-redis</a> supplies a <a href="http://code.google.com/p/redis/">Redis</a> session store and can be used as shown below:</p>788789<pre><code>var RedisStore = require('connect-redis');790app.use(express.cookieDecoder());791app.use(express.session({ store: new RedisStore }));792</code></pre>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 793why, one step back
793

Regenerated guideTj Holowaychukbefore adoptionf179979

lines 794–796why, one step back
794<p>Now the <em>req.session</em> and <em>req.sessionStore</em> properties will be accessible to all routes and subsequent middleware. Properties on <em>req.session</em> are automatically saved on a response, so for example if we wish to shopping cart data:</p>
795796<pre><code>var RedisStore = require('connect-redis');

Regenerated docsTj Holowaychukbefore adoption1c9831a

line 797why, one step back
797app.use(express.bodyDecoder());

Regenerated guideTj Holowaychukbefore adoptionf179979

lines 798–820why, one step back
798app.use(express.cookieDecoder());
799app.use(express.session({ store: new RedisStore }));800801app.post('/add-to-cart', function(req, res){802 // Perhaps we posted several items with a form803 // (use the bodyDecoder() middleware for this)804 var items = req.body.items;805 req.session.items = items;806 res.redirect('back');807});808809app.get('/add-to-cart', function(req, res){810 // When redirected back to GET /add-to-cart811 // we could check req.session.items &amp;&amp; req.session.items.length812 // to print out a message813 if (req.session.items &amp;&amp; req.session.items.length) {814 req.flash('info', 'You have %s items in your cart', req.session.items.length);815 }816 res.render('shopping-cart');817});818</code></pre>819820<p>The <em>req.session</em> object also has methods such as <em>Session#touch()</em>, <em>Session#destroy()</em>, <em>Session#regenerate()</em> among others to maintain and manipulate sessions. For more information view the <a href="http://senchalabs.github.com/connect/session.html">Connect Session</a> documentation.</p>

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

lines 821–824why, one step back
821
822<h3 id="Migration-Guide">Migration Guide</h3>823824<p> Pre-beta Express developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application.</p>

Regenerated guideTj Holowaychukbefore adoptionf179979

line 825why, one step back
825

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 826–857why, one step back
826<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>
827828<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>829830<pre><code>req.header('Host');831req.header('host');832req.header('Accept', '*/*');833</code></pre>834835<h3 id="req-accepts-type-">req.accepts(type)</h3>836837<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>838839<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise840the given <em>type</em> is matched by an exact match, and then subtypes. You841may pass the subtype such as "html" which is then converted internally842to "text/html" using the mime lookup table.</p>843844<pre><code>// Accept: text/html845req.accepts('html');846// =&gt; true847848// Accept: text/*; application/json849req.accepts('html');850req.accepts('text/html');851req.accepts('text/plain');852req.accepts('application/json');853// =&gt; true854855req.accepts('image/png');856req.accepts('png');857// =&gt; false

Added req.is() docsTj Holowaychukbefore adoption806aefa

lines 858–902why, one step back
858</code></pre>
859860<h3 id="req-is-type-">req.is(type)</h3>861862<p>Check if the incoming request contains the <em>Content-Type</em>863header field, and it contains the give mime <em>type</em>.</p>864865<pre><code> // With Content-Type: text/html; charset=utf-8866 req.is('html');867 // =&gt; true868869 req.is('text/html');870 // =&gt; true871872 // When Content-Type is application/json873 req.is('json');874 // =&gt; true875876 req.is('application/json');877 // =&gt; true878879 req.is('html');880 // =&gt; false881</code></pre>882883<p>Ad-hoc callbacks can also be registered with Express, to perform884assertions again the request, for example if we need an expressive885way to check if our incoming request is an image, we can register <em>"an image"</em>886callback:</p>887888<pre><code> app.is('an image', function(req){889 return 0 == req.headers['content-type'].indexOf('image');890 });891</code></pre>892893<p>Now within our route callbacks, we can use to to assert content types894such as <em>"image/jpeg"</em>, <em>"image/png"</em>, etc.</p>895896<pre><code> app.post('/image/upload', function(req, res, next){897 if (req.is('an image')) {898 // do something899 } else {900 next();901 }902 });

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 903–904why, one step back
903</code></pre>
904

Merge branch 'is'Tj Holowaychukbefore adoption7a71380

lines 905–917why, one step back
905<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you
906can perform any request assertion you wish.</p>907908<p>Wildcard matches can also be made, simplifying our example above for <em>"an image"</em>, by asserting the <em>subtype</em> only:</p>909910<pre><code>req.is('image/*');911</code></pre>912913<p>We may also assert the <em>type</em> as shown below, which would return true for <em>"application/json"</em>, and <em>"text/json"</em>.</p>914915<pre><code>req.is('*/json');916</code></pre>917

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 918–930why, one step back
918<h3 id="req-param-name-">req.param(name)</h3>
919920<p>Return the value of param <em>name</em> when present.</p>921922<ul>923<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>924<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>925<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>926</ul>927928929<p>To utilize urlencoded request bodies, <em>req.body</em>930should be an object. This can be done by using

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 932–951why, one step back
932
933<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>934935<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>936937<pre><code>req.flash('info', 'email sent');938req.flash('error', 'email delivery failed');939req.flash('info', 'email re-sent');940// =&gt; 2941942req.flash('info');943// =&gt; ['email sent', 'email re-sent']944945req.flash('info');946// =&gt; []947948req.flash();949// =&gt; { error: ['email delivery failed'], info: [] }950</code></pre>951

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 957–1002why, one step back
957<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>
958959<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header960to see if it was issued by an <em>XMLHttpRequest</em>:</p>961962<pre><code>req.xhr963req.isXMLHttpRequest964</code></pre>965966<h3 id="res-header-key-val-">res.header(key[, val])</h3>967968<p>Get or set the response header <em>key</em>.</p>969970<pre><code>res.header('Content-Length');971// =&gt; undefined972973res.header('Content-Length', 123);974// =&gt; 123975976res.header('Content-Length');977// =&gt; 123978</code></pre>979980<h3 id="res-contentType-type-">res.contentType(type)</h3>981982<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>983984<pre><code> var filename = 'path/to/image.png';985 res.contentType(filename);986 // res.headers['Content-Type'] is now "image/png"987</code></pre>988989<h3 id="res-attachment-filename-">res.attachment([filename])</h3>990991<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>992993<pre><code> res.attachment('path/to/my/image.png');994</code></pre>995996<h3 id="res-sendfile-path-">res.sendfile(path)</h3>997998<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>9991000<pre><code>res.sendfile('path/to/my.file');1001</code></pre>1002

Updated docsTj Holowaychukbefore adoptionf0eab06

lines 1003–1014why, one step back
1003<p>This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has <strong>not</strong> been streamed, <em>next(err)</em> will be called on an exception.</p>
10041005<pre><code>res.sendfile(path, function(err, path){1006 if (err) {1007 // handle the error1008 } else {1009 console.log('transferred %s', path);1010 }1011});1012</code></pre>10131014<p>When the filesize exceeds the <em>stream threshold</em> (defaulting to 32k), the file will be streamed using <em>fs.ReadStream</em> and <em>sys.pump()</em>.</p>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 1015–1035why, one step back
1015
1016<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>10171018<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>10191020<pre><code>res.download('path/to/image.png');1021res.download('path/to/image.png', 'foo.png');1022</code></pre>10231024<p>This is equivalent to:</p>10251026<pre><code>res.attachment(file);1027res.sendfile(file);1028</code></pre>10291030<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>10311032<p>The <code>res.send()</code> method is a high level response utility allowing you to pass1033objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status1034code based responses. The following are all valid uses:</p>1035

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 1038–1063why, one step back
1038 res.send({ some: 'json' });
1039 res.send('&lt;p&gt;some html&lt;/p&gt;');1040 res.send('Sorry, cant find that', 404);1041 res.send('text', { 'Content-Type': 'text/plain' }, 201);1042 res.send(404);1043</code></pre>10441045<p>By default the <em>Content-Type</em> response header is set, however if explicitly1046assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1047it will not be set again.</p>10481049<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>10501051<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>10521053<pre><code>res.redirect('/', 301);1054res.redirect('/account');1055res.redirect('http://google.com');1056res.redirect('home');1057res.redirect('back');1058</code></pre>10591060<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1061The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1062the "home" setting and defaults to "/".</p>1063

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1064–1087why, one step back
1064<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>
10651066<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>10671068<pre><code>// "Remember me" for 15 minutes 1069res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1070</code></pre>10711072<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>10731074<pre><code>app.use(express.cookieDecoder());10751076app.get('/', function(req, res){1077 // use req.cookies.rememberme1078});1079</code></pre>10801081<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>10821083<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>10841085<pre><code>res.clearCookie('rememberme');1086</code></pre>1087

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 1088–1097why, one step back
1088<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>
10891090<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1091When a callback function is given a response will <em>not</em> be made1092automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>10931094<p> Most engines accept one or more of the following options,1095 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>10961097<ul>

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

line 1098why, one step back
1098<li><em>scope</em> Template evaluation context (value of <em>this</em>)</li>

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 1099–1100why, one step back
1099<li><em>locals</em> Object containing local variables</li>
1100<li><em>debug</em> Output debugging information</li>

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 1103–1127why, one step back
1103</ul>
110411051106<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>11071108<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1109to the view as a local variable.</p>11101111<ul>1112<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>11131114<ul>1115<li>as: 'something' will add the <em>something</em> local variable</li>1116<li>as: this will use the collection value as the template context</li>1117<li>as: global will merge the collection value's properties with <em>locals</em></li>1118</ul>1119</li>1120<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1121For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1122</ul>112311241125<p>The following are equivalent, and the name of collection value when passed1126to the partial will be <em>movie</em> as derived from the name.</p>1127

Regenerated docsTj Holowaychukbefore adoption2a40cec

lines 1128–1130why, one step back
1128<pre><code>partial('theatre/movie.jade', { collection: movies });
1129partial('theatre/movie.jade', movies);1130partial('movie.jade', { collection: movies });

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 1131–1160why, one step back
1131partial('movie.jade', movies);
1132partial('movie', movies);1133// In view: movie.director1134</code></pre>11351136<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>11371138<pre><code>partial('movie', { collection: movies, as: 'video' });1139// In view: video.director1140</code></pre>11411142<p>Also we can make our movie the value of <em>this</em> within our view so that instead1143of <em>movie.director</em> we could use <em>this.director</em>.</p>11441145<pre><code>partial('movie', { collection: movies, as: this });1146// In view: this.director1147</code></pre>11481149<p>Another alternative is to "explode" the properties of the collection item into1150pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>11511152<pre><code>partials('movie', { collection: movies, as: global });1153// In view: director1154</code></pre>11551156<h3 id="app-set-name-val-">app.set(name[, val])</h3>11571158<p>Apply an application level setting <em>name</em> to <em>val</em>, or1159get the value of <em>name</em> when <em>val</em> is not present:</p>1160

Updated docsTj Holowaychukbefore adoption3234329

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 1164–1283why, one step back
1164</code></pre>
11651166<h3 id="app-enable-name-">app.enable(name)</h3>11671168<p>Enable the given setting <em>name</em>:</p>11691170<pre><code>app.enable('some arbitrary setting');1171app.set('some arbitrary setting');1172// =&gt; true1173</code></pre>11741175<h3 id="app-disable-name-">app.disable(name)</h3>11761177<p>Disable the given setting <em>name</em>:</p>11781179<pre><code>app.disable('some setting');1180app.set('some setting');1181// =&gt; false1182</code></pre>11831184<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>11851186<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>11871188<pre><code>app.configure(function(){1189 // executed for each env1190});11911192app.configure('development', function(){1193 // executed for 'development' only1194});1195</code></pre>11961197<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>11981199<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>12001201<pre><code>app.redirect('google', 'http://google.com');1202</code></pre>12031204<p>Now in a route we may call:</p>12051206<p> res.redirect('google');</p>12071208<p>We may also map dynamic redirects:</p>12091210<pre><code>app.redirect('comments', function(req, res){1211 return '/post/' + req.params.id + '/comments';1212});1213</code></pre>12141215<p>So now we may do the following, and the redirect will dynamically adjust to1216the context of the request. If we called this route with <em>GET /post/12</em> our1217redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>12181219<pre><code>app.get('/post/:id', function(req, res){1220 res.redirect('comments');1221});1222</code></pre>12231224<h3 id="app-error-function-">app.error(function)</h3>12251226<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1227Note that we may set several error handlers by making several calls to this method, however the handler1228should call <em>next(err)</em> if it does not wish to deal with the exception:</p>12291230<pre><code>app.error(function(err, req, res, next){1231 res.send(err.message, 500);1232});1233</code></pre>12341235<h3 id="app-helpers-obj-">app.helpers(obj)</h3>12361237<p>Registers static view helpers.</p>12381239<pre><code>app.helpers({1240 name: function(first, last){ return first + ', ' + last },1241 firstName: 'tj',1242 lastName: 'holowaychuk'1243});1244</code></pre>12451246<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1247as well as the <em>name()</em> function exposed.</p>12481249<pre><code>&lt;%= name(firstName, lastName) %>1250</code></pre>12511252<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>12531254<p>Registers dynamic view helpers. Dynamic view helpers1255are simply functions which accept <em>req</em>, <em>res</em>, and are1256evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1257becomes the local variable it is associated with.</p>12581259<pre><code>app.dynamicHelpers({1260 session: function(req, res){1261 return req.session;1262 }1263});1264</code></pre>12651266<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>12671268<pre><code>&lt;%= session.name %&gt;1269</code></pre>12701271<h3 id="app-mounted-fn-">app.mounted(fn)</h3>12721273<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>12741275<pre><code>var app = express.createServer(),1276 blog = express.createServer();12771278blog.mounted(function(parent){1279 // parent is app1280 // "this" is blog1281});12821283app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1284–1308why, one step back
1284</code></pre>
12851286<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>12871288<p>Register the given template engine <em>exports</em>1289as <em>ext</em>. For example we may wish to map ".html"1290files to jade:</p>12911292<pre><code> app.register('.html', require('jade'));1293</code></pre>12941295<p>This is also useful for libraries that may not1296match extensions correctly. For example my haml.js1297library is installed from npm as "hamljs" so instead1298of layout.hamljs, we can register the engine as ".haml":</p>12991300<pre><code> app.register('.haml', require('haml-js'));1301</code></pre>13021303<p>For engines that do not comply with the Express1304specification, we can also wrap their api this way.</p>13051306<pre><code> app.register('.foo', {1307 render: function(str, options) {1308 // perhaps their api is

Regenerated docsTj Holowaychukbefore adoption5152823

line 1309why, one step back
1309 // return foo.toHTML(str, options);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 1310–1311why, one step back
1310 }
1311 });

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 1312–1345why, one step back
1312</code></pre>
13131314<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>13151316<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1317connections will be accepted via <em>INADDR_ANY</em>.</p>13181319<pre><code>app.listen();1320app.listen(3000);1321app.listen(3000, 'n.n.n.n');1322</code></pre>13231324<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>13251326<pre><code>app.listen('/tmp/express.sock');1327</code></pre>13281329<p>Then try it out:</p>13301331<pre><code>$ telnet /tmp/express.sock1332GET / HTTP/1.113331334HTTP/1.1 200 OK1335Content-Type: text/plain1336Content-Length: 1113371338Hello World1339</code></pre>13401341</div>1342 </div>1343 </div>1344 </body>1345</html>