guide.html
This file
Path
docs/guide.html
1,568 lines · 54.4 KiB · HTML
Last changed by
docsTj Holowaychukbefore adoptionc1a82bf
History of this fileTake it
The walk stopped after 200 commits: lines older than 8d3296f point at it.
Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1–135why, one step back1<html>2 <head>3 <title>Express - node web framework</title>4 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>5 <style>6 #tagline {7 margin-left: 75px;8 margin-bottom: 30px;9 color: rgba(255,255,255,0.7); }10 html {11 background: #1c1c1c url(images/bg.tile.jpg); }1213 body {14 margin: 0;15 padding-bottom: 30px;16 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";17 font-size: 14px;18 line-height: 1.5;19 -webkit-font-smoothing: antialiased;20 background: url(images/bg.jpg) 50% 0 no-repeat;21 color: #8b8b8b; }2223 * {24 outline: none; }2526 em {27 color: white; }2829 a img {30 border: none !important; }3132 a {33 font-weight: bold;34 text-decoration: none;35 color: white;36 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;37 -webkit-transition-duration: 0.15s;38 -webkit-transition-timing-function: ease-out; }39 a:hover {40 opacity: 0.8; }4142 h1, h2, h3, h4 {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; }49 h4 {50 margin-left: 10px;51 font-size: 14px;52 }5354 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; }74 ul li ul {75 margin: 0;76 padding-left: 12px;77 }7879 .man-name, #Express { display:none; }8081 .sect {82 margin-left: 40px; }83 img {84 margin-left: 20px;85 margin-bottom: 15px;86 }8788 #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;114 padding-top: 80px;115 width: 550px; }116117 #toc {118 position: fixed;119 top: 0;120 left: 0;121 margin: 0 0 0 15px;122 padding: 15px;123 height: 100%;124 background: rgba(0,0,0,0.2);125 overflow: auto;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 {Regenerated docsTj Holowaychukbefore adoptiond3abcaf
line 136why, one step back136 margin-left: 75px;Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 137–182why, one step back137 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>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>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>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 183–184why, one step back183<li><a href="#Creating-A-Server">Creating A Server</a></li>184<li><a href="#Creating-An-HTTPS-Server">Creating An HTTPS Server</a></li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 185–192why, one step back185<li><a href="#Configuration">Configuration</a></li>186<li><a href="#Settings">Settings</a></li>187<li><a href="#Routing">Routing</a></li>188<li><a href="#Passing-Route-Control">Passing Route Control</a></li>189<li><a href="#Middleware">Middleware</a></li>190<li><a href="#Route-Middleware">Route Middleware</a></li>191<li><a href="#HTTP-Methods">HTTP Methods</a></li>192<li><a href="#Error-Handling">Error Handling</a></li>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 193why, one step back193<li><a href="#Route-Param-Pre-conditions">Route Param Pre-conditions</a></li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 194–195why, one step back194<li><a href="#View-Rendering">View Rendering</a></li>195<li><a href="#View-Partials">View Partials</a></li>view lookup docsTj Holowaychukbefore adoption8a62f8c
line 196why, one step back196<li><a href="#View-Lookup">View Lookup</a></li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 197–198why, one step back197<li><a href="#Template-Engines">Template Engines</a></li>198<li><a href="#Session-Support">Session Support</a></li>docsTj Holowaychukbefore adoptionc1a82bf
lines 199–201why, one step back199<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">2</a><ul class="section" id="section-2">200<li><a href="#2-x-Migration-Guide">x Migration Guide</a></li>201</ul></li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 202–205why, one step back202<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">203<li><a href="#req-header-key-defaultValue-">header()</a></li>204<li><a href="#req-accepts-type-">accepts()</a></li>205<li><a href="#req-is-type-">is()</a></li>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 206why, one step back206<li><a href="#req-param-name-default-">param()</a></li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 207–213why, one step back207<li><a href="#req-flash-type-msg-">flash()</a></li>208<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>209</ul></li>210<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">211<li><a href="#res-header-key-val-">header()</a></li>212<li><a href="#res-contentType-type-">contentType()</a></li>213<li><a href="#res-attachment-filename-">attachment()</a></li>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 214–215why, one step back214<li><a href="#res-sendfile-path-options-callback-">sendfile()</a></li>215<li><a href="#res-download-file-filename-callback-">download()</a></li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 216–221why, one step back216<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>217<li><a href="#res-redirect-url-status-">redirect()</a></li>218<li><a href="#res-cookie-name-val-options-">cookie()</a></li>219<li><a href="#res-clearCookie-name-">clearCookie()</a></li>220<li><a href="#res-render-view-options-fn-">render()</a></li>221<li><a href="#res-partial-view-options-">partial()</a></li>Re-built docsTj Holowaychukbefore adoption8e63d04
line 222why, one step back222<li><a href="#res-local-name-val-">local()</a></li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 223–226why, one step back223</ul></li>224<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">225<li><a href="#app-set-name-val-">set()</a></li>226<li><a href="#app-enable-name-">enable()</a></li>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 227why, one step back227<li><a href="#app-enabled-name-">enabled()</a></li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 228why, one step back228<li><a href="#app-disable-name-">disable()</a></li>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 229why, one step back229<li><a href="#app-disabled-name-">disabled()</a></li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 230–247why, one step back230<li><a href="#app-configure-env-function-function-">configure()</a></li>231<li><a href="#app-redirect-name-val-">redirect()</a></li>232<li><a href="#app-error-function-">error()</a></li>233<li><a href="#app-helpers-obj-">helpers()</a></li>234<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>235<li><a href="#app-mounted-fn-">mounted()</a></li>236<li><a href="#app-register-ext-exports-">register()</a></li>237<li><a href="#app-listen-port-host-">listen()</a></li>238</ul></li>239</ul>240 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 241 <p id="tagline">242 High performance, high class web development for243 <a href="http://nodejs.org">Node.js</a>244 </p>245 <ul id="menu">246 <li><a href="index.html">Home</a></li>247 <li><a href="guide.html">Guide</a></li>Added screencasts pageTj Holowaychukbefore adoption4144af3
line 248why, one step back248 <li><a href="screencasts.html">Screencasts</a></li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 249–260why, one step back249 <li><a href="applications.html">Applications</a></li>250 </ul>251<div class='mp'>252<h2 id="Express">Express</h2>253<p class="man-name">254 <code>guide</code>255</p>256<h3 id="Installation">Installation</h3>257258<pre><code>$ npm install express259</code></pre>260Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 261why, one step back261<h3 id="Creating-A-Server">Creating A Server</h3>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 262why, one step back262Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 263why, one step back263<p> To create an instance of the <em>express.HTTPServer</em>, simply invoke the <em>createServer()</em> method. With our instance <em>app</em> we can then define routes based on the HTTP verbs, in this example <em>app.get()</em>.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 264–267why, one step back264265<pre><code>var app = require('express').createServer();266267app.get('/', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 268why, one step back268 res.send('hello world');Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 269–273why, one step back269});270271app.listen(3000);272</code></pre>273Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 274–281why, one step back274<h3 id="Creating-An-HTTPS-Server">Creating An HTTPS Server</h3>275276<p> To initialize a <em>express.HTTPSServer</em> we do the same as above, however we277 pass an options object, accepting <em>key</em>, <em>cert</em> and the others mentioned in node's <a href="http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer">https documentation</a>.</p>278279<pre><code> var app = require('express').createServer({ key: ... });280</code></pre>281Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 282–289why, one step back282<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 tracesMerge branch 'docs'Tj Holowaychukbefore adoption64da262
line 290why, one step back290in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 291why, one step back291Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 292why, one step back292otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 293–295why, one step back293294<pre><code>app.configure(function(){295 app.use(express.methodOverride());Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 296why, one step back296 app.use(express.bodyParser());Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 297–300why, one step back297 app.use(app.router);298});299300app.configure('development', function(){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 301why, one step back301 app.use(express.static(__dirname + '/public'));Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 302–305why, one step back302 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));303});304305app.configure('production', function(){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 306–308why, one step back306 var oneYear = 31557600000;307 app.use(express.static({ root: __dirname + '/public', maxAge: oneYear }));308 app.use(express.errorHandler());Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 309–313why, one step back309});310</code></pre>311312<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>313Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 314why, one step back314<pre><code> app.configure(function(){Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 315–316why, one step back315 app.set('views', __dirname + '/views');316 app.set('views');Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 317why, one step back317 // => "/absolute/path/to/views"Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 318–323why, one step back318319 app.enable('some feature');320 // same as app.set('some feature', true);321322 app.disable('some feature');323 // same as app.set('some feature', false);Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 324–327why, one step back324325 app.enabled('some feature')326 // => false327 });Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 328–367why, one step back328</code></pre>329330<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>331332<pre><code>$ NODE_ENV=production node app.js333</code></pre>334335<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>336337<h3 id="Settings">Settings</h3>338339<p>Express supports the following settings out of the box:</p>340341<ul>342<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>343<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>344<li><em>view engine</em> Default view engine name for views rendered without extensions</li>345<li><em>view options</em> An object specifying global view options</li>346</ul>347348349<h3 id="Routing">Routing</h3>350351<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.352For example we may want to render a user's account for the path <em>/user/12</em>, this353can be done by defining the route below. The values associated to the named placeholders354are available as <code>req.params</code>.</p>355356<pre><code>app.get('/user/:id', function(req, res){357 res.send('user ' + req.params.id);358});359</code></pre>360361<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example362when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>363364<pre><code>\/user\/([^\/]+)\/?365</code></pre>366367<p>Regular expression literals may also be passed for complex uses. Since captureRegenerated docsTj Holowaychukbefore adoptiond3abcaf
line 368why, one step back368groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>. So our first capture group would be <em>req.params[0]</em> and the second would follow as <em>req.params[1]</em>.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 369–416why, one step back369370<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){371 res.send(req.params);372});373</code></pre>374375<p>Curl requests against the previously defined route:</p>376377<pre><code> $ curl http://dev:3000/user378 [null,null]379 $ curl http://dev:3000/users380 [null,null]381 $ curl http://dev:3000/users/1382 ["1",null]383 $ curl http://dev:3000/users/1..15384 ["1","15"]385</code></pre>386387<p>Below are some route examples, and the associated paths that they388may consume:</p>389390<pre><code> "/user/:id"391 /user/12392393 "/users/:id?"394 /users/5395 /users396397 "/files/*"398 /files/jquery.js399 /files/javascripts/jquery.js400401 "/file/*.*"402 /files/jquery.js403 /files/javascripts/jquery.js404405 "/user/:id/:operation?"406 /user/1407 /user/1/edit408409 "/products.:format"410 /products.json411 /products.xml412413 "/products.:format?"414 /products.json415 /products.xml416 /productsRegenerated docsTj Holowaychukbefore adoptiond3abcaf
lines 417–420why, one step back417418 "/user/:id.:format?"419 /user/12420 /user/12.jsonFixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 421–422why, one step back421</code></pre>422Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 423why, one step back423<p>For example we can <strong>POST</strong> some json, and echo the json back using the <em>bodyParser</em> middleware which will parse json request bodies (as well as others), and place the result in <em>req.body</em>:</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 424–427why, one step back424425<pre><code>var express = require('express')426 , app = express.createServer();427Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 428why, one step back428app.use(express.bodyParser());Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 429–435why, one step back429430app.post('/', function(req, res){431 res.send(req.body);432});433434app.listen(3000);435</code></pre>Regenerated docsTj Holowaychukbefore adoptiond3abcaf
line 436why, one step back436Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 437why, one step back437<p>Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use <em>'/user/:id(\d+)'</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 438–442why, one step back438439<h3 id="Passing-Route-Control">Passing Route Control</h3>440441<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,442the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 443why, one step back443and middleware continue to be invoked in the order that they are added via <em>use()</em>. 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> and decides to respond.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 444–458why, one step back444445<pre><code>app.get('/users/:id?', function(req, res, next){446 var id = req.params.id;447 if (id) {448 // do something449 } else {450 next();451 }452});453454app.get('/users', function(req, res){455 // do something else456});457</code></pre>458Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 459why, one step back459<p>The <em>app.all()</em> method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to <em>req.user</em>.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 460–501why, one step back460461<pre><code>var express = require('express')462 , app = express.createServer();463464var users = [{ name: 'tj' }];465466app.all('/user/:id/:op?', function(req, res, next){467 req.user = users[req.params.id];468 if (req.user) {469 next();470 } else {471 next(new Error('cannot find user ' + req.params.id));472 }473});474475app.get('/user/:id', function(req, res){476 res.send('viewing ' + req.user.name);477});478479app.get('/user/:id/edit', function(req, res){480 res.send('editing ' + req.user.name);481});482483app.put('/user/:id', function(req, res){484 res.send('updating ' + req.user.name);485});486487app.get('*', function(req, res){488 res.send('what???', 404);489});490491app.listen(3000); 492</code></pre>493494<h3 id="Middleware">Middleware</h3>495496<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be497passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>498499<pre><code> var express = require('express');500501var app = express.createServer(Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 502–503why, one step back502 express.logger()503 , express.bodyParser()Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 504–506why, one step back504 );505</code></pre>506Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 507why, one step back507<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 508–515why, one step back508509<pre><code>app.use(express.logger({ format: ':method :uri' }));510</code></pre>511512<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>513514<pre><code>var connect = require('connect');515app.use(connect.logger());Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 516why, one step back516app.use(connect.bodyParser());Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 517–521why, one step back517</code></pre>518519<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>520521<pre><code>app.use(express.logger());Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 522why, one step back522app.use(express.bodyParser());Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 523–531why, one step back523</code></pre>524525<h3 id="Route-Middleware">Route Middleware</h3>526527<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>528529<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>530531<pre><code>app.get('/user/:id', function(req, res, next){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 532–535why, one step back532 loadUser(req.params.id, function(err, user){533 if (err) return next(err);534 res.send('Viewing user ' + user.name);535 });Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 536–541why, one step back536});537</code></pre>538539<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>540541<pre><code>function loadUser(req, res, next) {Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 542–549why, one step back542 // You would fetch your user from the db543 var user = users[req.params.id];544 if (user) {545 req.user = user;546 next();547 } else {548 next(new Error('Failed to load user ' + req.params.id));549 }Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 550–552why, one step back550}551552app.get('/user/:id', loadUser, function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 553why, one step back553 res.send('Viewing user ' + req.user.name);Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 554–559why, one step back554});555</code></pre>556557<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>558559<pre><code>function andRestrictToSelf(req, res, next) {Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 560–562why, one step back560 req.authenticatedUser.id == req.user.id561 ? next()562 : next(new Error('Unauthorized'));Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 563–565why, one step back563}564565app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 566why, one step back566 res.send('Editing user ' + req.user.name);Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 567–572why, one step back567});568</code></pre>569570<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>571572<pre><code>function andRestrictTo(role) {Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 573–577why, one step back573 return function(req, res, next) {574 req.authenticatedUser.role == role575 ? next()576 : next(new Error('Unauthorized'));577 }Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 578–580why, one step back578}579580app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 581why, one step back581 res.send('Deleted user ' + req.user.name);Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 582–613why, one step back582});583</code></pre>584585<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>586587<pre><code>var a = [middleware1, middleware2]588 , b = [middleware3, middleware4]589 , all = [a, b];590591app.get('/foo', a, function(){});592app.get('/bar', a, function(){});593594app.get('/', a, middleware3, middleware4, function(){});595app.get('/', a, b, function(){});596app.get('/', all, function(){});597</code></pre>598599<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>600601<h3 id="HTTP-Methods">HTTP Methods</h3>602603<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>604605<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>606607<pre><code> <form method="post" action="/">608 <input type="text" name="user[name]" />609 <input type="text" name="user[email]" />610 <input type="submit" value="Submit" />611 </form>612</code></pre>613Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 614why, one step back614<p>By default Express does not know what to do with this request body, so we should add the <em>bodyParser</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> and <em>application/json</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 615why, one step back615Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 616why, one step back616<pre><code>app.use(express.bodyParser());Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 617–621why, one step back617</code></pre>618619<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>620621<pre><code>app.post('/', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 622–623why, one step back622 console.log(req.body.user);623 res.redirect('back');Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 624–626why, one step back624});625</code></pre>626Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 627why, one step back627<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>bodyParser</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 628why, one step back628Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 629why, one step back629<pre><code>app.use(express.bodyParser());Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 630–654why, one step back630app.use(express.methodOverride());631</code></pre>632633<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>634635<pre><code><form method="post" action="/">636 <input type="hidden" name="_method" value="put" />637 <input type="text" name="user[name]" />638 <input type="text" name="user[email]" />639 <input type="submit" value="Submit" /> 640</form>641642app.put('/', function(){643 console.log(req.body.user);644 res.redirect('back');645});646</code></pre>647648<h3 id="Error-Handling">Error Handling</h3>649650<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,651or passed to <em>next(err)</em>. Below is an example which serves different pages based on our652ad-hoc <em>NotFound</em> exception:</p>653654<pre><code>function NotFound(msg){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 655–657why, one step back655 this.name = 'NotFound';656 Error.call(this, msg);657 Error.captureStackTrace(this, arguments.callee);Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 658–659why, one step back658}659Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 660why, one step back660NotFound.protoype.__proto__ = Error.prototype;Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 661–662why, one step back661662app.get('/404', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 663why, one step back663 throw new NotFound;Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 664–666why, one step back664});665666app.get('/500', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 667why, one step back667 throw new Error('keyboard cat!');Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 668–689why, one step back668});669</code></pre>670671<p>We can call <em>app.error()</em> several times as shown below.672Here we check for an instanceof <em>NotFound</em> and show the673404 page, or we pass on to the next error handler.</p>674675<p>Note that these handlers can be defined anywhere, as they676will be placed below the route handlers on <em>listen()</em>. This677allows for definition within <em>configure()</em> blocks so we can678handle exceptions in different ways based on the environment.</p>679680<pre><code>app.error(function(err, req, res, next){681 if (err instanceof NotFound) {682 res.render('404.jade');683 } else {684 next(err);685 }686});687</code></pre>688689<p>Here we assume all errors as 500 for the simplicity ofMerge branch 'docs'Tj Holowaychukbefore adoption64da262
line 690why, one step back690this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the <em>error.code</em> of <em>ENOENT</em>, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 691–692why, one step back691692<pre><code>app.error(function(err, req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 693–695why, one step back693 res.render('500.jade', {694 error: err695 });Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 696–713why, one step back696});697</code></pre>698699<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware700to report on exceptions. For example if we wish to output exceptions701in "development" mode to <em>stderr</em> we can use:</p>702703<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));704</code></pre>705706<p>Also during development we may want fancy html pages to show exceptions707that are passed or thrown, so we can set <em>showStack</em> to true:</p>708709<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));710</code></pre>711712<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>713is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
line 714why, one step back714Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 715why, one step back715<h3 id="Route-Param-Pre-conditions">Route Param Pre-conditions</h3>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
line 716why, one step back716Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 717why, one step back717<p>Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for <em>/user/:id</em>, we might typically do something like below:</p>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
lines 718–726why, one step back718719<pre><code>app.get('/user/:userId', function(req, res, next){720 User.get(req.params.userId, function(err, user){721 if (err) return next(err);722 res.send('user ' + user.name);723 });724}); 725</code></pre>726Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 727why, one step back727<p>With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
lines 728–754why, one step back728729<pre><code>app.param('userId', function(req, res, next, id){730 User.get(id, function(err, user){731 if (err) return next(err);732 if (!user) return next(new Error('failed to find user'));733 req.user = user;734 next();735 });736});737</code></pre>738739<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>740741<pre><code>app.get('/user/:userId', function(req, res){742 res.send('user ' + req.user.name);743});744</code></pre>745746<p>For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to <em>next(err)</em>.</p>747748<pre><code>app.param('number', function(n){ return parseInt(n, 10); });749</code></pre>750751<p>We may also apply the same callback to several placeholders, for example a route GET <em>/commits/:from-:to</em> are both numbers, so we may define them as an array:</p>752753<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });754</code></pre>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 755–757why, one step back755756<h3 id="View-Rendering">View Rendering</h3>757Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 758why, one step back758<p>View filenames take the form "<name>.<engine>", where <engine> is the nameFixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 759why, one step back759of the module that will be required. For example the view <em>layout.ejs</em> willMerge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 760–761why, one step back760tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.compile(str, options)</em>, and return a <em>Function</em> to comply with Express. To alter this behaviour761<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 762why, one step back762Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 763–765why, one step back763<p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,764and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as765the <em>body</em> local variable in <em>layout.jade</em>.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 766–767why, one step back766767<pre><code>app.get('/', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 768why, one step back768 res.render('index.jade', { title: 'My Site' });Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 769–772why, one step back769});770</code></pre>771772<p>The new <em>view engine</em> setting allows us to specify our default template engine,Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 773why, one step back773so for example when using jade we could set:</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 774–796why, one step back774775<pre><code>app.set('view engine', 'jade');776</code></pre>777778<p>Allowing us to render with:</p>779780<pre><code>res.render('index');781</code></pre>782783<p>vs:</p>784785<pre><code>res.render('index.jade');786</code></pre>787788<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still789mix and match template engines:</p>790791<pre><code>res.render('another-page.ejs');792</code></pre>793794<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>795796<pre><code>app.set('view options', {Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 797why, one step back797 layout: falseFixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 798–800why, one step back798});799</code></pre>800Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 801why, one step back801<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 802–830why, one step back802803<pre><code>res.render('myview.ejs', { layout: true });804</code></pre>805806<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>807808<pre><code>res.render('page', { layout: 'mylayout' });809</code></pre>810811<p>Otherwise we must specify the extension:</p>812813<pre><code>res.render('page', { layout: 'mylayout.jade' });814</code></pre>815816<p>These paths may also be absolute:</p>817818<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });819</code></pre>820821<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>822823<pre><code>app.set('view options', {824 open: '{{',825 close: '}}'826});827</code></pre>828829<h3 id="View-Partials">View Partials</h3>830Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 831why, one step back831<p>The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iteratingFixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 832–836why, one step back832in a view to display comments, we would use a partial with collection support:</p>833834<pre><code>partial('comment', { collection: comments });835</code></pre>836Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 837why, one step back837<p>If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 838–845why, one step back838839<pre><code>partial('comment', comments);840</code></pre>841842<p>When using the partial collection support a few "magic" variables are provided843for free:</p>844845<ul>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 846–849why, one step back846<li><em>firstInCollection</em> true if this is the first object</li>847<li><em>indexInCollection</em> index of the object in the collection</li>848<li><em>lastInCollection</em> true if this is the last object</li>849<li><em>collectionLength</em> length of the collection</li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 850–852why, one step back850</ul>851852docsTj Holowaychukbefore adoption4609984
lines 853–854why, one step back853<p>Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well. So for example if we were to render a blog post with <em>partial('blog/post', post)</em> it would generate the <em>post</em> local, but the view calling this function had the local <em>user</em>, it would be available to the <em>blog/post</em> view as well.</p>854Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 855–856why, one step back855<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>856view lookup docsTj Holowaychukbefore adoption8a62f8c
lines 857–863why, one step back857<p><strong>NOTE:</strong> be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead.</p>858859<h3 id="View-Lookup">View Lookup</h3>860861<p>View lookup is performed relative to the parent view, for example if we had a page view named <em>views/user/list.jade</em>, and within that view we did <em>partial('edit')</em> it would attempt to load <em>views/user/edit.jade</em>, whereas <em>partial('../messages')</em> would load <em>views/messages.jade</em>.</p>862863<p>The view system also allows for index templates, allowing you to have a directory of the same name. For example within a route we may have <em>res.render('users')</em> either <em>views/users.jade</em>, or <em>views/users/index.jade</em>.</p>Added screencasts pageTj Holowaychukbefore adoption4144af3
line 864why, one step back864more docsTj Holowaychukbefore adoption0b6a941
lines 865–866why, one step back865<p>When utilizing index views as shown above, we may reference <em>views/users/index.jade</em> from a view in the same directory by <em>partial('users')</em>, and the view system will try <em>../users/index</em>, preventing us from needing to call <em>partial('index')</em>.</p>866Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 867–880why, one step back867<h3 id="Template-Engines">Template Engines</h3>868869<p>Below are a few template engines commonly used with Express:</p>870871<ul>872<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>873<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>874<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>875<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>876</ul>877878879<h3 id="Session-Support">Session Support</h3>880Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 881why, one step back881<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieParser</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 882why, one step back882Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 883–884why, one step back883<pre><code>app.use(express.cookieParser());884app.use(express.session({ secret: "keyboard cat" }));Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 885–889why, one step back885</code></pre>886887<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>888889<pre><code>var RedisStore = require('connect-redis');Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 890–891why, one step back890app.use(express.cookieParser());891app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 892–896why, one step back892</code></pre>893894<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>895896<pre><code>var RedisStore = require('connect-redis');Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 897–899why, one step back897app.use(express.bodyParser());898app.use(express.cookieParser());899app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 900–902why, one step back900901app.post('/add-to-cart', function(req, res){902 // Perhaps we posted several items with a formMerge branch 'docs'Tj Holowaychukbefore adoption64da262
line 903why, one step back903 // (use the bodyParser() middleware for this)Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 904–919why, one step back904 var items = req.body.items;905 req.session.items = items;906 res.redirect('back');907});908909app.get('/add-to-cart', function(req, res){910 // When redirected back to GET /add-to-cart911 // we could check req.session.items && req.session.items.length912 // to print out a message913 if (req.session.items && req.session.items.length) {914 req.flash('info', 'You have %s items in your cart', req.session.items.length);915 }916 res.render('shopping-cart');917});918</code></pre>919Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 920why, one step back920<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/middleware-session.html">Connect Session</a> documentation.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 921why, one step back921docsTj Holowaychukbefore adoptionc1a82bf
line 922why, one step back922<h3 id="2-x-Migration-Guide">2.x Migration Guide</h3>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 923why, one step back923docsTj Holowaychukbefore adoptionc1a82bf
line 924why, one step back924<p> Express 1.x developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application to work with Express 2.x, Connect 1.x, and Node 0.4.x.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 925–934why, one step back925926<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>927928<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>929930<pre><code>req.header('Host');931req.header('host');932req.header('Accept', '*/*');933</code></pre>934Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 935–945why, one step back935<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>936937<pre><code>// sent Referrer: http://google.com938939req.header('Referer');940// => "http://google.com"941942req.header('Referrer');943// => "http://google.com"944</code></pre>945Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 946–1024why, one step back946<h3 id="req-accepts-type-">req.accepts(type)</h3>947948<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>949950<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise951the given <em>type</em> is matched by an exact match, and then subtypes. You952may pass the subtype such as "html" which is then converted internally953to "text/html" using the mime lookup table.</p>954955<pre><code>// Accept: text/html956req.accepts('html');957// => true958959// Accept: text/*; application/json960req.accepts('html');961req.accepts('text/html');962req.accepts('text/plain');963req.accepts('application/json');964// => true965966req.accepts('image/png');967req.accepts('png');968// => false969</code></pre>970971<h3 id="req-is-type-">req.is(type)</h3>972973<p>Check if the incoming request contains the <em>Content-Type</em>974header field, and it contains the give mime <em>type</em>.</p>975976<pre><code> // With Content-Type: text/html; charset=utf-8977 req.is('html');978 req.is('text/html');979 // => true980981 // When Content-Type is application/json982 req.is('json');983 req.is('application/json');984 // => true985986 req.is('html');987 // => false988</code></pre>989990<p>Ad-hoc callbacks can also be registered with Express, to perform991assertions again the request, for example if we need an expressive992way to check if our incoming request is an image, we can register <em>"an image"</em>993callback:</p>994995<pre><code> app.is('an image', function(req){996 return 0 == req.headers['content-type'].indexOf('image');997 });998</code></pre>9991000<p>Now within our route callbacks, we can use to to assert content types1001such as <em>"image/jpeg"</em>, <em>"image/png"</em>, etc.</p>10021003<pre><code> app.post('/image/upload', function(req, res, next){1004 if (req.is('an image')) {1005 // do something1006 } else {1007 next();1008 }1009 });1010</code></pre>10111012<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you1013can perform any request assertion you wish.</p>10141015<p>Wildcard matches can also be made, simplifying our example above for <em>"an image"</em>, by asserting the <em>subtype</em> only:</p>10161017<pre><code>req.is('image/*');1018</code></pre>10191020<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>10211022<pre><code>req.is('*/json');1023</code></pre>1024Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1025why, one step back1025<h3 id="req-param-name-default-">req.param(name[, default])</h3>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 1026why, one step back1026Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1027why, one step back1027<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1028–1029why, one step back10281029<ul>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1030why, one step back1030<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1031–1037why, one step back1031<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1032<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1033</ul>103410351036<p>To utilize urlencoded request bodies, <em>req.body</em>1037should be an object. This can be done by usingMerge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1038why, one step back1038the _express.bodyParser middleware.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1039–1092why, one step back10391040<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>10411042<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>10431044<pre><code>req.flash('info', 'email sent');1045req.flash('error', 'email delivery failed');1046req.flash('info', 'email re-sent');1047// => 210481049req.flash('info');1050// => ['email sent', 'email re-sent']10511052req.flash('info');1053// => []10541055req.flash();1056// => { error: ['email delivery failed'], info: [] }1057</code></pre>10581059<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>10601061<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1062</code></pre>10631064<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>10651066<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1067to see if it was issued by an <em>XMLHttpRequest</em>:</p>10681069<pre><code>req.xhr1070req.isXMLHttpRequest1071</code></pre>10721073<h3 id="res-header-key-val-">res.header(key[, val])</h3>10741075<p>Get or set the response header <em>key</em>.</p>10761077<pre><code>res.header('Content-Length');1078// => undefined10791080res.header('Content-Length', 123);1081// => 12310821083res.header('Content-Length');1084// => 1231085</code></pre>10861087<h3 id="res-contentType-type-">res.contentType(type)</h3>10881089<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>10901091<pre><code> var filename = 'path/to/image.png';1092 res.contentType(filename);Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1093why, one step back1093 // Content-Type is now "image/png"Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1094–1102why, one step back1094</code></pre>10951096<h3 id="res-attachment-filename-">res.attachment([filename])</h3>10971098<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>10991100<pre><code> res.attachment('path/to/my/image.png');1101</code></pre>1102Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1103why, one step back1103<h3 id="res-sendfile-path-options-callback-">res.sendfile(path[, options[, callback]])</h3>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1104–1109why, one step back11041105<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>11061107<pre><code>res.sendfile('path/to/my.file');1108</code></pre>1109Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1110–1111why, one step back1110<p>This method accepts an optional callback which is called when1111an error occurs, or when the transfer is complete. By default failures call <code>next(err)</code>, however when a callback is supplied you must do this explicitly, or act on the error.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 1112why, one step back1112Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1113why, one step back1113<pre><code>res.sendfile(path, function(err){Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 1114why, one step back1114 if (err) {Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1115why, one step back1115 next(err);Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1116–1121why, one step back1116 } else {1117 console.log('transferred %s', path);1118 }1119});1120</code></pre>1121Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1122why, one step back1122<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 1123why, one step back1123Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1124–1127why, one step back1124<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1125 // handle1126});1127</code></pre>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 1128why, one step back1128Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1129–1130why, one step back1129<h3 id="res-download-file-filename-callback-">res.download(file[, filename[, callback]])</h3>1130Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1131–1142why, one step back1131<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>11321133<pre><code>res.download('path/to/image.png');1134res.download('path/to/image.png', 'foo.png');1135</code></pre>11361137<p>This is equivalent to:</p>11381139<pre><code>res.attachment(file);1140res.sendfile(file);1141</code></pre>1142Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1143–1149why, one step back1143<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>:</p>11441145<pre><code>res.download(path, 'expenses.doc', function(err){1146 // handle1147});1148</code></pre>1149Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1150–1151why, one step back1150<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>1151Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1152–1153why, one step back1152<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1153objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1154–1166why, one step back11541155<pre><code> res.send(); // 2041156 res.send(new Buffer('wahoo'));1157 res.send({ some: 'json' });1158 res.send('<p>some html</p>');1159 res.send('Sorry, cant find that', 404);1160 res.send('text', { 'Content-Type': 'text/plain' }, 201);1161 res.send(404);1162</code></pre>11631164<p>By default the <em>Content-Type</em> response header is set, however if explicitly1165assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1166it will not be set again.</p>Added screencasts pageTj Holowaychukbefore adoption4144af3
line 1167why, one step back1167Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1168why, one step back1168<p>Note that this method <em>end()</em>s the response, so you will want to use node's <em>res.write()</em> for multiple writes or streaming.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1169–1186why, one step back11691170<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>11711172<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>11731174<pre><code>res.redirect('/', 301);1175res.redirect('/account');1176res.redirect('http://google.com');1177res.redirect('home');1178res.redirect('back');1179</code></pre>11801181<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1182The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1183the "home" setting and defaults to "/".</p>11841185<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>1186Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1187why, one step back1187<p>Sets the given cookie <em>name</em> to <em>val</em>, with options <em>httpOnly</em>, <em>secure</em>, <em>expires</em> etc.</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1188–1194why, one step back11881189<pre><code>// "Remember me" for 15 minutes 1190res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1191</code></pre>11921193<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>1194Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1195why, one step back1195<pre><code>app.use(express.cookieParser());Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1196–1197why, one step back11961197app.get('/', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1198why, one step back1198 // use req.cookies.remembermeFixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1199–1214why, one step back1199});1200</code></pre>12011202<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>12031204<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>12051206<pre><code>res.clearCookie('rememberme');1207</code></pre>12081209<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>12101211<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1212When a callback function is given a response will <em>not</em> be made1213automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>1214Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1215why, one step back1215<p>The <em>options</em> passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 1216why, one step back1216Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1217–1219why, one step back1217<pre><code>var user = { name: 'tj' };1218res.render('index', { layout: false, user: user });1219</code></pre>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1220–1292why, one step back12201221<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>12221223<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1224to the view as a local variable.</p>12251226<ul>1227<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1228<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>12291230<ul>1231<li>as: 'something' will add the <em>something</em> local variable</li>1232<li>as: this will use the collection value as the template context</li>1233<li>as: global will merge the collection value's properties with <em>locals</em></li>1234</ul>1235</li>1236<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1237For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1238</ul>123912401241<p>The following are equivalent, and the name of collection value when passed1242to the partial will be <em>movie</em> as derived from the name.</p>12431244<pre><code>partial('theatre/movie.jade', { collection: movies });1245partial('theatre/movie.jade', movies);1246partial('movie.jade', { collection: movies });1247partial('movie.jade', movies);1248partial('movie', movies);1249// In view: movie.director1250</code></pre>12511252<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>12531254<pre><code>partial('movie', { collection: movies, as: 'video' });1255// In view: video.director1256</code></pre>12571258<p>Also we can make our movie the value of <em>this</em> within our view so that instead1259of <em>movie.director</em> we could use <em>this.director</em>.</p>12601261<pre><code>partial('movie', { collection: movies, as: this });1262// In view: this.director1263</code></pre>12641265<p>Another alternative is to "explode" the properties of the collection item into1266pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>12671268<pre><code>partial('movie', { collection: movies, as: global });1269// In view: director1270</code></pre>12711272<p>This same logic applies to a single partial object usage:</p>12731274<pre><code>partial('movie', { object: movie, as: this });1275// In view: this.director12761277partial('movie', { object: movie, as: global });1278// In view: director12791280partial('movie', { object: movie, as: 'video' });1281// In view: video.director12821283partial('movie', { object: movie });1284// In view: movie.director1285</code></pre>12861287<p>When a non-collection (does <em>not</em> have <em>.length</em>) is passed as the second argument, it is assumed to be the <em>object</em>, after which the object's local variable name is derived from the view name:</p>12881289<pre><code>partial('movie', movie);1290// => In view: movie.director1291</code></pre>1292Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1293–1308why, one step back1293<p>This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:</p>12941295<pre><code>app.get('/users', function(req, res){1296 if (req.xhr) {1297 // respond with the each user in the collection1298 // passed to the "user" view1299 res.partial('user', users);1300 } else {1301 // respond with layout, and users page1302 // which internally does partial('user', users)1303 // along with other UI1304 res.render('users', { users: users });1305 }1306});1307</code></pre>1308Re-built docsTj Holowaychukbefore adoption8e63d04
lines 1309–1326why, one step back1309<h3 id="res-local-name-val-">res.local(name[, val])</h3>13101311<p>Get or set the given local variable <em>name</em>. The locals built up for a response are applied to those given to the view rendering methods such as <code>res.render()</code>.</p>13121313<pre><code> app.all('/movie/:id', function(req, res, next){1314 Movie.get(req.params.id, function(err, movie){1315 // Assigns res.locals.movie = movie1316 res.local('movie', movie);1317 });1318 });13191320 app.get('/movie/:id', function(req, res){1321 // movie is already a local, however we1322 // can pass more if we wish1323 res.render('movie', { displayReviews: true });1324 });1325</code></pre>1326Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1327–1349why, one step back1327<h3 id="app-set-name-val-">app.set(name[, val])</h3>13281329<p>Apply an application level setting <em>name</em> to <em>val</em>, or1330get the value of <em>name</em> when <em>val</em> is not present:</p>13311332<pre><code>app.set('views', __dirname + '/views');1333app.set('views');1334// => ...path...1335</code></pre>13361337<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>13381339<pre><code>app.settings.views1340// => ...path...1341</code></pre>13421343<h3 id="app-enable-name-">app.enable(name)</h3>13441345<p>Enable the given setting <em>name</em>:</p>13461347<pre><code>app.enable('some arbitrary setting');1348app.set('some arbitrary setting');1349// => trueRe-built docsTj Holowaychukbefore adoption8e63d04
lines 1350–1352why, one step back13501351app.enabled('some arbitrary setting');1352// => trueFixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1353–1354why, one step back1353</code></pre>1354Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1355–1366why, one step back1355<h3 id="app-enabled-name-">app.enabled(name)</h3>13561357<p>Check if setting <em>name</em> is enabled:</p>13581359<pre><code>app.enabled('view cache');1360// => false13611362app.enable('view cache');1363app.enabled('view cache');1364// => true1365</code></pre>1366Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1367–1372why, one step back1367<h3 id="app-disable-name-">app.disable(name)</h3>13681369<p>Disable the given setting <em>name</em>:</p>13701371<pre><code>app.disable('some setting');1372app.set('some setting');Re-built docsTj Holowaychukbefore adoption8e63d04
lines 1373–1375why, one step back1373// => false13741375app.disabled('some setting');Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1376–1378why, one step back1376// => false1377</code></pre>1378Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1379–1392why, one step back1379<h3 id="app-disabled-name-">app.disabled(name)</h3>13801381<p>Check if setting <em>name</em> is disabled:</p>13821383<pre><code>app.enable('view cache');13841385app.disabled('view cache');1386// => false13871388app.disable('view cache');1389app.disabled('view cache');1390// => true1391</code></pre>1392Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1393–1407why, one step back1393<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>13941395<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>13961397<pre><code>app.configure(function(){1398 // executed for each env1399});14001401app.configure('development', function(){1402 // executed for 'development' only1403});1404</code></pre>14051406<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>1407Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1408why, one step back1408<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1409–1419why, one step back14091410<pre><code>app.redirect('google', 'http://google.com');1411</code></pre>14121413<p>Now in a route we may call:</p>14141415<p> res.redirect('google');</p>14161417<p>We may also map dynamic redirects:</p>14181419<pre><code>app.redirect('comments', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1420why, one step back1420 return '/post/' + req.params.id + '/comments';Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1421–1428why, one step back1421});1422</code></pre>14231424<p>So now we may do the following, and the redirect will dynamically adjust to1425the context of the request. If we called this route with <em>GET /post/12</em> our1426redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>14271428<pre><code>app.get('/post/:id', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1429why, one step back1429 res.redirect('comments');Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1430–1432why, one step back1430});1431</code></pre>1432Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1433–1437why, one step back1433<p>When mounted, <em>res.redirect()</em> will respect the mount-point. For example if a blog app is mounted at <em>/blog</em>, the following will redirect to <em>/blog/posts</em>:</p>14341435<pre><code>res.redirect('/posts');1436</code></pre>1437Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1438–1444why, one step back1438<h3 id="app-error-function-">app.error(function)</h3>14391440<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1441Note that we may set several error handlers by making several calls to this method, however the handler1442should call <em>next(err)</em> if it does not wish to deal with the exception:</p>14431444<pre><code>app.error(function(err, req, res, next){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1445why, one step back1445 res.send(err.message, 500);Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1446–1452why, one step back1446});1447</code></pre>14481449<h3 id="app-helpers-obj-">app.helpers(obj)</h3>14501451<p>Registers static view helpers.</p>1452Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1453–1457why, one step back1453<p> app.helpers({</p>14541455<pre><code> name: function(first, last){ return first + ', ' + last }1456, firstName: 'tj'1457, lastName: 'holowaychuk'Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1458–1459why, one step back1458</code></pre>1459Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1460–1461why, one step back1460<p> });</p>1461Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1462–1475why, one step back1462<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1463as well as the <em>name()</em> function exposed.</p>14641465<pre><code><%= name(firstName, lastName) %>1466</code></pre>14671468<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>14691470<p>Registers dynamic view helpers. Dynamic view helpers1471are simply functions which accept <em>req</em>, <em>res</em>, and are1472evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1473becomes the local variable it is associated with.</p>14741475<pre><code>app.dynamicHelpers({Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1476–1478why, one step back1476 session: function(req, res){1477 return req.session;1478 }Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1479–1494why, one step back1479});1480</code></pre>14811482<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>14831484<pre><code><%= session.name %>1485</code></pre>14861487<h3 id="app-mounted-fn-">app.mounted(fn)</h3>14881489<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>14901491<pre><code>var app = express.createServer(),1492 blog = express.createServer();14931494blog.mounted(function(parent){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1495–1496why, one step back1495 // parent is app1496 // "this" is blogFixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1497–1519why, one step back1497});14981499app.use(blog);1500</code></pre>15011502<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>15031504<p>Register the given template engine <em>exports</em>1505as <em>ext</em>. For example we may wish to map ".html"1506files to jade:</p>15071508<pre><code> app.register('.html', require('jade'));1509</code></pre>15101511<p>This is also useful for libraries that may not1512match extensions correctly. For example my haml.js1513library is installed from npm as "hamljs" so instead1514of layout.hamljs, we can register the engine as ".haml":</p>15151516<pre><code> app.register('.haml', require('haml-js'));1517</code></pre>15181519<p>For engines that do not comply with the ExpressMerge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1520–1523why, one step back1520specification, we can also wrap their api this way. Below1521we map <em>.md</em> to render markdown files, rendering the html once1522since it will not change on subsequent calls, and support local substitution1523in the form of "{name}".</p>Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
line 1524why, one step back1524Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1525–1534why, one step back1525<pre><code> app.register('.md', {1526 compile: function(str, options){1527 var html = md.toHTML(str);1528 return function(locals){1529 return html.replace(/\{([^}]+)\}/g, function(_, name){1530 return locals[name];1531 });1532 };1533 }1534 });Fixed mvc example due to view lookup changesTj Holowaychukbefore adoption8d3296f
lines 1535–1568why, one step back1535</code></pre>15361537<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>15381539<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1540connections will be accepted via <em>INADDR_ANY</em>.</p>15411542<pre><code>app.listen();1543app.listen(3000);1544app.listen(3000, 'n.n.n.n');1545</code></pre>15461547<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>15481549<pre><code>app.listen('/tmp/express.sock');1550</code></pre>15511552<p>Then try it out:</p>15531554<pre><code>$ telnet /tmp/express.sock1555GET / HTTP/1.115561557HTTP/1.1 200 OK1558Content-Type: text/plain1559Content-Length: 1115601561Hello World1562</code></pre>15631564</div>1565 </div>1566 </div>1567 </body>1568</html>