guide.html
This file
Path
docs/guide.html
1,810 lines · 63.4 KiB · HTML
Last changed by
fixed some docsTj Holowaychukbefore adoptione8c32df
History of this fileTake it
The walk stopped after 200 commits: lines older than cdbd8af point at it.
migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1–181why, 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 {136 margin-left: 75px;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>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">fixed some docsTj Holowaychukbefore adoptione8c32df
lines 182–187why, one step back182183</ul><ul id="toc">184185</ul><ul id="toc">186187</ul><ul id="toc">fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 188–205why, one step back188<li><a href="#installation">Installation</a></li>189<li><a href="#creating-a server">Creating A Server</a></li>190<li><a href="#creating-an https server">Creating An HTTPS Server</a></li>191<li><a href="#configuration">Configuration</a></li>192<li><a href="#settings">Settings</a></li>193<li><a href="#routing">Routing</a></li>194<li><a href="#passing-route control">Passing Route Control</a></li>195<li><a href="#middleware">Middleware</a></li>196<li><a href="#route-middleware">Route Middleware</a></li>197<li><a href="#http-methods">HTTP Methods</a></li>198<li><a href="#error-handling">Error Handling</a></li>199<li><a href="#route-param pre-conditions">Route Param Pre-conditions</a></li>200<li><a href="#view-rendering">View Rendering</a></li>201<li><a href="#view-partials">View Partials</a></li>202<li><a href="#view-lookup">View Lookup</a></li>203<li><a href="#template-engines">Template Engines</a></li>204<li><a href="#session-support">Session Support</a></li>205<li><a href="#migration-guide">Migration Guide</a></li>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 206why, one step back206<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 207–210why, one step back207<li><a href="#req.header()">header()</a></li>208<li><a href="#req.accepts()">accepts()</a></li>209<li><a href="#req.is()">is()</a></li>210<li><a href="#req.param()">param()</a></li>updated docsTj Holowaychukbefore adoption652e166
line 211why, one step back211<li><a href="#req.get()">get()</a></li>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 212–213why, one step back212<li><a href="#req.flash()">flash()</a></li>213<li><a href="#req.isxmlhttprequest">isXMLHttpRequest</a></li>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 214–215why, one step back214</ul></li>215<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 216–229why, one step back216<li><a href="#res.header()">header()</a></li>217<li><a href="#res.charset">charset</a></li>218<li><a href="#res.contenttype()">contentType()</a></li>219<li><a href="#res.attachment()">attachment()</a></li>220<li><a href="#res.sendfile()">sendfile()</a></li>221<li><a href="#res.download()">download()</a></li>222<li><a href="#res.send()">send()</a></li>223<li><a href="#res.redirect()">redirect()</a></li>224<li><a href="#res.cookie()">cookie()</a></li>225<li><a href="#res.clearcookie()">clearCookie()</a></li>226<li><a href="#res.render()">render()</a></li>227<li><a href="#res.partial()">partial()</a></li>228<li><a href="#res.local()">local()</a></li>229<li><a href="#res.locals()">locals()</a></li>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 230–231why, one step back230</ul></li>231<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 232–241why, one step back232<li><a href="#app.set()">set()</a></li>233<li><a href="#app.enable()">enable()</a></li>234<li><a href="#app.enabled()">enabled()</a></li>235<li><a href="#app.disable()">disable()</a></li>236<li><a href="#app.disabled()">disabled()</a></li>237<li><a href="#app.configure()">configure()</a></li>238<li><a href="#app.redirect()">redirect()</a></li>239<li><a href="#app.error()">error()</a></li>240<li><a href="#app.helpers()">helpers()</a></li>241<li><a href="#app.dynamichelpers()">dynamicHelpers()</a></li>updated docsTj Holowaychukbefore adoption99b49d2
lines 242–243why, one step back242<li><a href="#app.lookup">lookup</a></li>243<li><a href="#app.match">match</a></li>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 244–246why, one step back244<li><a href="#app.mounted()">mounted()</a></li>245<li><a href="#app.register()">register()</a></li>246<li><a href="#app.listen()">listen()</a></li>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 247–259why, one step back247</ul></li>248</ul>249 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 250 <p id="tagline">251 High performance, high class web development for252 <a href="http://nodejs.org">Node.js</a>253 </p>254 <ul id="menu">255 <li><a href="index.html">Home</a></li>256 <li><a href="guide.html">Guide</a></li>257 <li><a href="screencasts.html">Screencasts</a></li>258 <li><a href="applications.html">Applications</a></li>259 </ul>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 260why, one step back260<h3 id="installation">Installation</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 261why, one step back261fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 262–263why, one step back262<pre><code>$ npm install express263</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 264why, one step back264generate docsTj Holowaychukbefore adoptionff7d5ff
lines 265–289why, one step back265<p>or to access the <code>express(1)</code> executable install globally:</p>266267<pre><code>$ npm install -g express268</code></pre>269270<h2>Quick Start</h2>271272<p> The quickest way to get started with express is to utilize the executable <code>express(1)</code> to generate an application as shown below:</p>273274<p> Create the app:</p>275276<pre><code>$ npm install -g express277$ express /tmp/foo && cd /tmp/foo278</code></pre>279280<p> Install dependencies:</p>281282<pre><code>$ npm install -d283</code></pre>284285<p> Start the server:</p>286287<pre><code>$ node app.js288</code></pre>289fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 290why, one step back290<h3 id="creating-a server">Creating A Server</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 291–299why, one step back291292<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>293294<pre><code>var app = require('express').createServer();295296app.get('/', function(req, res){297 res.send('hello world');298});299fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 300–301why, one step back300app.listen(3000);301</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 302why, one step back302fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 303why, one step back303<h3 id="creating-an https server">Creating An HTTPS Server</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 304–305why, one step back304305<p> To initialize a <em>express.HTTPSServer</em> we do the same as above, however wefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 306why, one step back306 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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 307why, one step back307fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 308–309why, one step back308<pre><code> var app = require('express').createServer({ key: ... });309</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 310why, one step back310fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 311why, one step back311<h3 id="configuration">Configuration</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 312–314why, one step back312313<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers314can use the <em>configure()</em> method to setup needs required by the current environment. Whenfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 315why, one step back315<em>configure()</em> is called without an environment name it will be run in <em>every</em> environmentmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 316–323why, one step back316prior to the environment specific callback.</p>317318<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces319in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.320Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,321otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>322323<pre><code>app.configure(function(){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 324–326why, one step back324 app.use(express.methodOverride());325 app.use(express.bodyParser());326 app.use(app.router);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 327–329why, one step back327});328329app.configure('development', function(){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 330–331why, one step back330 app.use(express.static(__dirname + '/public'));331 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 332–335why, one step back332});333334app.configure('production', function(){335 var oneYear = 31557600000;regenerated docsTj Holowaychukbefore adoptiondd7158a
line 336why, one step back336 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 337why, one step back337 app.use(express.errorHandler());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 338–339why, one step back338});339</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 340–355why, one step back340341<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>342343<pre><code> app.configure(function(){344 app.set('views', __dirname + '/views');345 app.set('views');346 // => "/absolute/path/to/views"347348 app.enable('some feature');349 // same as app.set('some feature', true);350351 app.disable('some feature');352 // same as app.set('some feature', false);353354 app.enabled('some feature')355 // => falsefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 356–357why, one step back356 });357</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 358why, one step back358fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 359why, one step back359<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 360why, one step back360fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 361–362why, one step back361<pre><code>$ NODE_ENV=production node app.js362</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 363–365why, one step back363364<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>365fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 366why, one step back366<h3 id="settings">Settings</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 367–369why, one step back367368<p>Express supports the following settings out of the box:</p>369fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 370–374why, one step back370<ul>371<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>372<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>373<li><em>view engine</em> Default view engine name for views rendered without extensions</li>374<li><em>view options</em> An object specifying global view options</li>docsTj Holowaychukbefore adoption3588c1e
lines 375–376why, one step back375<li><em>view cache</em> Enable view caching (enabled in production)</li>376<li><em>case sensitive routes</em> Enable case-sensitive routing</li>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 377why, one step back377</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 378–379why, one step back378379fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 380–381why, one step back380<h3 id="routing">Routing</h3>381migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 382why, one step back382<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 383–384why, one step back383For example we may want to render a user’s account for the path <em>/user/12</em>, this384can be done by defining the route below. The values associated to the named placeholdersmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 385–387why, one step back385are available as <code>req.params</code>.</p>386387<pre><code>app.get('/user/:id', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 388–390why, one step back388 res.send('user ' + req.params.id);389});390</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 391why, one step back391docsTj Holowaychukbefore adoption3588c1e
line 392why, one step back392<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For examplemigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 393–394why, one step back393when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>394fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 395–396why, one step back395<pre><code>\/user\/([^\/]+)\/?396</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 397–398why, one step back397398<p>Regular expression literals may also be passed for complex uses. Since capturefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 399why, one step back399groups 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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 400–402why, one step back400401<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){402 res.send(req.params);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 403–404why, one step back403});404</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 405–414why, one step back405406<p>Curl requests against the previously defined route:</p>407408<pre><code> $ curl http://dev:3000/user409 [null,null]410 $ curl http://dev:3000/users411 [null,null]412 $ curl http://dev:3000/users/1413 ["1",null]414 $ curl http://dev:3000/users/1..15fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 415–416why, one step back415 ["1","15"]416</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 417–450why, one step back417418<p>Below are some route examples, and the associated paths that they419may consume:</p>420421<pre><code> "/user/:id"422 /user/12423424 "/users/:id?"425 /users/5426 /users427428 "/files/*"429 /files/jquery.js430 /files/javascripts/jquery.js431432 "/file/*.*"433 /files/jquery.js434 /files/javascripts/jquery.js435436 "/user/:id/:operation?"437 /user/1438 /user/1/edit439440 "/products.:format"441 /products.json442 /products.xml443444 "/products.:format?"445 /products.json446 /products.xml447 /products448449 "/user/:id.:format?"450 /user/12fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 451–452why, one step back451 /user/12.json452</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 453–464why, one step back453454<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>455456<pre><code>var express = require('express')457 , app = express.createServer();458459app.use(express.bodyParser());460461app.post('/', function(req, res){462 res.send(req.body);463});464fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 465–466why, one step back465app.listen(3000);466</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 467why, one step back467docsTj Holowaychukbefore adoption3588c1e
line 468why, one step back468<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([0-9]+)’</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 469why, one step back469fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 470why, one step back470<h3 id="passing-route control">Passing Route Control</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 471–476why, one step back471472<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,473the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,474and 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>475476<pre><code>app.get('/users/:id?', function(req, res, next){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 477–482why, one step back477 var id = req.params.id;478 if (id) {479 // do something480 } else {481 next();482 }migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 483–485why, one step back483});484485app.get('/users', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 486–488why, one step back486 // do something else487});488</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 489–521why, one step back489490<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>491492<pre><code>var express = require('express')493 , app = express.createServer();494495var users = [{ name: 'tj' }];496497app.all('/user/:id/:op?', function(req, res, next){498 req.user = users[req.params.id];499 if (req.user) {500 next();501 } else {502 next(new Error('cannot find user ' + req.params.id));503 }504});505506app.get('/user/:id', function(req, res){507 res.send('viewing ' + req.user.name);508});509510app.get('/user/:id/edit', function(req, res){511 res.send('editing ' + req.user.name);512});513514app.put('/user/:id', function(req, res){515 res.send('updating ' + req.user.name);516});517518app.get('*', function(req, res){519 res.send('what???', 404);520});521fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 522–523why, one step back522app.listen(3000); 523</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 524why, one step back524fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 525why, one step back525<h3 id="middleware">Middleware</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 526–532why, one step back526527<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be528passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>529530<pre><code> var express = require('express');531532var app = express.createServer(fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 533–536why, one step back533 express.logger()534 , express.bodyParser()535 );536</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 537–539why, one step back537538<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>539generate docsTj Holowaychukbefore adoptionff7d5ff
line 540why, one step back540<pre><code>app.use(express.logger({ format: ':method :url' }));fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 541why, one step back541</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 542why, one step back542fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 543why, one step back543<p>Typically with connect middleware you would <em>require(‘connect’)</em> like so:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 544–546why, one step back544545<pre><code>var connect = require('connect');546app.use(connect.logger());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 547–548why, one step back547app.use(connect.bodyParser());548</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 549–552why, one step back549550<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>551552<pre><code>app.use(express.logger());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 553–554why, one step back553app.use(express.bodyParser());554</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 555why, one step back555docsTj Holowaychukbefore adoption3588c1e
lines 556–583why, one step back556<p>Middleware ordering is important, when Connect receives a request the <em>first</em> middleware we pass to <em>createServer()</em> or <em>use()</em> is executed with three parameters, <em>request</em>, <em>response</em>, and a callback function usually named <em>next</em>. When <em>next()</em> is invoked the second middleware will then have it’s turn and so on. This is important to note because many middleware depend on each other, for example <em>methodOverride()</em> checks <em>req.body.</em>method<em> for the HTTP method override, however </em>bodyParser()<em> parses the request body and populates </em>req.body<em>. Another example of this is cookie parsing and session support, we must first </em>use()<em> </em>cookieParser()<em> followed by </em>session()_.</p>557558<p>Many Express applications may contain the line <em>app.use(app.router)</em>, while this may appear strange, it’s simply the middleware function that contains all defined routes, and performs route lookup based on the current request url and HTTP method. Express allows you to position this middleware, though by default it will be added to the bottom. By positioning the router, we can alter middleware precedence, for example we may want to add error reporting as the <em>last</em> middleware so that any exception passed to <em>next()</em> will be handled by it, or perhaps we want static file serving to have low precedence, allowing our routes to intercept requests to a static file to count downloads etc. This may look a little like below</p>559560<pre><code>app.use(express.logger(...));561app.use(express.bodyParser(...));562app.use(express.cookieParser(...));563app.use(express.session(...));564app.use(app.router);565app.use(express.static(...));566app.use(express.errorHandler(...));567</code></pre>568569<p>First we add <em>logger()</em> so that it may wrap node’s <em>req.end()</em> method, providing us with response-time data. Next the request’s body will be parsed (if any), followed by cookie parsing and session support, meaning <em>req.session</em> will be defined by the time we hit our routes in <em>app.router</em>. If a request such as <em>GET /javascripts/jquery.js</em> is handled by our routes, and we do not call <em>next()</em> then the <em>static()</em> middleware will never see this request, however if were to define a route as shown below, we can record stats, refuse downloads, consume download credits etc.</p>570571<pre><code>var downloads = {};572573app.use(app.router);574app.use(express.static(__dirname + '/public'));575576app.get('/*', function(req, res, next){577 var file = req.params[0];578 downloads[file] = downloads[file] || 0;579 downloads[file]++;580 next();581});582</code></pre>583fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 584why, one step back584<h3 id="route-middleware">Route Middleware</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 585–587why, one step back585586<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>587fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 588why, one step back588<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 589–594why, one step back589590<pre><code>app.get('/user/:id', function(req, res, next){591 loadUser(req.params.id, function(err, user){592 if (err) return next(err);593 res.send('Viewing user ' + user.name);594 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 595–596why, one step back595});596</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 597why, one step back597fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 598why, one step back598<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 599–612why, one step back599600<pre><code>function loadUser(req, res, next) {601 // You would fetch your user from the db602 var user = users[req.params.id];603 if (user) {604 req.user = user;605 next();606 } else {607 next(new Error('Failed to load user ' + req.params.id));608 }609}610611app.get('/user/:id', loadUser, function(req, res){612 res.send('Viewing user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 613–614why, one step back613});614</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 615–625why, one step back615616<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>617618<pre><code>function andRestrictToSelf(req, res, next) {619 req.authenticatedUser.id == req.user.id620 ? next()621 : next(new Error('Unauthorized'));622}623624app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){625 res.send('Editing user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 626–627why, one step back626});627</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 628–640why, one step back628629<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>630631<pre><code>function andRestrictTo(role) {632 return function(req, res, next) {633 req.authenticatedUser.role == role634 ? next()635 : next(new Error('Unauthorized'));636 }637}638639app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){640 res.send('Deleted user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 641–642why, one step back641});642</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 643why, one step back643fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 644why, one step back644<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 645–654why, one step back645646<pre><code>var a = [middleware1, middleware2]647 , b = [middleware3, middleware4]648 , all = [a, b];649650app.get('/foo', a, function(){});651app.get('/bar', a, function(){});652653app.get('/', a, middleware3, middleware4, function(){});654app.get('/', a, b, function(){});fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 655–656why, one step back655app.get('/', all, function(){});656</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 657–659why, one step back657658<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>659docsTj Holowaychukbefore adoption3588c1e
lines 660–661why, one step back660<p>There are times when we may want to “skip” passed remaining route middleware, but continue matching subsequent routes. To do this we invoke <code>next()</code> with the string “route” <code>next('route')</code>. If no remaining routes match the request url then Express will respond with 404 Not Found.</p>661fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 662why, one step back662<h3 id="http-methods">HTTP Methods</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 663–665why, one step back663664<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>665fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 666why, one step back666<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 667–671why, one step back667668<pre><code> <form method="post" action="/">669 <input type="text" name="user[name]" />670 <input type="text" name="user[email]" />671 <input type="submit" value="Submit" />fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 672–673why, one step back672 </form>673</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 674why, one step back674fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 675why, one step back675<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 676why, one step back676fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 677–678why, one step back677<pre><code>app.use(express.bodyParser());678</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 679–684why, one step back679680<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>681682<pre><code>app.post('/', function(req, res){683 console.log(req.body.user);684 res.redirect('back');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 685–686why, one step back685});686</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 687why, one step back687fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 688why, one step back688<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 689–690why, one step back689690<pre><code>app.use(express.bodyParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 691–692why, one step back691app.use(express.methodOverride());692</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 693–705why, one step back693694<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>695696<pre><code><form method="post" action="/">697 <input type="hidden" name="_method" value="put" />698 <input type="text" name="user[name]" />699 <input type="text" name="user[email]" />700 <input type="submit" value="Submit" /> 701</form>702703app.put('/', function(){704 console.log(req.body.user);705 res.redirect('back');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 706–707why, one step back706});707</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 708why, one step back708fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 709why, one step back709<h3 id="error-handling">Error Handling</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 710–720why, one step back710711<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,712or passed to <em>next(err)</em>. Below is an example which serves different pages based on our713ad-hoc <em>NotFound</em> exception:</p>714715<pre><code>function NotFound(msg){716 this.name = 'NotFound';717 Error.call(this, msg);718 Error.captureStackTrace(this, arguments.callee);719}720fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 721why, one step back721NotFound.prototype.__proto__ = Error.prototype;migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 722–728why, one step back722723app.get('/404', function(req, res){724 throw new NotFound;725});726727app.get('/500', function(req, res){728 throw new Error('keyboard cat!');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 729–730why, one step back729});730</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 731–736why, one step back731732<p>We can call <em>app.error()</em> several times as shown below.733Here we check for an instanceof <em>NotFound</em> and show the734404 page, or we pass on to the next error handler.</p>735736<p>Note that these handlers can be defined anywhere, as theyfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 737why, one step back737will be placed below the route handlers on <em>listen()</em>. Thismigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 738–746why, one step back738allows for definition within <em>configure()</em> blocks so we can739handle exceptions in different ways based on the environment.</p>740741<pre><code>app.error(function(err, req, res, next){742 if (err instanceof NotFound) {743 res.render('404.jade');744 } else {745 next(err);746 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 747–748why, one step back747});748</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 749–750why, one step back749750<p>Here we assume all errors as 500 for the simplicity offixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 751why, one step back751this 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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 752–756why, one step back752753<pre><code>app.error(function(err, req, res){754 res.render('500.jade', {755 error: err756 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 757–758why, one step back757});758</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 759–760why, one step back759760<p>Our apps could also utilize the Connect <em>errorHandler</em> middlewarefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 761–762why, one step back761to report on exceptions. For example if we wish to output exceptions762in “development” mode to <em>stderr</em> we can use:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 763why, one step back763fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 764–765why, one step back764<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));765</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 766–769why, one step back766767<p>Also during development we may want fancy html pages to show exceptions768that are passed or thrown, so we can set <em>showStack</em> to true:</p>769fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 770–771why, one step back770<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));771</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 772–775why, one step back772773<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>774is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>775fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 776why, one step back776<h3 id="route-param pre-conditions">Route Param Pre-conditions</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 777–784why, one step back777778<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>779780<pre><code>app.get('/user/:userId', function(req, res, next){781 User.get(req.params.userId, function(err, user){782 if (err) return next(err);783 res.send('user ' + user.name);784 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 785–786why, one step back785}); 786</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 787–796why, one step back787788<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>789790<pre><code>app.param('userId', function(req, res, next, id){791 User.get(id, function(err, user){792 if (err) return next(err);793 if (!user) return next(new Error('failed to find user'));794 req.user = user;795 next();796 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 797–798why, one step back797});798</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 799–803why, one step back799800<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>801802<pre><code>app.get('/user/:userId', function(req, res){803 res.send('user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 804–805why, one step back804});805</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 806why, one step back806fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 807why, one step back807<h3 id="view-rendering">View Rendering</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 808why, one step back808fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 809why, one step back809<p>View filenames take the form “<name>.<engine>”, where <engine> is the namemigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 810why, one step back810of the module that will be required. For example the view <em>layout.ejs</em> willfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 811–812why, one step back811tell 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 behaviour812<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 813–814why, one step back813814<p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 815why, one step back815and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed asmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 816–818why, one step back816the <em>body</em> local variable in <em>layout.jade</em>.</p>817818<pre><code>app.get('/', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 819–821why, one step back819 res.render('index.jade', { title: 'My Site' });820});821</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 822–825why, one step back822823<p>The new <em>view engine</em> setting allows us to specify our default template engine,824so for example when using jade we could set:</p>825fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 826–827why, one step back826<pre><code>app.set('view engine', 'jade');827</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 828–830why, one step back828829<p>Allowing us to render with:</p>830fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 831–832why, one step back831<pre><code>res.render('index');832</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 833–835why, one step back833834<p>vs:</p>835fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 836–837why, one step back836<pre><code>res.render('index.jade');837</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 838–841why, one step back838839<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still840mix and match template engines:</p>841fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 842–843why, one step back842<pre><code>res.render('another-page.ejs');843</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 844–848why, one step back844845<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>846847<pre><code>app.set('view options', {848 layout: falsefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 849–850why, one step back849});850</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 851–853why, one step back851852<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>853fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 854–855why, one step back854<pre><code>res.render('myview.ejs', { layout: true });855</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 856–858why, one step back856857<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>858fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 859–860why, one step back859<pre><code>res.render('page', { layout: 'mylayout' });860</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 861–863why, one step back861862<p>Otherwise we must specify the extension:</p>863fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 864–865why, one step back864<pre><code>res.render('page', { layout: 'mylayout.jade' });865</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 866–868why, one step back866867<p>These paths may also be absolute:</p>868fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 869–870why, one step back869<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });870</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 871–876why, one step back871872<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>873874<pre><code>app.set('view options', {875 open: '{{',876 close: '}}'fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 877–878why, one step back877});878</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 879why, one step back879fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 880why, one step back880<h3 id="view-partials">View Partials</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 881why, one step back881fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 882why, one step back882<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 iteratingregenerated docsTj Holowaychukbefore adoptiondd7158a
line 883why, one step back883in a view to display comments, we could use partial collection:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 884why, one step back884fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 885–886why, one step back885<pre><code>partial('comment', { collection: comments });886</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 887why, one step back887regenerated docsTj Holowaychukbefore adoptiondd7158a
line 888why, one step back888<p>If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 889why, one step back889fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 890–891why, one step back890<pre><code>partial('comment', comments);891</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 892why, one step back892fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 893why, one step back893<p>When using the partial collection support a few “magic” locals are providedmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 894–895why, one step back894for free:</p>895fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 896–901why, one step back896<ul>897<li><em>firstInCollection</em> true if this is the first object</li>898<li><em>indexInCollection</em> index of the object in the collection</li>899<li><em>lastInCollection</em> true if this is the last object</li>900<li><em>collectionLength</em> length of the collection</li>901</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 902–903why, one step back902903fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 904–905why, one step back904<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>905migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 906–909why, one step back906<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>907908<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>909fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 910why, one step back910<h3 id="view-lookup">View Lookup</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 911why, one step back911fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 912why, one step back912<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 913why, one step back913fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 914why, one step back914<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 915why, one step back915fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 916why, one step back916<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 917why, one step back917fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 918why, one step back918<h3 id="template-engines">Template Engines</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 919–921why, one step back919920<p>Below are a few template engines commonly used with Express:</p>921fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 922–928why, one step back922<ul>923<li><a href="http://github.com/visionmedia/haml.js">Haml</a> haml implementation</li>924<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>925<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>926<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>927<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>928</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 929–930why, one step back929930fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 931why, one step back931<h3 id="session-support">Session Support</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 932why, one step back932fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 933–934why, one step back933<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>934migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 935why, one step back935<pre><code>app.use(express.cookieParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 936–937why, one step back936app.use(express.session({ secret: "keyboard cat" }));937</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 938–940why, one step back938939<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>940Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4
line 941why, one step back941<pre><code>var RedisStore = require('connect-redis')(express);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 942why, one step back942app.use(express.cookieParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 943–944why, one step back943app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));944</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 945–947why, one step back945946<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>947Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4
line 948why, one step back948<pre><code>var RedisStore = require('connect-redis')(express);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 949–968why, one step back949app.use(express.bodyParser());950app.use(express.cookieParser());951app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));952953app.post('/add-to-cart', function(req, res){954 // Perhaps we posted several items with a form955 // (use the bodyParser() middleware for this)956 var items = req.body.items;957 req.session.items = items;958 res.redirect('back');959});960961app.get('/add-to-cart', function(req, res){962 // When redirected back to GET /add-to-cart963 // we could check req.session.items && req.session.items.length964 // to print out a message965 if (req.session.items && req.session.items.length) {966 req.flash('info', 'You have %s items in your cart', req.session.items.length);967 }968 res.render('shopping-cart');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 969–970why, one step back969});970</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 971–973why, one step back971972<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>973fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 974why, one step back974<h3 id="migration-guide">Migration Guide</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 975–977why, one step back975976<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>977fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 978why, one step back978<h3 id="req.header()">req.header(key[, defaultValue])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 979–983why, one step back979980<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>981982<pre><code>req.header('Host');983req.header('host');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 984–985why, one step back984req.header('Accept', '*/*');985</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 986–994why, one step back986987<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>988989<pre><code>// sent Referrer: http://google.com990991req.header('Referer');992// => "http://google.com"993994req.header('Referrer');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 995–996why, one step back995// => "http://google.com"996</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 997why, one step back997fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 998why, one step back998<h3 id="req.accepts()">req.accepts(type)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 999–1003why, one step back9991000<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>10011002<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise1003the given <em>type</em> is matched by an exact match, and then subtypes. Youfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1004–1005why, one step back1004may pass the subtype such as “html” which is then converted internally1005to “text/html” using the mime lookup table.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1006–1019why, one step back10061007<pre><code>// Accept: text/html1008req.accepts('html');1009// => true10101011// Accept: text/*; application/json1012req.accepts('html');1013req.accepts('text/html');1014req.accepts('text/plain');1015req.accepts('application/json');1016// => true10171018req.accepts('image/png');1019req.accepts('png');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1020–1021why, one step back1020// => false1021</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1022why, one step back1022fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1023why, one step back1023<h3 id="req.is()">req.is(type)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1024–1038why, one step back10241025<p>Check if the incoming request contains the <em>Content-Type</em>1026header field, and it contains the give mime <em>type</em>.</p>10271028<pre><code> // With Content-Type: text/html; charset=utf-81029 req.is('html');1030 req.is('text/html');1031 // => true10321033 // When Content-Type is application/json1034 req.is('json');1035 req.is('application/json');1036 // => true10371038 req.is('html');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1039–1040why, one step back1039 // => false1040</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1041–1043why, one step back10411042<p>Ad-hoc callbacks can also be registered with Express, to perform1043assertions again the request, for example if we need an expressivefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1044why, one step back1044way to check if our incoming request is an image, we can register <em>“an image”</em>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1045–1048why, one step back1045callback:</p>10461047<pre><code> app.is('an image', function(req){1048 return 0 == req.headers['content-type'].indexOf('image');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1049–1050why, one step back1049 });1050</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1051–1052why, one step back10511052<p>Now within our route callbacks, we can use to to assert content typesfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1053why, one step back1053such as <em>“image/jpeg”</em>, <em>“image/png”</em>, etc.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1054–1060why, one step back10541055<pre><code> app.post('/image/upload', function(req, res, next){1056 if (req.is('an image')) {1057 // do something1058 } else {1059 next();1060 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1061–1062why, one step back1061 });1062</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1063–1066why, one step back10631064<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you1065can perform any request assertion you wish.</p>1066fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1067why, one step back1067<p>Wildcard matches can also be made, simplifying our example above for <em>“an image”</em>, by asserting the <em>subtype</em> only:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1068why, one step back1068fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1069–1070why, one step back1069<pre><code>req.is('image/*');1070</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1071why, one step back1071fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1072why, one step back1072<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1073why, one step back1073fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1074–1075why, one step back1074<pre><code>req.is('*/json');1075</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1076why, one step back1076fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1077why, one step back1077<h3 id="req.param()">req.param(name[, default])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1078–1080why, one step back10781079<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>1080fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1081–1085why, one step back1081<ul>1082<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>1083<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1084<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1085</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1086why, one step back1086fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1087why, one step back1087migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1088–1090why, one step back1088<p>To utilize urlencoded request bodies, <em>req.body</em>1089should be an object. This can be done by using1090the _express.bodyParser middleware.</p>updated docsTj Holowaychukbefore adoption652e166
lines 1091–1102why, one step back10911092<h3 id="req.get()">req.get(field, param)</h3>10931094<p> Get <em>field</em>’s <em>param</em> value, defaulting to ‘’ when the <em>param</em>1095 or <em>field</em> is not present.</p>10961097<pre><code> req.get('content-disposition', 'filename');1098 // => "something.png"10991100 req.get('Content-Type', 'boundary');1101 // => "--foo-bar-baz"1102</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1103why, one step back1103fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1104why, one step back1104<h3 id="req.flash()">req.flash(type[, msg])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1105–1119why, one step back11051106<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>11071108<pre><code>req.flash('info', 'email sent');1109req.flash('error', 'email delivery failed');1110req.flash('info', 'email re-sent');1111// => 211121113req.flash('info');1114// => ['email sent', 'email re-sent']11151116req.flash('info');1117// => []11181119req.flash();fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1120–1121why, one step back1120// => { error: ['email delivery failed'], info: [] }1121</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1122–1124why, one step back11221123<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>1124fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1125–1126why, one step back1125<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1126</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1127why, one step back1127fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1128why, one step back1128<h3 id="req.isxmlhttprequest">req.isXMLHttpRequest</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1129–1133why, one step back11291130<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1131to see if it was issued by an <em>XMLHttpRequest</em>:</p>11321133<pre><code>req.xhrfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1134–1135why, one step back1134req.isXMLHttpRequest1135</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1136why, one step back1136fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1137why, one step back1137<h3 id="res.header()">res.header(key[, val])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1138–1147why, one step back11381139<p>Get or set the response header <em>key</em>.</p>11401141<pre><code>res.header('Content-Length');1142// => undefined11431144res.header('Content-Length', 123);1145// => 12311461147res.header('Content-Length');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1148–1149why, one step back1148// => 1231149</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1150why, one step back1150fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1151why, one step back1151<h3 id="res.charset">res.charset</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1152why, one step back1152fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1153why, one step back1153<p>Sets the charset for subsequent <code>Content-Type</code> header fields. For example <code>res.send()</code> and <code>res.render()</code> default to “utf8”, so we may explicitly set the charset before rendering a template:</p>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1154–1155why, one step back11541155<pre><code>res.charset = 'ISO-8859-1';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1156–1157why, one step back1156res.render('users');1157</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1158–1161why, one step back11581159<p>or before responding with <code>res.send()</code>:</p>11601161<pre><code>res.charset = 'ISO-8859-1';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1162–1163why, one step back1162res.send(str);1163</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1164why, one step back1164fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1165why, one step back1165<p>or with node’s <code>res.end()</code>:</p>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1166–1168why, one step back11661167<pre><code>res.charset = 'ISO-8859-1';1168res.header('Content-Type', 'text/plain');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1169–1170why, one step back1169res.end(str);1170</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1171why, one step back1171fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1172why, one step back1172<h3 id="res.contenttype()">res.contentType(type)</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1173why, one step back1173migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1174–1177why, one step back1174<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>11751176<pre><code> var filename = 'path/to/image.png';1177 res.contentType(filename);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1178–1179why, one step back1178 // Content-Type is now "image/png"1179</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1180why, one step back1180regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1181why, one step back1181<p>A literal <em>Content-Type</em> works as well:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1182why, one step back1182fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1183–1184why, one step back1183<pre><code> res.contentType('application/json');1184</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1185–1187why, one step back11851186<p>Or simply the extension without leading <code>.</code>:</p>1187fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1188–1189why, one step back1188<pre><code> res.contentType('json');1189</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1190why, one step back1190fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1191why, one step back1191<h3 id="res.attachment()">res.attachment([filename])</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1192why, one step back1192fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1193why, one step back1193<p>Sets the <em>Content-Disposition</em> response header to “attachment”, with optional <em>filename</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1194why, one step back1194fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1195–1196why, one step back1195<pre><code> res.attachment('path/to/my/image.png');1196</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1197why, one step back1197fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1198why, one step back1198<h3 id="res.sendfile()">res.sendfile(path[, options[, callback]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1199why, one step back1199fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1200why, one step back1200<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1201why, one step back1201fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1202–1203why, one step back1202<pre><code>res.sendfile('path/to/my.file');1203</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1204–1213why, one step back12041205<p>This method accepts an optional callback which is called when1206an 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>12071208<pre><code>res.sendfile(path, function(err){1209 if (err) {1210 next(err);1211 } else {1212 console.log('transferred %s', path);1213 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1214–1215why, one step back1214});1215</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1216–1220why, one step back12161217<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>12181219<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1220 // handlefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1221–1222why, one step back1221});1222</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1223why, one step back1223docsTj Holowaychukbefore adoption3588c1e
line 1224why, one step back1224<h3 id="res.download()">res.download(file[, filename[, callback[, callback2]]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1225–1228why, one step back12251226<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>12271228<pre><code>res.download('path/to/image.png');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1229–1230why, one step back1229res.download('path/to/image.png', 'foo.png');1230</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1231–1234why, one step back12311232<p>This is equivalent to:</p>12331234<pre><code>res.attachment(file);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1235–1236why, one step back1235res.sendfile(file);1236</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1237why, one step back1237docsTj Holowaychukbefore adoption3588c1e
line 1238why, one step back1238<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>. Within this callback you may still respond, as the header has not been sent.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1239–1241why, one step back12391240<pre><code>res.download(path, 'expenses.doc', function(err){1241 // handlefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1242–1243why, one step back1242});1243</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1244why, one step back1244docsTj Holowaychukbefore adoption3588c1e
lines 1245–1253why, one step back1245<p>An optional second callback, <em>callback2</em> may be given to allow you to act on connection related errors, however you should not attempt to respond.</p>12461247<pre><code>res.download(path, function(err){1248 // error or finished1249}, function(err){1250 // connection related error1251});1252</code></pre>1253fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1254why, one step back1254<h3 id="res.send()">res.send(body|status[, headers|status[, status]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1255–1264why, one step back12551256<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1257objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>12581259<pre><code> res.send(); // 2041260 res.send(new Buffer('wahoo'));1261 res.send({ some: 'json' });1262 res.send('<p>some html</p>');1263 res.send('Sorry, cant find that', 404);1264 res.send('text', { 'Content-Type': 'text/plain' }, 201);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1265–1266why, one step back1265 res.send(404);1266</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1267–1271why, one step back12671268<p>By default the <em>Content-Type</em> response header is set, however if explicitly1269assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1270it will not be set again.</p>1271fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1272why, one step back1272<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1273why, one step back1273fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1274why, one step back1274<h3 id="res.redirect()">res.redirect(url[, status])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1275–1281why, one step back12751276<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>12771278<pre><code>res.redirect('/', 301);1279res.redirect('/account');1280res.redirect('http://google.com');1281res.redirect('home');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1282–1283why, one step back1282res.redirect('back');1283</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1284why, one step back1284fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1285why, one step back1285<p>Express supports “redirect mapping”, which by default provides <em>home</em>, and <em>back</em>.migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1286why, one step back1286The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizesfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1287why, one step back1287the “home” setting and defaults to “/”.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1288why, one step back1288fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1289why, one step back1289<h3 id="res.cookie()">res.cookie(name, val[, options])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1290–1293why, one step back12901291<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>12921293<pre><code>// "Remember me" for 15 minutes fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1294–1295why, one step back1294res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1295</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1296–1298why, one step back12961297<p>The <em>maxAge</em> property may be used to set <em>expires</em> relative to <em>Date.now()</em> in milliseconds, so our example above can now become:</p>1298fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1299–1300why, one step back1299<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });1300</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1301why, one step back1301updated docsTj Holowaychukbefore adoption99b49d2
line 1302why, one step back1302<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieParser</em> middleware, which provides the <em>req.cookies</em> object:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1303–1307why, one step back13031304<pre><code>app.use(express.cookieParser());13051306app.get('/', function(req, res){1307 // use req.cookies.remembermefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1308–1309why, one step back1308});1309</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1310why, one step back1310docsTj Holowaychukbefore adoption3588c1e
line 1311why, one step back1311<h3 id="res.clearcookie()">res.clearCookie(name[, options])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1312why, one step back1312fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1313why, one step back1313<p>Clear cookie <em>name</em> by setting “expires” far in the past.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1314why, one step back1314fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1315–1316why, one step back1315<pre><code>res.clearCookie('rememberme');1316</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1317why, one step back1317fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1318why, one step back1318<h3 id="res.render()">res.render(view[, options[, fn]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1319–1323why, one step back13191320<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1321When a callback function is given a response will <em>not</em> be made1322automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>1323fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1324why, one step back1324<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1325–1326why, one step back13251326<pre><code>var user = { name: 'tj' };fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1327–1328why, one step back1327res.render('index', { layout: false, user: user });1328</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1329why, one step back1329fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1330why, one step back1330<h3 id="res.partial()">res.partial(view[, options])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1331–1334why, one step back13311332<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1333to the view as a local variable.</p>1334fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1335–1337why, one step back1335<ul>1336<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1337<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1338why, one step back1338fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1339–1349why, one step back1339<ul>1340<li>as: ‘something’ will add the <em>something</em> local variable</li>1341<li>as: this will use the collection value as the template context</li>1342<li>as: global will merge the collection value’s properties with <em>locals</em></li>1343</ul>1344</li>1345<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1346For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1347</ul>13481349migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1350–1357why, one step back1350<p>The following are equivalent, and the name of collection value when passed1351to the partial will be <em>movie</em> as derived from the name.</p>13521353<pre><code>partial('theatre/movie.jade', { collection: movies });1354partial('theatre/movie.jade', movies);1355partial('movie.jade', { collection: movies });1356partial('movie.jade', movies);1357partial('movie', movies);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1358–1359why, one step back1358// In view: movie.director1359</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1360why, one step back1360fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1361why, one step back1361<p>To change the local from <em>movie</em> to <em>video</em> we can use the “as” option:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1362–1363why, one step back13621363<pre><code>partial('movie', { collection: movies, as: 'video' });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1364–1365why, one step back1364// In view: video.director1365</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1366–1370why, one step back13661367<p>Also we can make our movie the value of <em>this</em> within our view so that instead1368of <em>movie.director</em> we could use <em>this.director</em>.</p>13691370<pre><code>partial('movie', { collection: movies, as: this });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1371–1372why, one step back1371// In view: this.director1372</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1373why, one step back1373fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1374why, one step back1374<p>Another alternative is to “expand” the properties of the collection item intomigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1375–1377why, one step back1375pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>13761377<pre><code>partial('movie', { collection: movies, as: global });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1378–1379why, one step back1378// In view: director1379</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1380–1392why, one step back13801381<p>This same logic applies to a single partial object usage:</p>13821383<pre><code>partial('movie', { object: movie, as: this });1384// In view: this.director13851386partial('movie', { object: movie, as: global });1387// In view: director13881389partial('movie', { object: movie, as: 'video' });1390// In view: video.director13911392partial('movie', { object: movie });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1393–1394why, one step back1393// In view: movie.director1394</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1395why, one step back1395fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1396why, one step back1396<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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1397why, one step back1397regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1398–1399why, one step back1398<pre><code>var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1399partial('movie', movie)fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1400–1401why, one step back1400// => In view: movie.director1401</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1402why, one step back1402fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1403why, one step back1403<p>The exception of this, is when a “plain” object, aka “{}” or “new Object” is passed, which is considered an object with local variable. For example some may expect a “movie” local with the following, however since it is a plain object “director” and “title” are simply locals:</p>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1404–1405why, one step back14041405<pre><code>var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1406–1407why, one step back1406partial('movie', movie)1407</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1408–1412why, one step back14081409<p>For cases like this where passing a plain object is desired, simply assign it to a key, or use the <code>object</code> key which will use the filename-derived variable name. The examples below are equivalent:</p>14101411<pre><code> partial('movie', { locals: { movie: movie }})1412 partial('movie', { movie: movie })fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1413–1414why, one step back1413 partial('movie', { object: movie })1414</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1415why, one step back1415migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1416–1428why, one step back1416<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>14171418<pre><code>app.get('/users', function(req, res){1419 if (req.xhr) {1420 // respond with the each user in the collection1421 // passed to the "user" view1422 res.partial('user', users);1423 } else {1424 // respond with layout, and users page1425 // which internally does partial('user', users)1426 // along with other UI1427 res.render('users', { users: users });1428 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1429–1430why, one step back1429});1430</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1431why, one step back1431fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1432why, one step back1432<h3 id="res.local()">res.local(name[, val])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1433–1446why, one step back14331434<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>14351436<pre><code> app.all('/movie/:id', function(req, res, next){1437 Movie.get(req.params.id, function(err, movie){1438 // Assigns res.locals.movie = movie1439 res.local('movie', movie);1440 });1441 });14421443 app.get('/movie/:id', function(req, res){1444 // movie is already a local, however we1445 // can pass more if we wish1446 res.render('movie', { displayReviews: true });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1447–1448why, one step back1447 });1448</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1449why, one step back1449fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1450why, one step back1450<h3 id="res.locals()">res.locals(obj)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1451why, one step back1451regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1452–1456why, one step back1452<p> Assign several locals with the given <em>obj</em>. The following are equivalent:</p>14531454<pre><code> res.local('foo', bar);1455 res.local('bar', baz);1456fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1457–1458why, one step back1457 res.locals({ foo: bar, bar, baz });1458</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1459why, one step back1459fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1460why, one step back1460<h3 id="app.set()">app.set(name[, val])</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1461why, one step back1461migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1462–1466why, one step back1462<p>Apply an application level setting <em>name</em> to <em>val</em>, or1463get the value of <em>name</em> when <em>val</em> is not present:</p>14641465<pre><code>app.set('views', __dirname + '/views');1466app.set('views');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1467–1468why, one step back1467// => ...path...1468</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1469–1472why, one step back14691470<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>14711472<pre><code>app.settings.viewsfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1473–1474why, one step back1473// => ...path...1474</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1475why, one step back1475fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1476why, one step back1476<h3 id="app.enable()">app.enable(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1477–1484why, one step back14771478<p>Enable the given setting <em>name</em>:</p>14791480<pre><code>app.enable('some arbitrary setting');1481app.set('some arbitrary setting');1482// => true14831484app.enabled('some arbitrary setting');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1485–1486why, one step back1485// => true1486</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1487why, one step back1487fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1488why, one step back1488<h3 id="app.enabled()">app.enabled(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1489–1496why, one step back14891490<p>Check if setting <em>name</em> is enabled:</p>14911492<pre><code>app.enabled('view cache');1493// => false14941495app.enable('view cache');1496app.enabled('view cache');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1497–1498why, one step back1497// => true1498</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1499why, one step back1499fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1500why, one step back1500<h3 id="app.disable()">app.disable(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1501–1508why, one step back15011502<p>Disable the given setting <em>name</em>:</p>15031504<pre><code>app.disable('some setting');1505app.set('some setting');1506// => false15071508app.disabled('some setting');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1509–1510why, one step back1509// => false1510</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1511why, one step back1511fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1512why, one step back1512<h3 id="app.disabled()">app.disabled(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1513–1522why, one step back15131514<p>Check if setting <em>name</em> is disabled:</p>15151516<pre><code>app.enable('view cache');15171518app.disabled('view cache');1519// => false15201521app.disable('view cache');1522app.disabled('view cache');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1523–1524why, one step back1523// => true1524</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1525why, one step back1525fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1526why, one step back1526<h3 id="app.configure()">app.configure(env|function[, function])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1527–1535why, one step back15271528<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>15291530<pre><code>app.configure(function(){1531 // executed for each env1532});15331534app.configure('development', function(){1535 // executed for 'development' onlyfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1536–1537why, one step back1536});1537</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1538why, one step back1538fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1539why, one step back1539<h3 id="app.redirect()">app.redirect(name, val)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1540–1542why, one step back15401541<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>1542fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1543–1544why, one step back1543<pre><code>app.redirect('google', 'http://google.com');1544</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1545–1547why, one step back15451546<p>Now in a route we may call:</p>1547fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1548why, one step back1548<p> res.redirect(‘google’);</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1549–1553why, one step back15491550<p>We may also map dynamic redirects:</p>15511552<pre><code>app.redirect('comments', function(req, res){1553 return '/post/' + req.params.id + '/comments';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1554–1555why, one step back1554});1555</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1556–1562why, one step back15561557<p>So now we may do the following, and the redirect will dynamically adjust to1558the context of the request. If we called this route with <em>GET /post/12</em> our1559redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>15601561<pre><code>app.get('/post/:id', function(req, res){1562 res.redirect('comments');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1563–1564why, one step back1563});1564</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1565–1567why, one step back15651566<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>1567fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1568–1569why, one step back1568<pre><code>res.redirect('/posts');1569</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1570why, one step back1570fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1571why, one step back1571<h3 id="app.error()">app.error(function)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1572–1578why, one step back15721573<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1574Note that we may set several error handlers by making several calls to this method, however the handler1575should call <em>next(err)</em> if it does not wish to deal with the exception:</p>15761577<pre><code>app.error(function(err, req, res, next){1578 res.send(err.message, 500);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1579–1580why, one step back1579});1580</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1581why, one step back1581fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1582why, one step back1582<h3 id="app.helpers()">app.helpers(obj)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1583–1585why, one step back15831584<p>Registers static view helpers.</p>1585updated docsTj Holowaychukbefore adoption99b49d2
lines 1586–1590why, one step back1586<pre><code>app.helpers({1587 name: function(first, last){ return first + ', ' + last }1588 , firstName: 'tj'1589 , lastName: 'holowaychuk'1590});fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1591–1592why, one step back1591</code></pre>1592migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1593–1595why, one step back1593<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1594as well as the <em>name()</em> function exposed.</p>1595fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1596–1597why, one step back1596<pre><code><%= name(firstName, lastName) %>1597</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1598why, one step back1598updated docsTj Holowaychukbefore adoption99b49d2
lines 1599–1602why, one step back1599<p>Express also provides a few locals by default:</p>16001601<pre><code>- `settings` the app's settings object1602- `filename` the view's filenamedocsTj Holowaychukbefore adoption3588c1e
line 1603why, one step back1603- `layout(path)` specify the layout from within a viewupdated docsTj Holowaychukbefore adoption99b49d2
lines 1604–1607why, one step back1604</code></pre>16051606<p>This method is aliased as <em>app.locals()</em>.</p>1607fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1608why, one step back1608<h3 id="app.dynamichelpers()">app.dynamicHelpers(obj)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1609–1618why, one step back16091610<p>Registers dynamic view helpers. Dynamic view helpers1611are simply functions which accept <em>req</em>, <em>res</em>, and are1612evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1613becomes the local variable it is associated with.</p>16141615<pre><code>app.dynamicHelpers({1616 session: function(req, res){1617 return req.session;1618 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1619–1620why, one step back1619});1620</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1621–1623why, one step back16211622<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>1623fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1624why, one step back1624<pre><code><%= session.name %>updated docsTj Holowaychukbefore adoption99b49d2
lines 1625–1728why, one step back1625</code></pre>16261627<h3 id="app.lookup">app.lookup</h3>16281629<p> The <em>app.lookup</em> http methods returns an array of callback functions1630 associated with the given <em>path</em>.</p>16311632<p> Suppose we define the following routes:</p>16331634<pre><code> app.get('/user/:id', function(){});1635 app.put('/user/:id', function(){});1636 app.get('/user/:id/:op?', function(){});1637</code></pre>16381639<p> We can utilize this lookup functionality to check which routes1640 have been defined, which can be extremely useful for higher level1641 frameworks built on Express.</p>16421643<pre><code> app.lookup.get('/user/:id');1644 // => [Function]16451646 app.lookup.get('/user/:id/:op?');1647 // => [Function]16481649 app.lookup.put('/user/:id');1650 // => [Function]16511652 app.lookup.all('/user/:id');1653 // => [Function, Function]16541655 app.lookup.all('/hey');1656 // => []1657</code></pre>16581659<p> To alias <em>app.lookup.VERB()</em>, we can simply invoke <em>app.VERB()</em>1660 without a callback, as a shortcut, for example the following are1661 equivalent:</p>16621663<pre><code> app.lookup.get('/user');1664 app.get('/user');1665</code></pre>16661667<p> Each function returned has the following properties:</p>16681669<pre><code> var fn = app.get('/user/:id/:op?')[0];16701671 fn.regexp1672 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i16731674 fn.keys1675 // => ['id', 'op']16761677 fn.path1678 // => '/user/:id/:op?'16791680 fn.method1681 // => 'GET'1682</code></pre>16831684<h3 id="app.match">app.match</h3>16851686<p> The <em>app.match</em> http methods return an array of callback functions1687 which match the given <em>url</em>, which may include a query string etc. This1688 is useful when you want reflect on which routes have the opportunity to1689 respond.</p>16901691<p> Suppose we define the following routes:</p>16921693<pre><code> app.get('/user/:id', function(){});1694 app.put('/user/:id', function(){});1695 app.get('/user/:id/:op?', function(){});1696</code></pre>16971698<p> Our match against <strong>GET</strong> will return two functions, since the <em>:op</em>1699 in our second route is optional.</p>17001701<pre><code> app.match.get('/user/1');1702 // => [Function, Function]1703</code></pre>17041705<p> This second call returns only the callback for <em>/user/:id/:op?</em>.</p>17061707<pre><code> app.match.get('/user/23/edit');1708 // => [Function]1709</code></pre>17101711<p> We can also use <em>all()</em> to disregard the http method:</p>17121713<pre><code> app.match.all('/user/20');1714 // => [Function, Function, Function]1715</code></pre>17161717<p> Each function matched has the following properties:</p>17181719<pre><code> var fn = app.match.get('/user/23/edit')[0];17201721 fn.keys1722 // => ['id', 'op']17231724 fn.params1725 // => { id: '23', op: 'edit' }17261727 fn.method1728 // => 'GET'fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1729why, one step back1729</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1730why, one step back1730fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1731why, one step back1731<h3 id="app.mounted()">app.mounted(fn)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1732–1742why, one step back17321733<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>17341735<pre><code>var app = express.createServer(),1736 blog = express.createServer();17371738blog.mounted(function(parent){1739 // parent is app1740 // "this" is blog1741});1742fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1743–1744why, one step back1743app.use(blog);1744</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1745why, one step back1745fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1746why, one step back1746<h3 id="app.register()">app.register(ext, exports)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1747–1748why, one step back17471748<p>Register the given template engine <em>exports</em>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1749why, one step back1749as <em>ext</em>. For example we may wish to map “.html”migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1750–1751why, one step back1750files to jade:</p>1751fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1752–1753why, one step back1752<pre><code> app.register('.html', require('jade'));1753</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1754–1756why, one step back17541755<p>This is also useful for libraries that may not1756match extensions correctly. For example my haml.jsfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1757–1758why, one step back1757library is installed from npm as “hamljs” so instead1758of layout.hamljs, we can register the engine as “.haml”:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1759why, one step back1759fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1760–1761why, one step back1760<pre><code> app.register('.haml', require('haml-js'));1761</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1762–1766why, one step back17621763<p>For engines that do not comply with the Express1764specification, we can also wrap their api this way. Below1765we map <em>.md</em> to render markdown files, rendering the html once1766since it will not change on subsequent calls, and support local substitutionfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1767why, one step back1767in the form of “{name}”.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1768–1777why, one step back17681769<pre><code> app.register('.md', {1770 compile: function(str, options){1771 var html = md.toHTML(str);1772 return function(locals){1773 return html.replace(/\{([^}]+)\}/g, function(_, name){1774 return locals[name];1775 });1776 };1777 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1778–1779why, one step back1778 });1779</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1780why, one step back1780fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1781why, one step back1781<h3 id="app.listen()">app.listen([port[, host]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1782–1783why, one step back17821783<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted allfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1784why, one step back1784connections will be accepted via <em>INADDR_ANY</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1785–1787why, one step back17851786<pre><code>app.listen();1787app.listen(3000);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1788–1789why, one step back1788app.listen(3000, 'n.n.n.n');1789</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1790–1792why, one step back17901791<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>1792fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1793–1794why, one step back1793<pre><code>app.listen('/tmp/express.sock');1794</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1795–1804why, one step back17951796<p>Then try it out:</p>17971798<pre><code>$ telnet /tmp/express.sock1799GET / HTTP/1.118001801HTTP/1.1 200 OK1802Content-Type: text/plain1803Content-Length: 111804fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1805–1806why, one step back1805Hello World1806</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1807–1810why, one step back1807 </div>1808 </div>1809 </body>1810</html>