guide.html
This file
Path
docs/guide.html
1,737 lines · 59.5 KiB · HTML
Last changed by
updated docsTj Holowaychukbefore adoption99b49d2
History of this fileTake it
The walk stopped after 200 commits: lines older than 60daf0d point at it.
Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
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 docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 182–199why, one step back182<li><a href="#installation">Installation</a></li>183<li><a href="#creating-a server">Creating A Server</a></li>184<li><a href="#creating-an https server">Creating An HTTPS Server</a></li>185<li><a href="#configuration">Configuration</a></li>186<li><a href="#settings">Settings</a></li>187<li><a href="#routing">Routing</a></li>188<li><a href="#passing-route control">Passing Route Control</a></li>189<li><a href="#middleware">Middleware</a></li>190<li><a href="#route-middleware">Route Middleware</a></li>191<li><a href="#http-methods">HTTP Methods</a></li>192<li><a href="#error-handling">Error Handling</a></li>193<li><a href="#route-param pre-conditions">Route Param Pre-conditions</a></li>194<li><a href="#view-rendering">View Rendering</a></li>195<li><a href="#view-partials">View Partials</a></li>196<li><a href="#view-lookup">View Lookup</a></li>197<li><a href="#template-engines">Template Engines</a></li>198<li><a href="#session-support">Session Support</a></li>199<li><a href="#migration-guide">Migration Guide</a></li>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 200why, one step back200<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 201–206why, one step back201<li><a href="#req.header()">header()</a></li>202<li><a href="#req.accepts()">accepts()</a></li>203<li><a href="#req.is()">is()</a></li>204<li><a href="#req.param()">param()</a></li>205<li><a href="#req.flash()">flash()</a></li>206<li><a href="#req.isxmlhttprequest">isXMLHttpRequest</a></li>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 207–208why, one step back207</ul></li>208<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 209–222why, one step back209<li><a href="#res.header()">header()</a></li>210<li><a href="#res.charset">charset</a></li>211<li><a href="#res.contenttype()">contentType()</a></li>212<li><a href="#res.attachment()">attachment()</a></li>213<li><a href="#res.sendfile()">sendfile()</a></li>214<li><a href="#res.download()">download()</a></li>215<li><a href="#res.send()">send()</a></li>216<li><a href="#res.redirect()">redirect()</a></li>217<li><a href="#res.cookie()">cookie()</a></li>218<li><a href="#res.clearcookie()">clearCookie()</a></li>219<li><a href="#res.render()">render()</a></li>220<li><a href="#res.partial()">partial()</a></li>221<li><a href="#res.local()">local()</a></li>222<li><a href="#res.locals()">locals()</a></li>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 223–224why, one step back223</ul></li>224<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 225–234why, one step back225<li><a href="#app.set()">set()</a></li>226<li><a href="#app.enable()">enable()</a></li>227<li><a href="#app.enabled()">enabled()</a></li>228<li><a href="#app.disable()">disable()</a></li>229<li><a href="#app.disabled()">disabled()</a></li>230<li><a href="#app.configure()">configure()</a></li>231<li><a href="#app.redirect()">redirect()</a></li>232<li><a href="#app.error()">error()</a></li>233<li><a href="#app.helpers()">helpers()</a></li>234<li><a href="#app.dynamichelpers()">dynamicHelpers()</a></li>updated docsTj Holowaychukbefore adoption99b49d2
lines 235–236why, one step back235<li><a href="#app.lookup">lookup</a></li>236<li><a href="#app.match">match</a></li>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 237–239why, one step back237<li><a href="#app.mounted()">mounted()</a></li>238<li><a href="#app.register()">register()</a></li>239<li><a href="#app.listen()">listen()</a></li>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 240–252why, one step back240</ul></li>241</ul>242 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 243 <p id="tagline">244 High performance, high class web development for245 <a href="http://nodejs.org">Node.js</a>246 </p>247 <ul id="menu">248 <li><a href="index.html">Home</a></li>249 <li><a href="guide.html">Guide</a></li>250 <li><a href="screencasts.html">Screencasts</a></li>251 <li><a href="applications.html">Applications</a></li>252 </ul>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 253why, one step back253<h3 id="installation">Installation</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 254why, one step back254fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 255–256why, one step back255<pre><code>$ npm install express256</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 257why, one step back257fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 258why, one step back258<h3 id="creating-a server">Creating A Server</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 259–267why, one step back259260<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>261262<pre><code>var app = require('express').createServer();263264app.get('/', function(req, res){265 res.send('hello world');266});267fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 268–269why, one step back268app.listen(3000);269</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 270why, one step back270fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 271why, one step back271<h3 id="creating-an https server">Creating An HTTPS Server</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 272–273why, one step back272273<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 274why, one step back274 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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 275why, one step back275fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 276–277why, one step back276<pre><code> var app = require('express').createServer({ key: ... });277</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 278why, one step back278fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 279why, one step back279<h3 id="configuration">Configuration</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 280–282why, one step back280281<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers282can 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 283why, one step back283<em>configure()</em> is called without an environment name it will be run in <em>every</em> environmentIgnore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 284–291why, one step back284prior to the environment specific callback.</p>285286<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces287in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.288Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,289otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>290291<pre><code>app.configure(function(){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 292–294why, one step back292 app.use(express.methodOverride());293 app.use(express.bodyParser());294 app.use(app.router);Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 295–297why, one step back295});296297app.configure('development', function(){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 298–299why, one step back298 app.use(express.static(__dirname + '/public'));299 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 300–303why, one step back300});301302app.configure('production', function(){303 var oneYear = 31557600000;regenerated docsTj Holowaychukbefore adoptiondd7158a
line 304why, one step back304 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 305why, one step back305 app.use(express.errorHandler());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 306–307why, one step back306});307</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 308–323why, one step back308309<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>310311<pre><code> app.configure(function(){312 app.set('views', __dirname + '/views');313 app.set('views');314 // => "/absolute/path/to/views"315316 app.enable('some feature');317 // same as app.set('some feature', true);318319 app.disable('some feature');320 // same as app.set('some feature', false);321322 app.enabled('some feature')323 // => falsefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 324–325why, one step back324 });325</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 326why, one step back326fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 327why, one step back327<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 328why, one step back328fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 329–330why, one step back329<pre><code>$ NODE_ENV=production node app.js330</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 331–333why, one step back331332<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>333fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 334why, one step back334<h3 id="settings">Settings</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 335–337why, one step back335336<p>Express supports the following settings out of the box:</p>337fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 338–343why, one step back338<ul>339<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>340<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>341<li><em>view engine</em> Default view engine name for views rendered without extensions</li>342<li><em>view options</em> An object specifying global view options</li>343</ul>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 344–345why, one step back344345fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 346–347why, one step back346<h3 id="routing">Routing</h3>347Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 348why, one step back348<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 349–350why, one step back349For example we may want to render a user’s account for the path <em>/user/12</em>, this350can be done by defining the route below. The values associated to the named placeholdersIgnore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 351–353why, one step back351are available as <code>req.params</code>.</p>352353<pre><code>app.get('/user/:id', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 354–356why, one step back354 res.send('user ' + req.params.id);355});356</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 357–360why, one step back357358<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example359when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>360fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 361–362why, one step back361<pre><code>\/user\/([^\/]+)\/?362</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 363–364why, one step back363364<p>Regular expression literals may also be passed for complex uses. Since capturefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 365why, one step back365groups 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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 366–368why, one step back366367<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){368 res.send(req.params);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 369–370why, one step back369});370</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 371–380why, one step back371372<p>Curl requests against the previously defined route:</p>373374<pre><code> $ curl http://dev:3000/user375 [null,null]376 $ curl http://dev:3000/users377 [null,null]378 $ curl http://dev:3000/users/1379 ["1",null]380 $ curl http://dev:3000/users/1..15fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 381–382why, one step back381 ["1","15"]382</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 383–416why, one step back383384<p>Below are some route examples, and the associated paths that they385may consume:</p>386387<pre><code> "/user/:id"388 /user/12389390 "/users/:id?"391 /users/5392 /users393394 "/files/*"395 /files/jquery.js396 /files/javascripts/jquery.js397398 "/file/*.*"399 /files/jquery.js400 /files/javascripts/jquery.js401402 "/user/:id/:operation?"403 /user/1404 /user/1/edit405406 "/products.:format"407 /products.json408 /products.xml409410 "/products.:format?"411 /products.json412 /products.xml413 /products414415 "/user/:id.:format?"416 /user/12fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 417–418why, one step back417 /user/12.json418</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 419–430why, one step back419420<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>421422<pre><code>var express = require('express')423 , app = express.createServer();424425app.use(express.bodyParser());426427app.post('/', function(req, res){428 res.send(req.body);429});430fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 431–432why, one step back431app.listen(3000);432</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 433why, one step back433fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 434why, one step back434<p>Typically we may use a “dumb” placeholder such as “/user/:id” which has no restrictions, however say for example we are limiting a user id to digits, we may use <em>‘/user/:id(\d+)’</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 435why, one step back435fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 436why, one step back436<h3 id="passing-route control">Passing Route Control</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 437–442why, one step back437438<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,439the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,440and 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>441442<pre><code>app.get('/users/:id?', function(req, res, next){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 443–448why, one step back443 var id = req.params.id;444 if (id) {445 // do something446 } else {447 next();448 }Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 449–451why, one step back449});450451app.get('/users', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 452–454why, one step back452 // do something else453});454</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 455–487why, one step back455456<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>457458<pre><code>var express = require('express')459 , app = express.createServer();460461var users = [{ name: 'tj' }];462463app.all('/user/:id/:op?', function(req, res, next){464 req.user = users[req.params.id];465 if (req.user) {466 next();467 } else {468 next(new Error('cannot find user ' + req.params.id));469 }470});471472app.get('/user/:id', function(req, res){473 res.send('viewing ' + req.user.name);474});475476app.get('/user/:id/edit', function(req, res){477 res.send('editing ' + req.user.name);478});479480app.put('/user/:id', function(req, res){481 res.send('updating ' + req.user.name);482});483484app.get('*', function(req, res){485 res.send('what???', 404);486});487fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 488–489why, one step back488app.listen(3000); 489</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 490why, one step back490fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 491why, one step back491<h3 id="middleware">Middleware</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 492–498why, one step back492493<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be494passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>495496<pre><code> var express = require('express');497498var app = express.createServer(fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 499–502why, one step back499 express.logger()500 , express.bodyParser()501 );502</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 503–505why, one step back503504<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>505fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 506–507why, one step back506<pre><code>app.use(express.logger({ format: ':method :uri' }));507</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 508why, one step back508fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 509why, one step back509<p>Typically with connect middleware you would <em>require(‘connect’)</em> like so:</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 510–512why, one step back510511<pre><code>var connect = require('connect');512app.use(connect.logger());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 513–514why, one step back513app.use(connect.bodyParser());514</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 515–518why, one step back515516<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>517518<pre><code>app.use(express.logger());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 519–520why, one step back519app.use(express.bodyParser());520</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 521why, one step back521fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 522why, one step back522<h3 id="route-middleware">Route Middleware</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 523–525why, one step back523524<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>525fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 526why, one step back526<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 527–532why, one step back527528<pre><code>app.get('/user/:id', function(req, res, next){529 loadUser(req.params.id, function(err, user){530 if (err) return next(err);531 res.send('Viewing user ' + user.name);532 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 533–534why, one step back533});534</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 535why, one step back535fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 536why, one step back536<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 537–550why, one step back537538<pre><code>function loadUser(req, res, next) {539 // You would fetch your user from the db540 var user = users[req.params.id];541 if (user) {542 req.user = user;543 next();544 } else {545 next(new Error('Failed to load user ' + req.params.id));546 }547}548549app.get('/user/:id', loadUser, function(req, res){550 res.send('Viewing user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 551–552why, one step back551});552</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 553–563why, one step back553554<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>555556<pre><code>function andRestrictToSelf(req, res, next) {557 req.authenticatedUser.id == req.user.id558 ? next()559 : next(new Error('Unauthorized'));560}561562app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){563 res.send('Editing user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 564–565why, one step back564});565</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 566–578why, one step back566567<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>568569<pre><code>function andRestrictTo(role) {570 return function(req, res, next) {571 req.authenticatedUser.role == role572 ? next()573 : next(new Error('Unauthorized'));574 }575}576577app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){578 res.send('Deleted user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 579–580why, one step back579});580</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 581why, one step back581fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 582why, one step back582<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 583–592why, one step back583584<pre><code>var a = [middleware1, middleware2]585 , b = [middleware3, middleware4]586 , all = [a, b];587588app.get('/foo', a, function(){});589app.get('/bar', a, function(){});590591app.get('/', a, middleware3, middleware4, function(){});592app.get('/', a, b, function(){});fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 593–594why, one step back593app.get('/', all, function(){});594</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 595–597why, one step back595596<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>597fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 598why, one step back598<h3 id="http-methods">HTTP Methods</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 599–601why, one step back599600<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>601fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 602why, one step back602<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 603–607why, one step back603604<pre><code> <form method="post" action="/">605 <input type="text" name="user[name]" />606 <input type="text" name="user[email]" />607 <input type="submit" value="Submit" />fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 608–609why, one step back608 </form>609</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 610why, one step back610fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 611why, one step back611<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 612why, one step back612fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 613–614why, one step back613<pre><code>app.use(express.bodyParser());614</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 615–620why, one step back615616<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>617618<pre><code>app.post('/', function(req, res){619 console.log(req.body.user);620 res.redirect('back');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 621–622why, one step back621});622</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 623why, one step back623fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 624why, one step back624<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 625–626why, one step back625626<pre><code>app.use(express.bodyParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 627–628why, one step back627app.use(express.methodOverride());628</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 629–641why, one step back629630<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>631632<pre><code><form method="post" action="/">633 <input type="hidden" name="_method" value="put" />634 <input type="text" name="user[name]" />635 <input type="text" name="user[email]" />636 <input type="submit" value="Submit" /> 637</form>638639app.put('/', function(){640 console.log(req.body.user);641 res.redirect('back');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 642–643why, one step back642});643</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 644why, one step back644fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 645why, one step back645<h3 id="error-handling">Error Handling</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 646–656why, one step back646647<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,648or passed to <em>next(err)</em>. Below is an example which serves different pages based on our649ad-hoc <em>NotFound</em> exception:</p>650651<pre><code>function NotFound(msg){652 this.name = 'NotFound';653 Error.call(this, msg);654 Error.captureStackTrace(this, arguments.callee);655}656fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 657why, one step back657NotFound.prototype.__proto__ = Error.prototype;Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 658–664why, one step back658659app.get('/404', function(req, res){660 throw new NotFound;661});662663app.get('/500', function(req, res){664 throw new Error('keyboard cat!');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 665–666why, one step back665});666</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 667–672why, one step back667668<p>We can call <em>app.error()</em> several times as shown below.669Here we check for an instanceof <em>NotFound</em> and show the670404 page, or we pass on to the next error handler.</p>671672<p>Note that these handlers can be defined anywhere, as theyfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 673why, one step back673will be placed below the route handlers on <em>listen()</em>. ThisIgnore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 674–682why, one step back674allows for definition within <em>configure()</em> blocks so we can675handle exceptions in different ways based on the environment.</p>676677<pre><code>app.error(function(err, req, res, next){678 if (err instanceof NotFound) {679 res.render('404.jade');680 } else {681 next(err);682 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 683–684why, one step back683});684</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 685–686why, one step back685686<p>Here we assume all errors as 500 for the simplicity offixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 687why, one step back687this 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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 688–692why, one step back688689<pre><code>app.error(function(err, req, res){690 res.render('500.jade', {691 error: err692 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 693–694why, one step back693});694</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 695–696why, one step back695696<p>Our apps could also utilize the Connect <em>errorHandler</em> middlewarefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 697–698why, one step back697to report on exceptions. For example if we wish to output exceptions698in “development” mode to <em>stderr</em> we can use:</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 699why, one step back699fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 700–701why, one step back700<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));701</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 702–705why, one step back702703<p>Also during development we may want fancy html pages to show exceptions704that are passed or thrown, so we can set <em>showStack</em> to true:</p>705fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 706–707why, one step back706<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));707</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 708–711why, one step back708709<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>710is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>711fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 712why, one step back712<h3 id="route-param pre-conditions">Route Param Pre-conditions</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 713–720why, one step back713714<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>715716<pre><code>app.get('/user/:userId', function(req, res, next){717 User.get(req.params.userId, function(err, user){718 if (err) return next(err);719 res.send('user ' + user.name);720 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 721–722why, one step back721}); 722</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 723–732why, one step back723724<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>725726<pre><code>app.param('userId', function(req, res, next, id){727 User.get(id, function(err, user){728 if (err) return next(err);729 if (!user) return next(new Error('failed to find user'));730 req.user = user;731 next();732 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 733–734why, one step back733});734</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 735–739why, one step back735736<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>737738<pre><code>app.get('/user/:userId', function(req, res){739 res.send('user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 740–741why, one step back740});741</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 742–744why, one step back742743<p>For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to <em>next(err)</em>.</p>744fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 745–746why, one step back745<pre><code>app.param('number', function(n){ return parseInt(n, 10); });746</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 747–749why, one step back747748<p>We may also apply the same callback to several placeholders, for example a route GET <em>/commits/:from-:to</em> are both numbers, so we may define them as an array:</p>749fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 750–751why, one step back750<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });751</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 752why, one step back752fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 753why, one step back753<h3 id="view-rendering">View Rendering</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 754why, one step back754fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 755why, one step back755<p>View filenames take the form “<name>.<engine>”, where <engine> is the nameIgnore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 756why, one step back756of 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 757–758why, one step back757tell 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 behaviour758<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 759–760why, one step back759760<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 761why, one step back761and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed asIgnore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 762–764why, one step back762the <em>body</em> local variable in <em>layout.jade</em>.</p>763764<pre><code>app.get('/', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 765–767why, one step back765 res.render('index.jade', { title: 'My Site' });766});767</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 768–771why, one step back768769<p>The new <em>view engine</em> setting allows us to specify our default template engine,770so for example when using jade we could set:</p>771fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 772–773why, one step back772<pre><code>app.set('view engine', 'jade');773</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 774–776why, one step back774775<p>Allowing us to render with:</p>776fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 777–778why, one step back777<pre><code>res.render('index');778</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 779–781why, one step back779780<p>vs:</p>781fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 782–783why, one step back782<pre><code>res.render('index.jade');783</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 784–787why, one step back784785<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still786mix and match template engines:</p>787fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 788–789why, one step back788<pre><code>res.render('another-page.ejs');789</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 790–794why, one step back790791<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>792793<pre><code>app.set('view options', {794 layout: falsefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 795–796why, one step back795});796</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 797–799why, one step back797798<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>799fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 800–801why, one step back800<pre><code>res.render('myview.ejs', { layout: true });801</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 802–804why, one step back802803<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>804fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 805–806why, one step back805<pre><code>res.render('page', { layout: 'mylayout' });806</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 807–809why, one step back807808<p>Otherwise we must specify the extension:</p>809fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 810–811why, one step back810<pre><code>res.render('page', { layout: 'mylayout.jade' });811</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 812–814why, one step back812813<p>These paths may also be absolute:</p>814fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 815–816why, one step back815<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });816</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 817–822why, one step back817818<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>819820<pre><code>app.set('view options', {821 open: '{{',822 close: '}}'fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 823–824why, one step back823});824</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 825why, one step back825fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 826why, one step back826<h3 id="view-partials">View Partials</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 827why, one step back827fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 828why, one step back828<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 829why, one step back829in a view to display comments, we could use partial collection:</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 830why, one step back830fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 831–832why, one step back831<pre><code>partial('comment', { collection: comments });832</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 833why, one step back833regenerated docsTj Holowaychukbefore adoptiondd7158a
line 834why, one step back834<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 835why, one step back835fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 836–837why, one step back836<pre><code>partial('comment', comments);837</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 838why, one step back838fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 839why, one step back839<p>When using the partial collection support a few “magic” locals are providedIgnore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 840–841why, one step back840for free:</p>841fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 842–847why, one step back842<ul>843<li><em>firstInCollection</em> true if this is the first object</li>844<li><em>indexInCollection</em> index of the object in the collection</li>845<li><em>lastInCollection</em> true if this is the last object</li>846<li><em>collectionLength</em> length of the collection</li>847</ul>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 848why, one step back848docsTj Holowaychukbefore adoption4609984
line 849why, one step back849fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 850–851why, one step back850<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>851Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 852–855why, one step back852<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>853854<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>855fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 856why, one step back856<h3 id="view-lookup">View Lookup</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 857why, one step back857fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 858why, one step back858<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 859why, one step back859fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 860why, one step back860<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 861why, one step back861fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 862why, one step back862<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 863why, one step back863fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 864why, one step back864<h3 id="template-engines">Template Engines</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 865–867why, one step back865866<p>Below are a few template engines commonly used with Express:</p>867fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 868–874why, one step back868<ul>869<li><a href="http://github.com/visionmedia/haml.js">Haml</a> haml implementation</li>870<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>871<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>872<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>873<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>874</ul>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 875–876why, one step back875876fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 877why, one step back877<h3 id="session-support">Session Support</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 878why, one step back878fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 879–880why, one step back879<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>880Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 881why, one step back881<pre><code>app.use(express.cookieParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 882–883why, one step back882app.use(express.session({ secret: "keyboard cat" }));883</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 884–888why, one step back884885<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>886887<pre><code>var RedisStore = require('connect-redis');888app.use(express.cookieParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 889–890why, one step back889app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));890</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 891–914why, one step back891892<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>893894<pre><code>var RedisStore = require('connect-redis');895app.use(express.bodyParser());896app.use(express.cookieParser());897app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));898899app.post('/add-to-cart', function(req, res){900 // Perhaps we posted several items with a form901 // (use the bodyParser() middleware for this)902 var items = req.body.items;903 req.session.items = items;904 res.redirect('back');905});906907app.get('/add-to-cart', function(req, res){908 // When redirected back to GET /add-to-cart909 // we could check req.session.items && req.session.items.length910 // to print out a message911 if (req.session.items && req.session.items.length) {912 req.flash('info', 'You have %s items in your cart', req.session.items.length);913 }914 res.render('shopping-cart');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 915–916why, one step back915});916</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 917–919why, one step back917918<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>919fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 920why, one step back920<h3 id="migration-guide">Migration Guide</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 921why, one step back921docsTj Holowaychukbefore adoptionc1a82bf
line 922why, one step back922<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 923why, one step back923fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 924why, one step back924<h3 id="req.header()">req.header(key[, defaultValue])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 925–929why, one step back925926<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>927928<pre><code>req.header('Host');929req.header('host');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 930–931why, one step back930req.header('Accept', '*/*');931</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 932–940why, one step back932933<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>934935<pre><code>// sent Referrer: http://google.com936937req.header('Referer');938// => "http://google.com"939940req.header('Referrer');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 941–942why, one step back941// => "http://google.com"942</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 943why, one step back943fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 944why, one step back944<h3 id="req.accepts()">req.accepts(type)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 945–949why, one step back945946<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>947948<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise949the 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 950–951why, one step back950may pass the subtype such as “html” which is then converted internally951to “text/html” using the mime lookup table.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 952–965why, one step back952953<pre><code>// Accept: text/html954req.accepts('html');955// => true956957// Accept: text/*; application/json958req.accepts('html');959req.accepts('text/html');960req.accepts('text/plain');961req.accepts('application/json');962// => true963964req.accepts('image/png');965req.accepts('png');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 966–967why, one step back966// => false967</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 968why, one step back968fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 969why, one step back969<h3 id="req.is()">req.is(type)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 970–984why, one step back970971<p>Check if the incoming request contains the <em>Content-Type</em>972header field, and it contains the give mime <em>type</em>.</p>973974<pre><code> // With Content-Type: text/html; charset=utf-8975 req.is('html');976 req.is('text/html');977 // => true978979 // When Content-Type is application/json980 req.is('json');981 req.is('application/json');982 // => true983984 req.is('html');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 985–986why, one step back985 // => false986</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 987–989why, one step back987988<p>Ad-hoc callbacks can also be registered with Express, to perform989assertions again the request, for example if we need an expressivefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 990why, one step back990way to check if our incoming request is an image, we can register <em>“an image”</em>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 991–994why, one step back991callback:</p>992993<pre><code> app.is('an image', function(req){994 return 0 == req.headers['content-type'].indexOf('image');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 995–996why, one step back995 });996</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 997–998why, one step back997998<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 999why, one step back999such as <em>“image/jpeg”</em>, <em>“image/png”</em>, etc.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1000–1006why, one step back10001001<pre><code> app.post('/image/upload', function(req, res, next){1002 if (req.is('an image')) {1003 // do something1004 } else {1005 next();1006 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1007–1008why, one step back1007 });1008</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1009–1012why, one step back10091010<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you1011can perform any request assertion you wish.</p>1012fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1013why, one step back1013<p>Wildcard matches can also be made, simplifying our example above for <em>“an image”</em>, by asserting the <em>subtype</em> only:</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1014why, one step back1014fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1015–1016why, one step back1015<pre><code>req.is('image/*');1016</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1017why, one step back1017fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1018why, one step back1018<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1019why, one step back1019fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1020–1021why, one step back1020<pre><code>req.is('*/json');1021</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1022why, one step back1022fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1023why, one step back1023<h3 id="req.param()">req.param(name[, default])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1024–1026why, one step back10241025<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>1026fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1027–1031why, one step back1027<ul>1028<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>1029<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1030<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1031</ul>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1032why, one step back1032fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1033why, one step back1033Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1034–1037why, one step back1034<p>To utilize urlencoded request bodies, <em>req.body</em>1035should be an object. This can be done by using1036the _express.bodyParser middleware.</p>1037fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1038why, one step back1038<h3 id="req.flash()">req.flash(type[, msg])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1039–1053why, one step back10391040<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>10411042<pre><code>req.flash('info', 'email sent');1043req.flash('error', 'email delivery failed');1044req.flash('info', 'email re-sent');1045// => 210461047req.flash('info');1048// => ['email sent', 'email re-sent']10491050req.flash('info');1051// => []10521053req.flash();fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1054–1055why, one step back1054// => { error: ['email delivery failed'], info: [] }1055</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1056–1058why, one step back10561057<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>1058fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1059–1060why, one step back1059<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1060</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1061why, one step back1061fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1062why, one step back1062<h3 id="req.isxmlhttprequest">req.isXMLHttpRequest</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1063–1067why, one step back10631064<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1065to see if it was issued by an <em>XMLHttpRequest</em>:</p>10661067<pre><code>req.xhrfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1068–1069why, one step back1068req.isXMLHttpRequest1069</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1070why, one step back1070fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1071why, one step back1071<h3 id="res.header()">res.header(key[, val])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1072–1081why, one step back10721073<p>Get or set the response header <em>key</em>.</p>10741075<pre><code>res.header('Content-Length');1076// => undefined10771078res.header('Content-Length', 123);1079// => 12310801081res.header('Content-Length');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1082–1083why, one step back1082// => 1231083</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1084why, one step back1084fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1085why, one step back1085<h3 id="res.charset">res.charset</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1086why, one step back1086fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1087why, one step back1087<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 1088–1089why, one step back10881089<pre><code>res.charset = 'ISO-8859-1';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1090–1091why, one step back1090res.render('users');1091</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1092–1095why, one step back10921093<p>or before responding with <code>res.send()</code>:</p>10941095<pre><code>res.charset = 'ISO-8859-1';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1096–1097why, one step back1096res.send(str);1097</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1098why, one step back1098fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1099why, one step back1099<p>or with node’s <code>res.end()</code>:</p>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1100–1102why, one step back11001101<pre><code>res.charset = 'ISO-8859-1';1102res.header('Content-Type', 'text/plain');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1103–1104why, one step back1103res.end(str);1104</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1105why, one step back1105fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1106why, one step back1106<h3 id="res.contenttype()">res.contentType(type)</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1107why, one step back1107Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1108–1111why, one step back1108<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>11091110<pre><code> var filename = 'path/to/image.png';1111 res.contentType(filename);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1112–1113why, one step back1112 // Content-Type is now "image/png"1113</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1114why, one step back1114regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1115why, one step back1115<p>A literal <em>Content-Type</em> works as well:</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1116why, one step back1116fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1117–1118why, one step back1117<pre><code> res.contentType('application/json');1118</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1119–1121why, one step back11191120<p>Or simply the extension without leading <code>.</code>:</p>1121fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1122–1123why, one step back1122<pre><code> res.contentType('json');1123</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1124why, one step back1124fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1125why, one step back1125<h3 id="res.attachment()">res.attachment([filename])</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1126why, one step back1126fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1127why, one step back1127<p>Sets the <em>Content-Disposition</em> response header to “attachment”, with optional <em>filename</em>.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1128why, one step back1128fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1129–1130why, one step back1129<pre><code> res.attachment('path/to/my/image.png');1130</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1131why, one step back1131fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1132why, one step back1132<h3 id="res.sendfile()">res.sendfile(path[, options[, callback]])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1133why, one step back1133fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1134why, one step back1134<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1135why, one step back1135fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1136–1137why, one step back1136<pre><code>res.sendfile('path/to/my.file');1137</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1138–1147why, one step back11381139<p>This method accepts an optional callback which is called when1140an 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>11411142<pre><code>res.sendfile(path, function(err){1143 if (err) {1144 next(err);1145 } else {1146 console.log('transferred %s', path);1147 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1148–1149why, one step back1148});1149</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1150–1154why, one step back11501151<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>11521153<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1154 // handlefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1155–1156why, one step back1155});1156</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1157why, one step back1157fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1158why, one step back1158<h3 id="res.download()">res.download(file[, filename[, callback]])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1159–1162why, one step back11591160<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>11611162<pre><code>res.download('path/to/image.png');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1163–1164why, one step back1163res.download('path/to/image.png', 'foo.png');1164</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1165–1168why, one step back11651166<p>This is equivalent to:</p>11671168<pre><code>res.attachment(file);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1169–1170why, one step back1169res.sendfile(file);1170</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1171–1175why, one step back11711172<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>:</p>11731174<pre><code>res.download(path, 'expenses.doc', function(err){1175 // handlefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1176–1177why, one step back1176});1177</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1178why, one step back1178fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1179why, one step back1179<h3 id="res.send()">res.send(body|status[, headers|status[, status]])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1180–1189why, one step back11801181<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1182objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>11831184<pre><code> res.send(); // 2041185 res.send(new Buffer('wahoo'));1186 res.send({ some: 'json' });1187 res.send('<p>some html</p>');1188 res.send('Sorry, cant find that', 404);1189 res.send('text', { 'Content-Type': 'text/plain' }, 201);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1190–1191why, one step back1190 res.send(404);1191</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1192–1196why, one step back11921193<p>By default the <em>Content-Type</em> response header is set, however if explicitly1194assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1195it will not be set again.</p>1196fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1197why, one step back1197<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1198why, one step back1198fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1199why, one step back1199<h3 id="res.redirect()">res.redirect(url[, status])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1200–1206why, one step back12001201<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>12021203<pre><code>res.redirect('/', 301);1204res.redirect('/account');1205res.redirect('http://google.com');1206res.redirect('home');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1207–1208why, one step back1207res.redirect('back');1208</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1209why, one step back1209fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1210why, one step back1210<p>Express supports “redirect mapping”, which by default provides <em>home</em>, and <em>back</em>.Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1211why, one step back1211The <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 1212why, one step back1212the “home” setting and defaults to “/”.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1213why, one step back1213fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1214why, one step back1214<h3 id="res.cookie()">res.cookie(name, val[, options])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1215–1218why, one step back12151216<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>12171218<pre><code>// "Remember me" for 15 minutes fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1219–1220why, one step back1219res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1220</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1221why, one step back1221docsTj Holowaychukbefore adoption131970b
lines 1222–1223why, one step back1222<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>1223fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1224–1225why, one step back1224<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });1225</code></pre>docsTj Holowaychukbefore adoption131970b
line 1226why, one step back1226updated docsTj Holowaychukbefore adoption99b49d2
line 1227why, one step back1227<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieParser</em> middleware, which provides the <em>req.cookies</em> object:</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1228–1232why, one step back12281229<pre><code>app.use(express.cookieParser());12301231app.get('/', function(req, res){1232 // use req.cookies.remembermefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1233–1234why, one step back1233});1234</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1235why, one step back1235fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1236why, one step back1236<h3 id="res.clearcookie()">res.clearCookie(name)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1237why, one step back1237fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1238why, one step back1238<p>Clear cookie <em>name</em> by setting “expires” far in the past.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1239why, one step back1239fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1240–1241why, one step back1240<pre><code>res.clearCookie('rememberme');1241</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1242why, one step back1242fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1243why, one step back1243<h3 id="res.render()">res.render(view[, options[, fn]])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1244–1248why, one step back12441245<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1246When a callback function is given a response will <em>not</em> be made1247automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>1248fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1249why, one step back1249<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1250–1251why, one step back12501251<pre><code>var user = { name: 'tj' };fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1252–1253why, one step back1252res.render('index', { layout: false, user: user });1253</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1254why, one step back1254fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1255why, one step back1255<h3 id="res.partial()">res.partial(view[, options])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1256–1259why, one step back12561257<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1258to the view as a local variable.</p>1259fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1260–1262why, one step back1260<ul>1261<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1262<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1263why, one step back1263fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1264–1274why, one step back1264<ul>1265<li>as: ‘something’ will add the <em>something</em> local variable</li>1266<li>as: this will use the collection value as the template context</li>1267<li>as: global will merge the collection value’s properties with <em>locals</em></li>1268</ul>1269</li>1270<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1271For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1272</ul>12731274Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1275–1282why, one step back1275<p>The following are equivalent, and the name of collection value when passed1276to the partial will be <em>movie</em> as derived from the name.</p>12771278<pre><code>partial('theatre/movie.jade', { collection: movies });1279partial('theatre/movie.jade', movies);1280partial('movie.jade', { collection: movies });1281partial('movie.jade', movies);1282partial('movie', movies);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1283–1284why, one step back1283// In view: movie.director1284</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1285why, one step back1285fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1286why, one step back1286<p>To change the local from <em>movie</em> to <em>video</em> we can use the “as” option:</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1287–1288why, one step back12871288<pre><code>partial('movie', { collection: movies, as: 'video' });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1289–1290why, one step back1289// In view: video.director1290</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1291–1295why, one step back12911292<p>Also we can make our movie the value of <em>this</em> within our view so that instead1293of <em>movie.director</em> we could use <em>this.director</em>.</p>12941295<pre><code>partial('movie', { collection: movies, as: this });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1296–1297why, one step back1296// In view: this.director1297</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1298why, one step back1298fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1299why, one step back1299<p>Another alternative is to “expand” the properties of the collection item intoIgnore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1300–1302why, one step back1300pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>13011302<pre><code>partial('movie', { collection: movies, as: global });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1303–1304why, one step back1303// In view: director1304</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1305–1317why, one step back13051306<p>This same logic applies to a single partial object usage:</p>13071308<pre><code>partial('movie', { object: movie, as: this });1309// In view: this.director13101311partial('movie', { object: movie, as: global });1312// In view: director13131314partial('movie', { object: movie, as: 'video' });1315// In view: video.director13161317partial('movie', { object: movie });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1318–1319why, one step back1318// In view: movie.director1319</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1320why, one step back1320fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1321why, one step back1321<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>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1322why, one step back1322regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1323–1324why, one step back1323<pre><code>var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1324partial('movie', movie)fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1325–1326why, one step back1325// => In view: movie.director1326</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1327why, one step back1327fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1328why, one step back1328<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 1329–1330why, one step back13291330<pre><code>var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1331–1332why, one step back1331partial('movie', movie)1332</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1333–1337why, one step back13331334<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>13351336<pre><code> partial('movie', { locals: { movie: movie }})1337 partial('movie', { movie: movie })fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1338–1339why, one step back1338 partial('movie', { object: movie })1339</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1340why, one step back1340Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1341–1353why, one step back1341<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>13421343<pre><code>app.get('/users', function(req, res){1344 if (req.xhr) {1345 // respond with the each user in the collection1346 // passed to the "user" view1347 res.partial('user', users);1348 } else {1349 // respond with layout, and users page1350 // which internally does partial('user', users)1351 // along with other UI1352 res.render('users', { users: users });1353 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1354–1355why, one step back1354});1355</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1356why, one step back1356fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1357why, one step back1357<h3 id="res.local()">res.local(name[, val])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1358–1371why, one step back13581359<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>13601361<pre><code> app.all('/movie/:id', function(req, res, next){1362 Movie.get(req.params.id, function(err, movie){1363 // Assigns res.locals.movie = movie1364 res.local('movie', movie);1365 });1366 });13671368 app.get('/movie/:id', function(req, res){1369 // movie is already a local, however we1370 // can pass more if we wish1371 res.render('movie', { displayReviews: true });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1372–1373why, one step back1372 });1373</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1374why, one step back1374fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1375why, one step back1375<h3 id="res.locals()">res.locals(obj)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1376why, one step back1376regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1377–1381why, one step back1377<p> Assign several locals with the given <em>obj</em>. The following are equivalent:</p>13781379<pre><code> res.local('foo', bar);1380 res.local('bar', baz);1381fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1382–1383why, one step back1382 res.locals({ foo: bar, bar, baz });1383</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1384why, one step back1384fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1385why, one step back1385<h3 id="app.set()">app.set(name[, val])</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1386why, one step back1386Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1387–1391why, one step back1387<p>Apply an application level setting <em>name</em> to <em>val</em>, or1388get the value of <em>name</em> when <em>val</em> is not present:</p>13891390<pre><code>app.set('views', __dirname + '/views');1391app.set('views');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1392–1393why, one step back1392// => ...path...1393</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1394–1397why, one step back13941395<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>13961397<pre><code>app.settings.viewsfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1398–1399why, one step back1398// => ...path...1399</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1400why, one step back1400fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1401why, one step back1401<h3 id="app.enable()">app.enable(name)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1402–1409why, one step back14021403<p>Enable the given setting <em>name</em>:</p>14041405<pre><code>app.enable('some arbitrary setting');1406app.set('some arbitrary setting');1407// => true14081409app.enabled('some arbitrary setting');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1410–1411why, one step back1410// => true1411</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1412why, one step back1412fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1413why, one step back1413<h3 id="app.enabled()">app.enabled(name)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1414–1421why, one step back14141415<p>Check if setting <em>name</em> is enabled:</p>14161417<pre><code>app.enabled('view cache');1418// => false14191420app.enable('view cache');1421app.enabled('view cache');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1422–1423why, one step back1422// => true1423</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1424why, one step back1424fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1425why, one step back1425<h3 id="app.disable()">app.disable(name)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1426–1433why, one step back14261427<p>Disable the given setting <em>name</em>:</p>14281429<pre><code>app.disable('some setting');1430app.set('some setting');1431// => false14321433app.disabled('some setting');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1434–1435why, one step back1434// => false1435</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1436why, one step back1436fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1437why, one step back1437<h3 id="app.disabled()">app.disabled(name)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1438–1447why, one step back14381439<p>Check if setting <em>name</em> is disabled:</p>14401441<pre><code>app.enable('view cache');14421443app.disabled('view cache');1444// => false14451446app.disable('view cache');1447app.disabled('view cache');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1448–1449why, one step back1448// => true1449</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1450why, one step back1450fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1451why, one step back1451<h3 id="app.configure()">app.configure(env|function[, function])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1452–1460why, one step back14521453<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>14541455<pre><code>app.configure(function(){1456 // executed for each env1457});14581459app.configure('development', function(){1460 // executed for 'development' onlyfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1461–1462why, one step back1461});1462</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1463why, one step back1463fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1464why, one step back1464<h3 id="app.redirect()">app.redirect(name, val)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1465–1467why, one step back14651466<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>1467fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1468–1469why, one step back1468<pre><code>app.redirect('google', 'http://google.com');1469</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1470–1472why, one step back14701471<p>Now in a route we may call:</p>1472fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1473why, one step back1473<p> res.redirect(‘google’);</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1474–1478why, one step back14741475<p>We may also map dynamic redirects:</p>14761477<pre><code>app.redirect('comments', function(req, res){1478 return '/post/' + req.params.id + '/comments';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1479–1480why, one step back1479});1480</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1481–1487why, one step back14811482<p>So now we may do the following, and the redirect will dynamically adjust to1483the context of the request. If we called this route with <em>GET /post/12</em> our1484redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>14851486<pre><code>app.get('/post/:id', function(req, res){1487 res.redirect('comments');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1488–1489why, one step back1488});1489</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1490–1492why, one step back14901491<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>1492fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1493–1494why, one step back1493<pre><code>res.redirect('/posts');1494</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1495why, one step back1495fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1496why, one step back1496<h3 id="app.error()">app.error(function)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1497–1503why, one step back14971498<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1499Note that we may set several error handlers by making several calls to this method, however the handler1500should call <em>next(err)</em> if it does not wish to deal with the exception:</p>15011502<pre><code>app.error(function(err, req, res, next){1503 res.send(err.message, 500);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1504–1505why, one step back1504});1505</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1506why, one step back1506fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1507why, one step back1507<h3 id="app.helpers()">app.helpers(obj)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1508–1510why, one step back15081509<p>Registers static view helpers.</p>1510updated docsTj Holowaychukbefore adoption99b49d2
lines 1511–1515why, one step back1511<pre><code>app.helpers({1512 name: function(first, last){ return first + ', ' + last }1513 , firstName: 'tj'1514 , lastName: 'holowaychuk'1515});fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1516–1517why, one step back1516</code></pre>1517Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1518–1520why, one step back1518<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1519as well as the <em>name()</em> function exposed.</p>1520fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1521–1522why, one step back1521<pre><code><%= name(firstName, lastName) %>1522</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1523why, one step back1523updated docsTj Holowaychukbefore adoption99b49d2
lines 1524–1534why, one step back1524<p>Express also provides a few locals by default:</p>15251526<pre><code>- `settings` the app's settings object1527- `filename` the view's filename1528- `request` the request object1529- `response` the response object1530- `app` the application itself1531</code></pre>15321533<p>This method is aliased as <em>app.locals()</em>.</p>1534fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1535why, one step back1535<h3 id="app.dynamichelpers()">app.dynamicHelpers(obj)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1536–1545why, one step back15361537<p>Registers dynamic view helpers. Dynamic view helpers1538are simply functions which accept <em>req</em>, <em>res</em>, and are1539evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1540becomes the local variable it is associated with.</p>15411542<pre><code>app.dynamicHelpers({1543 session: function(req, res){1544 return req.session;1545 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1546–1547why, one step back1546});1547</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1548–1550why, one step back15481549<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>1550fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1551why, one step back1551<pre><code><%= session.name %>updated docsTj Holowaychukbefore adoption99b49d2
lines 1552–1655why, one step back1552</code></pre>15531554<h3 id="app.lookup">app.lookup</h3>15551556<p> The <em>app.lookup</em> http methods returns an array of callback functions1557 associated with the given <em>path</em>.</p>15581559<p> Suppose we define the following routes:</p>15601561<pre><code> app.get('/user/:id', function(){});1562 app.put('/user/:id', function(){});1563 app.get('/user/:id/:op?', function(){});1564</code></pre>15651566<p> We can utilize this lookup functionality to check which routes1567 have been defined, which can be extremely useful for higher level1568 frameworks built on Express.</p>15691570<pre><code> app.lookup.get('/user/:id');1571 // => [Function]15721573 app.lookup.get('/user/:id/:op?');1574 // => [Function]15751576 app.lookup.put('/user/:id');1577 // => [Function]15781579 app.lookup.all('/user/:id');1580 // => [Function, Function]15811582 app.lookup.all('/hey');1583 // => []1584</code></pre>15851586<p> To alias <em>app.lookup.VERB()</em>, we can simply invoke <em>app.VERB()</em>1587 without a callback, as a shortcut, for example the following are1588 equivalent:</p>15891590<pre><code> app.lookup.get('/user');1591 app.get('/user');1592</code></pre>15931594<p> Each function returned has the following properties:</p>15951596<pre><code> var fn = app.get('/user/:id/:op?')[0];15971598 fn.regexp1599 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i16001601 fn.keys1602 // => ['id', 'op']16031604 fn.path1605 // => '/user/:id/:op?'16061607 fn.method1608 // => 'GET'1609</code></pre>16101611<h3 id="app.match">app.match</h3>16121613<p> The <em>app.match</em> http methods return an array of callback functions1614 which match the given <em>url</em>, which may include a query string etc. This1615 is useful when you want reflect on which routes have the opportunity to1616 respond.</p>16171618<p> Suppose we define the following routes:</p>16191620<pre><code> app.get('/user/:id', function(){});1621 app.put('/user/:id', function(){});1622 app.get('/user/:id/:op?', function(){});1623</code></pre>16241625<p> Our match against <strong>GET</strong> will return two functions, since the <em>:op</em>1626 in our second route is optional.</p>16271628<pre><code> app.match.get('/user/1');1629 // => [Function, Function]1630</code></pre>16311632<p> This second call returns only the callback for <em>/user/:id/:op?</em>.</p>16331634<pre><code> app.match.get('/user/23/edit');1635 // => [Function]1636</code></pre>16371638<p> We can also use <em>all()</em> to disregard the http method:</p>16391640<pre><code> app.match.all('/user/20');1641 // => [Function, Function, Function]1642</code></pre>16431644<p> Each function matched has the following properties:</p>16451646<pre><code> var fn = app.match.get('/user/23/edit')[0];16471648 fn.keys1649 // => ['id', 'op']16501651 fn.params1652 // => { id: '23', op: 'edit' }16531654 fn.method1655 // => 'GET'fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1656why, one step back1656</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1657why, one step back1657fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1658why, one step back1658<h3 id="app.mounted()">app.mounted(fn)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1659–1669why, one step back16591660<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>16611662<pre><code>var app = express.createServer(),1663 blog = express.createServer();16641665blog.mounted(function(parent){1666 // parent is app1667 // "this" is blog1668});1669fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1670–1671why, one step back1670app.use(blog);1671</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1672why, one step back1672fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1673why, one step back1673<h3 id="app.register()">app.register(ext, exports)</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1674–1675why, one step back16741675<p>Register the given template engine <em>exports</em>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1676why, one step back1676as <em>ext</em>. For example we may wish to map “.html”Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1677–1678why, one step back1677files to jade:</p>1678fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1679–1680why, one step back1679<pre><code> app.register('.html', require('jade'));1680</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1681–1683why, one step back16811682<p>This is also useful for libraries that may not1683match extensions correctly. For example my haml.jsfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1684–1685why, one step back1684library is installed from npm as “hamljs” so instead1685of layout.hamljs, we can register the engine as “.haml”:</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1686why, one step back1686fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1687–1688why, one step back1687<pre><code> app.register('.haml', require('haml-js'));1688</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1689–1693why, one step back16891690<p>For engines that do not comply with the Express1691specification, we can also wrap their api this way. Below1692we map <em>.md</em> to render markdown files, rendering the html once1693since it will not change on subsequent calls, and support local substitutionfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1694why, one step back1694in the form of “{name}”.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1695–1704why, one step back16951696<pre><code> app.register('.md', {1697 compile: function(str, options){1698 var html = md.toHTML(str);1699 return function(locals){1700 return html.replace(/\{([^}]+)\}/g, function(_, name){1701 return locals[name];1702 });1703 };1704 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1705–1706why, one step back1705 });1706</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
line 1707why, one step back1707fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1708why, one step back1708<h3 id="app.listen()">app.listen([port[, host]])</h3>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1709–1710why, one step back17091710<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 1711why, one step back1711connections will be accepted via <em>INADDR_ANY</em>.</p>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1712–1714why, one step back17121713<pre><code>app.listen();1714app.listen(3000);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1715–1716why, one step back1715app.listen(3000, 'n.n.n.n');1716</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1717–1719why, one step back17171718<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>1719fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1720–1721why, one step back1720<pre><code>app.listen('/tmp/express.sock');1721</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1722–1731why, one step back17221723<p>Then try it out:</p>17241725<pre><code>$ telnet /tmp/express.sock1726GET / HTTP/1.117271728HTTP/1.1 200 OK1729Content-Type: text/plain1730Content-Length: 111731fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1732–1733why, one step back1732Hello World1733</code></pre>Ignore .DS_StoreTj Holowaychukbefore adoption60daf0d
lines 1734–1737why, one step back1734 </div>1735 </div>1736 </body>1737</html>