guide.html
This file
Path
docs/guide.html
1,791 lines · 63.0 KiB · HTML
Last changed by
Merge pull request #706 from jakeg/patch-1TJ Holowaychukbefore adoptionf4f79d2
History of this fileTake it
The walk stopped after 200 commits: lines older than cdbd8af point at it.
migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1–181why, one step back1<html>2 <head>3 <title>Express - node web framework</title>4 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>5 <style>6 #tagline {7 margin-left: 75px;8 margin-bottom: 30px;9 color: rgba(255,255,255,0.7); }10 html {11 background: #1c1c1c url(images/bg.tile.jpg); }1213 body {14 margin: 0;15 padding-bottom: 30px;16 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";17 font-size: 14px;18 line-height: 1.5;19 -webkit-font-smoothing: antialiased;20 background: url(images/bg.jpg) 50% 0 no-repeat;21 color: #8b8b8b; }2223 * {24 outline: none; }2526 em {27 color: white; }2829 a img {30 border: none !important; }3132 a {33 font-weight: bold;34 text-decoration: none;35 color: white;36 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;37 -webkit-transition-duration: 0.15s;38 -webkit-transition-timing-function: ease-out; }39 a:hover {40 opacity: 0.8; }4142 h1, h2, h3, h4 {43 margin: 45px 0 0 0;44 color: white;45 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4647 h3 {48 font-size: 18px; }49 h4 {50 margin-left: 10px;51 font-size: 14px;52 }5354 pre {55 margin: 20px 10px;56 padding: 25px 20px;57 background: rgba(0,0,0,0.5);58 border: 1px solid #323232;59 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);60 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -webkit-border-radius: 5px;62 -moz-border-radius: 5px; }6364 code {65 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6667 ul {68 margin: 15px 0;69 padding: 0 0 0 35px; }70 ul li {71 margin: 0;72 padding: 2px 0;73 list-style: square; }74 ul li ul {75 margin: 0;76 padding-left: 12px;77 }7879 .man-name, #Express { display:none; }8081 .sect {82 margin-left: 40px; }83 img {84 margin-left: 20px;85 margin-bottom: 15px;86 }8788 #logo {89 display: block;90 margin-left: 30%;91 margin-bottom: 30px;92 width: 194px;93 height: 51px;94 background: url(images/logo.png) 0 0 no-repeat;95 text-indent: -99999px; }96 #logo:hover {97 opacity: 0.7; }98 #logo:active {99 opacity: 0.3; }100101 #ribbon {102 position: fixed;103 top: 0;104 right: 0;105 z-index: 2; }106107 #wrapper {108 width: 100%;109 min-height: 800px;110 background: url(images/top.png) 0 0 repeat-x; }111112 #container {113 margin: 0 auto;114 padding-top: 80px;115 width: 550px; }116117 #toc {118 position: fixed;119 top: 0;120 left: 0;121 margin: 0 0 0 15px;122 padding: 15px;123 height: 100%;124 background: rgba(0,0,0,0.2);125 overflow: auto;126 border-right: 1px solid rgba(255,255,255,0.05);127 }128 #toc li {129 padding: 0;130 list-style: none;131 }132 #toc li a {133 font-size: 11px;134 }135 #menu {136 margin-left: 75px;137 padding: 0;138 padding-bottom: 30px; }139 #menu li {140 display: inline;141 list-style: none; }142 #menu li a {143 display: block;144 float: left;145 margin: 0 2px;146 padding: 3px 15px;147 background: rgba(0,0,0,0.2);148 -webkit-border-radius: 8px;149 -moz-border-radius: 8px;150 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);151 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;153 -webkit-transition-duration: 0.15s;154 -webkit-transition-timing-function: ease-out; }155 #menu li a:hover,156 #menu li a.active {157 background: rgba(0,0,0,0.5); }158 #menu li a:active {159 background: rgba(0,0,0,0.1);160 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);161 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }162 </style>163 <script>164 $(function(){165 $('.section').hide();166 $('.toggle, a.section-title').toggle(function(){167 $(this).siblings('ul').fadeIn(300);168 return false;169 }, function(){170 $(this).siblings('ul').fadeOut(300);171 return false;172 });173 });174 </script>175 </head>176 <body>177 <a href='http://github.com/visionmedia/express'> 178 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 179 </a>180 <div id="wrapper">181 <div id="container"><ul id="toc">fixed 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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
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>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 257why, one step back257generate docsTj Holowaychukbefore adoptionff7d5ff
lines 258–282why, one step back258<p>or to access the <code>express(1)</code> executable install globally:</p>259260<pre><code>$ npm install -g express261</code></pre>262263<h2>Quick Start</h2>264265<p> The quickest way to get started with express is to utilize the executable <code>express(1)</code> to generate an application as shown below:</p>266267<p> Create the app:</p>268269<pre><code>$ npm install -g express270$ express /tmp/foo && cd /tmp/foo271</code></pre>272273<p> Install dependencies:</p>274275<pre><code>$ npm install -d276</code></pre>277278<p> Start the server:</p>279280<pre><code>$ node app.js281</code></pre>282fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 283why, one step back283<h3 id="creating-a server">Creating A Server</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 284–292why, one step back284285<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>286287<pre><code>var app = require('express').createServer();288289app.get('/', function(req, res){290 res.send('hello world');291});292fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 293–294why, one step back293app.listen(3000);294</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 295why, one step back295fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 296why, one step back296<h3 id="creating-an https server">Creating An HTTPS Server</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 297–298why, one step back297298<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 299why, one step back299 pass an options object, accepting <em>key</em>, <em>cert</em> and the others mentioned in node’s <a href="http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer">https documentation</a>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 300why, one step back300fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 301–302why, one step back301<pre><code> var app = require('express').createServer({ key: ... });302</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 303why, one step back303fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 304why, one step back304<h3 id="configuration">Configuration</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 305–307why, one step back305306<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers307can 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 308why, one step back308<em>configure()</em> is called without an environment name it will be run in <em>every</em> environmentmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 309–316why, one step back309prior to the environment specific callback.</p>310311<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces312in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.313Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,314otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>315316<pre><code>app.configure(function(){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 317–319why, one step back317 app.use(express.methodOverride());318 app.use(express.bodyParser());319 app.use(app.router);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 320–322why, one step back320});321322app.configure('development', function(){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 323–324why, one step back323 app.use(express.static(__dirname + '/public'));324 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 325–328why, one step back325});326327app.configure('production', function(){328 var oneYear = 31557600000;regenerated docsTj Holowaychukbefore adoptiondd7158a
line 329why, one step back329 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 330why, one step back330 app.use(express.errorHandler());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 331–332why, one step back331});332</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 333–348why, one step back333334<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>335336<pre><code> app.configure(function(){337 app.set('views', __dirname + '/views');338 app.set('views');339 // => "/absolute/path/to/views"340341 app.enable('some feature');342 // same as app.set('some feature', true);343344 app.disable('some feature');345 // same as app.set('some feature', false);346347 app.enabled('some feature')348 // => falsefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 349–350why, one step back349 });350</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 351why, one step back351fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 352why, one step back352<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 353why, one step back353fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 354–355why, one step back354<pre><code>$ NODE_ENV=production node app.js355</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 356–358why, one step back356357<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>358fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 359why, one step back359<h3 id="settings">Settings</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 360–362why, one step back360361<p>Express supports the following settings out of the box:</p>362fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 363–367why, one step back363<ul>364<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>365<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>366<li><em>view engine</em> Default view engine name for views rendered without extensions</li>367<li><em>view options</em> An object specifying global view options</li>docsTj Holowaychukbefore adoption3588c1e
lines 368–369why, one step back368<li><em>view cache</em> Enable view caching (enabled in production)</li>369<li><em>case sensitive routes</em> Enable case-sensitive routing</li>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 370why, one step back370</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 371–372why, one step back371372fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 373–374why, one step back373<h3 id="routing">Routing</h3>374migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 375why, one step back375<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 376–377why, one step back376For example we may want to render a user’s account for the path <em>/user/12</em>, this377can be done by defining the route below. The values associated to the named placeholdersmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 378–380why, one step back378are available as <code>req.params</code>.</p>379380<pre><code>app.get('/user/:id', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 381–383why, one step back381 res.send('user ' + req.params.id);382});383</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 384why, one step back384docsTj Holowaychukbefore adoption3588c1e
line 385why, one step back385<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For examplemigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 386–387why, one step back386when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>387fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 388–389why, one step back388<pre><code>\/user\/([^\/]+)\/?389</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 390–391why, one step back390391<p>Regular expression literals may also be passed for complex uses. Since capturefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 392why, one step back392groups with literal <em>RegExp</em>’s are anonymous we can access them directly <code>req.params</code>. So our first capture group would be <em>req.params[0]</em> and the second would follow as <em>req.params[1]</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 393–395why, one step back393394<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){395 res.send(req.params);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 396–397why, one step back396});397</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 398–407why, one step back398399<p>Curl requests against the previously defined route:</p>400401<pre><code> $ curl http://dev:3000/user402 [null,null]403 $ curl http://dev:3000/users404 [null,null]405 $ curl http://dev:3000/users/1406 ["1",null]407 $ curl http://dev:3000/users/1..15fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 408–409why, one step back408 ["1","15"]409</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 410–443why, one step back410411<p>Below are some route examples, and the associated paths that they412may consume:</p>413414<pre><code> "/user/:id"415 /user/12416417 "/users/:id?"418 /users/5419 /users420421 "/files/*"422 /files/jquery.js423 /files/javascripts/jquery.js424425 "/file/*.*"426 /files/jquery.js427 /files/javascripts/jquery.js428429 "/user/:id/:operation?"430 /user/1431 /user/1/edit432433 "/products.:format"434 /products.json435 /products.xml436437 "/products.:format?"438 /products.json439 /products.xml440 /products441442 "/user/:id.:format?"443 /user/12fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 444–445why, one step back444 /user/12.json445</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 446–457why, one step back446447<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>448449<pre><code>var express = require('express')450 , app = express.createServer();451452app.use(express.bodyParser());453454app.post('/', function(req, res){455 res.send(req.body);456});457fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 458–459why, one step back458app.listen(3000);459</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 460why, one step back460docsTj Holowaychukbefore adoption3588c1e
line 461why, one step back461<p>Typically we may use a “dumb” placeholder such as “/user/:id” which has no restrictions, however say for example we are limiting a user id to digits, we may use <em>‘/user/:id([0-9]+)’</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 462why, one step back462fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 463why, one step back463<h3 id="passing-route control">Passing Route Control</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 464–469why, one step back464465<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,466the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,467and 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>468469<pre><code>app.get('/users/:id?', function(req, res, next){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 470–475why, one step back470 var id = req.params.id;471 if (id) {472 // do something473 } else {474 next();475 }migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 476–478why, one step back476});477478app.get('/users', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 479–481why, one step back479 // do something else480});481</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 482–514why, one step back482483<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>484485<pre><code>var express = require('express')486 , app = express.createServer();487488var users = [{ name: 'tj' }];489490app.all('/user/:id/:op?', function(req, res, next){491 req.user = users[req.params.id];492 if (req.user) {493 next();494 } else {495 next(new Error('cannot find user ' + req.params.id));496 }497});498499app.get('/user/:id', function(req, res){500 res.send('viewing ' + req.user.name);501});502503app.get('/user/:id/edit', function(req, res){504 res.send('editing ' + req.user.name);505});506507app.put('/user/:id', function(req, res){508 res.send('updating ' + req.user.name);509});510511app.get('*', function(req, res){512 res.send('what???', 404);513});514fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 515–516why, one step back515app.listen(3000); 516</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 517why, one step back517fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 518why, one step back518<h3 id="middleware">Middleware</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 519–525why, one step back519520<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be521passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>522523<pre><code> var express = require('express');524525var app = express.createServer(fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 526–529why, one step back526 express.logger()527 , express.bodyParser()528 );529</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 530–532why, one step back530531<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>532generate docsTj Holowaychukbefore adoptionff7d5ff
line 533why, one step back533<pre><code>app.use(express.logger({ format: ':method :url' }));fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 534why, one step back534</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 535why, one step back535fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 536why, one step back536<p>Typically with connect middleware you would <em>require(‘connect’)</em> like so:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 537–539why, one step back537538<pre><code>var connect = require('connect');539app.use(connect.logger());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 540–541why, one step back540app.use(connect.bodyParser());541</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 542–545why, one step back542543<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>544545<pre><code>app.use(express.logger());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 546–547why, one step back546app.use(express.bodyParser());547</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 548why, one step back548docsTj Holowaychukbefore adoption3588c1e
lines 549–576why, one step back549<p>Middleware ordering is important, when Connect receives a request the <em>first</em> middleware we pass to <em>createServer()</em> or <em>use()</em> is executed with three parameters, <em>request</em>, <em>response</em>, and a callback function usually named <em>next</em>. When <em>next()</em> is invoked the second middleware will then have it’s turn and so on. This is important to note because many middleware depend on each other, for example <em>methodOverride()</em> checks <em>req.body.</em>method<em> for the HTTP method override, however </em>bodyParser()<em> parses the request body and populates </em>req.body<em>. Another example of this is cookie parsing and session support, we must first </em>use()<em> </em>cookieParser()<em> followed by </em>session()_.</p>550551<p>Many Express applications may contain the line <em>app.use(app.router)</em>, while this may appear strange, it’s simply the middleware function that contains all defined routes, and performs route lookup based on the current request url and HTTP method. Express allows you to position this middleware, though by default it will be added to the bottom. By positioning the router, we can alter middleware precedence, for example we may want to add error reporting as the <em>last</em> middleware so that any exception passed to <em>next()</em> will be handled by it, or perhaps we want static file serving to have low precedence, allowing our routes to intercept requests to a static file to count downloads etc. This may look a little like below</p>552553<pre><code>app.use(express.logger(...));554app.use(express.bodyParser(...));555app.use(express.cookieParser(...));556app.use(express.session(...));557app.use(app.router);558app.use(express.static(...));559app.use(express.errorHandler(...));560</code></pre>561562<p>First we add <em>logger()</em> so that it may wrap node’s <em>req.end()</em> method, providing us with response-time data. Next the request’s body will be parsed (if any), followed by cookie parsing and session support, meaning <em>req.session</em> will be defined by the time we hit our routes in <em>app.router</em>. If a request such as <em>GET /javascripts/jquery.js</em> is handled by our routes, and we do not call <em>next()</em> then the <em>static()</em> middleware will never see this request, however if were to define a route as shown below, we can record stats, refuse downloads, consume download credits etc.</p>563564<pre><code>var downloads = {};565566app.use(app.router);567app.use(express.static(__dirname + '/public'));568569app.get('/*', function(req, res, next){570 var file = req.params[0];571 downloads[file] = downloads[file] || 0;572 downloads[file]++;573 next();574});575</code></pre>576fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 577why, one step back577<h3 id="route-middleware">Route Middleware</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 578–580why, one step back578579<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>580fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 581why, one step back581<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 582–587why, one step back582583<pre><code>app.get('/user/:id', function(req, res, next){584 loadUser(req.params.id, function(err, user){585 if (err) return next(err);586 res.send('Viewing user ' + user.name);587 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 588–589why, one step back588});589</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 590why, one step back590fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 591why, one step back591<p>To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 592–605why, one step back592593<pre><code>function loadUser(req, res, next) {594 // You would fetch your user from the db595 var user = users[req.params.id];596 if (user) {597 req.user = user;598 next();599 } else {600 next(new Error('Failed to load user ' + req.params.id));601 }602}603604app.get('/user/:id', loadUser, function(req, res){605 res.send('Viewing user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 606–607why, one step back606});607</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 608–618why, one step back608609<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>610611<pre><code>function andRestrictToSelf(req, res, next) {612 req.authenticatedUser.id == req.user.id613 ? next()614 : next(new Error('Unauthorized'));615}616617app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){618 res.send('Editing user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 619–620why, one step back619});620</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 621–633why, one step back621622<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>623624<pre><code>function andRestrictTo(role) {625 return function(req, res, next) {626 req.authenticatedUser.role == role627 ? next()628 : next(new Error('Unauthorized'));629 }630}631632app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){633 res.send('Deleted user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 634–635why, one step back634});635</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 636why, one step back636fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 637why, one step back637<p>Commonly used “stacks” of middleware can be passed as an array (<em>applied recursively</em>), which can be mixed and matched to any degree.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 638–647why, one step back638639<pre><code>var a = [middleware1, middleware2]640 , b = [middleware3, middleware4]641 , all = [a, b];642643app.get('/foo', a, function(){});644app.get('/bar', a, function(){});645646app.get('/', a, middleware3, middleware4, function(){});647app.get('/', a, b, function(){});fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 648–649why, one step back648app.get('/', all, function(){});649</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 650–652why, one step back650651<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>652docsTj Holowaychukbefore adoption3588c1e
lines 653–654why, one step back653<p>There are times when we may want to “skip” passed remaining route middleware, but continue matching subsequent routes. To do this we invoke <code>next()</code> with the string “route” <code>next('route')</code>. If no remaining routes match the request url then Express will respond with 404 Not Found.</p>654fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 655why, one step back655<h3 id="http-methods">HTTP Methods</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 656–658why, one step back656657<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>658fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 659why, one step back659<p> A common example for <em>POST</em> usage, is when “submitting” a form. Below we simply set our form method to “post” in our html, and control will be given to the route we have defined below it.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 660–664why, one step back660661<pre><code> <form method="post" action="/">662 <input type="text" name="user[name]" />663 <input type="text" name="user[email]" />664 <input type="submit" value="Submit" />fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 665–666why, one step back665 </form>666</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 667why, one step back667fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 668why, one step back668<p>By default Express does not know what to do with this request body, so we should add the <em>bodyParser</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> and <em>application/json</em> request bodies and place the variables in <em>req.body</em>. We can do this by “using” the middleware as shown below:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 669why, one step back669fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 670–671why, one step back670<pre><code>app.use(express.bodyParser());671</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 672–677why, one step back672673<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>674675<pre><code>app.post('/', function(req, res){676 console.log(req.body.user);677 res.redirect('back');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 678–679why, one step back678});679</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 680why, one step back680fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 681why, one step back681<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyParser</em> so that it can utilize it’s <em>req.body</em> containing the form values.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 682–683why, one step back682683<pre><code>app.use(express.bodyParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 684–685why, one step back684app.use(express.methodOverride());685</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 686–698why, one step back686687<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>688689<pre><code><form method="post" action="/">690 <input type="hidden" name="_method" value="put" />691 <input type="text" name="user[name]" />692 <input type="text" name="user[email]" />693 <input type="submit" value="Submit" /> 694</form>695696app.put('/', function(){697 console.log(req.body.user);698 res.redirect('back');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 699–700why, one step back699});700</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 701why, one step back701fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 702why, one step back702<h3 id="error-handling">Error Handling</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 703–713why, one step back703704<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,705or passed to <em>next(err)</em>. Below is an example which serves different pages based on our706ad-hoc <em>NotFound</em> exception:</p>707708<pre><code>function NotFound(msg){709 this.name = 'NotFound';710 Error.call(this, msg);711 Error.captureStackTrace(this, arguments.callee);712}713fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 714why, one step back714NotFound.prototype.__proto__ = Error.prototype;migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 715–721why, one step back715716app.get('/404', function(req, res){717 throw new NotFound;718});719720app.get('/500', function(req, res){721 throw new Error('keyboard cat!');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 722–723why, one step back722});723</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 724–729why, one step back724725<p>We can call <em>app.error()</em> several times as shown below.726Here we check for an instanceof <em>NotFound</em> and show the727404 page, or we pass on to the next error handler.</p>728729<p>Note that these handlers can be defined anywhere, as theyfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 730why, one step back730will be placed below the route handlers on <em>listen()</em>. Thismigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 731–739why, one step back731allows for definition within <em>configure()</em> blocks so we can732handle exceptions in different ways based on the environment.</p>733734<pre><code>app.error(function(err, req, res, next){735 if (err instanceof NotFound) {736 res.render('404.jade');737 } else {738 next(err);739 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 740–741why, one step back740});741</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 742–743why, one step back742743<p>Here we assume all errors as 500 for the simplicity offixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 744why, one step back744this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the <em>error.code</em> of <em>ENOENT</em>, meaning “no such file or directory”, we can utilize this in our error handling and display a page specific to this if desired.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 745–749why, one step back745746<pre><code>app.error(function(err, req, res){747 res.render('500.jade', {748 error: err749 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 750–751why, one step back750});751</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 752–753why, one step back752753<p>Our apps could also utilize the Connect <em>errorHandler</em> middlewarefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 754–755why, one step back754to report on exceptions. For example if we wish to output exceptions755in “development” mode to <em>stderr</em> we can use:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 756why, one step back756fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 757–758why, one step back757<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));758</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 759–762why, one step back759760<p>Also during development we may want fancy html pages to show exceptions761that are passed or thrown, so we can set <em>showStack</em> to true:</p>762fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 763–764why, one step back763<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));764</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 765–768why, one step back765766<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>767is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>768fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 769why, one step back769<h3 id="route-param pre-conditions">Route Param Pre-conditions</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 770–777why, one step back770771<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>772773<pre><code>app.get('/user/:userId', function(req, res, next){774 User.get(req.params.userId, function(err, user){775 if (err) return next(err);776 res.send('user ' + user.name);777 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 778–779why, one step back778}); 779</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 780–789why, one step back780781<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>782783<pre><code>app.param('userId', function(req, res, next, id){784 User.get(id, function(err, user){785 if (err) return next(err);786 if (!user) return next(new Error('failed to find user'));787 req.user = user;788 next();789 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 790–791why, one step back790});791</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 792–796why, one step back792793<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>794795<pre><code>app.get('/user/:userId', function(req, res){796 res.send('user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 797–798why, one step back797});798</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 799why, one step back799fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 800why, one step back800<h3 id="view-rendering">View Rendering</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 801why, one step back801fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 802why, one step back802<p>View filenames take the form “<name>.<engine>”, where <engine> is the namemigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 803why, one step back803of 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 804–805why, one step back804tell 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 behaviour805<em>app.register()</em> can be used to map engines to file extensions, so that for example “foo.html” can be rendered by ejs.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 806–807why, one step back806807<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 808why, one step back808and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed asmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 809–811why, one step back809the <em>body</em> local variable in <em>layout.jade</em>.</p>810811<pre><code>app.get('/', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 812–814why, one step back812 res.render('index.jade', { title: 'My Site' });813});814</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 815–818why, one step back815816<p>The new <em>view engine</em> setting allows us to specify our default template engine,817so for example when using jade we could set:</p>818fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 819–820why, one step back819<pre><code>app.set('view engine', 'jade');820</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 821–823why, one step back821822<p>Allowing us to render with:</p>823fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 824–825why, one step back824<pre><code>res.render('index');825</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 826–828why, one step back826827<p>vs:</p>828fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 829–830why, one step back829<pre><code>res.render('index.jade');830</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 831–834why, one step back831832<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still833mix and match template engines:</p>834fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 835–836why, one step back835<pre><code>res.render('another-page.ejs');836</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 837–841why, one step back837838<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>839840<pre><code>app.set('view options', {841 layout: falsefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 842–843why, one step back842});843</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 844–846why, one step back844845<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>846fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 847–848why, one step back847<pre><code>res.render('myview.ejs', { layout: true });848</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 849–851why, one step back849850<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>851fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 852–853why, one step back852<pre><code>res.render('page', { layout: 'mylayout' });853</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 854–856why, one step back854855<p>Otherwise we must specify the extension:</p>856fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 857–858why, one step back857<pre><code>res.render('page', { layout: 'mylayout.jade' });858</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 859–861why, one step back859860<p>These paths may also be absolute:</p>861fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 862–863why, one step back862<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });863</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 864–869why, one step back864865<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>866867<pre><code>app.set('view options', {868 open: '{{',869 close: '}}'fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 870–871why, one step back870});871</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 872why, one step back872fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 873why, one step back873<h3 id="view-partials">View Partials</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 874why, one step back874fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 875why, one step back875<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 876why, one step back876in a view to display comments, we could use partial collection:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 877why, one step back877fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 878–879why, one step back878<pre><code>partial('comment', { collection: comments });879</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 880why, one step back880regenerated docsTj Holowaychukbefore adoptiondd7158a
line 881why, one step back881<p>If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 882why, one step back882fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 883–884why, one step back883<pre><code>partial('comment', comments);884</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 885why, one step back885fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 886why, one step back886<p>When using the partial collection support a few “magic” locals are providedmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 887–888why, one step back887for free:</p>888fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 889–894why, one step back889<ul>890<li><em>firstInCollection</em> true if this is the first object</li>891<li><em>indexInCollection</em> index of the object in the collection</li>892<li><em>lastInCollection</em> true if this is the last object</li>893<li><em>collectionLength</em> length of the collection</li>894</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 895–896why, one step back895896fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 897–898why, one step back897<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>898migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 899–902why, one step back899<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>900901<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>902fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 903why, one step back903<h3 id="view-lookup">View Lookup</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 904why, one step back904fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 905why, one step back905<p>View lookup is performed relative to the parent view, for example if we had a page view named <em>views/user/list.jade</em>, and within that view we did <em>partial(‘edit’)</em> it would attempt to load <em>views/user/edit.jade</em>, whereas <em>partial(‘../messages’)</em> would load <em>views/messages.jade</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 906why, one step back906fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 907why, one step back907<p>The view system also allows for index templates, allowing you to have a directory of the same name. For example within a route we may have <em>res.render(‘users’)</em> either <em>views/users.jade</em>, or <em>views/users/index.jade</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 908why, one step back908fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 909why, one step back909<p>When utilizing index views as shown above, we may reference <em>views/users/index.jade</em> from a view in the same directory by <em>partial(‘users’)</em>, and the view system will try <em>../users/index</em>, preventing us from needing to call <em>partial(‘index’)</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 910why, one step back910fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 911why, one step back911<h3 id="template-engines">Template Engines</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 912–914why, one step back912913<p>Below are a few template engines commonly used with Express:</p>914fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 915–921why, one step back915<ul>916<li><a href="http://github.com/visionmedia/haml.js">Haml</a> haml implementation</li>917<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>918<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>919<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>920<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>921</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 922–923why, one step back922923fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 924why, one step back924<h3 id="session-support">Session Support</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 925why, one step back925fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 926–927why, one step back926<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>927migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 928why, one step back928<pre><code>app.use(express.cookieParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 929–930why, one step back929app.use(express.session({ secret: "keyboard cat" }));930</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 931–933why, one step back931932<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>933Merge pull request #706 from jakeg/patch-1TJ Holowaychukbefore adoptionf4f79d2
line 934why, one step back934<pre><code>var RedisStore = require('connect-redis')(express);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 935why, one step back935app.use(express.cookieParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 936–937why, one step back936app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));937</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 938–940why, one step back938939<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>940Merge pull request #706 from jakeg/patch-1TJ Holowaychukbefore adoptionf4f79d2
line 941why, one step back941<pre><code>var RedisStore = require('connect-redis')(express);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 942–961why, one step back942app.use(express.bodyParser());943app.use(express.cookieParser());944app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));945946app.post('/add-to-cart', function(req, res){947 // Perhaps we posted several items with a form948 // (use the bodyParser() middleware for this)949 var items = req.body.items;950 req.session.items = items;951 res.redirect('back');952});953954app.get('/add-to-cart', function(req, res){955 // When redirected back to GET /add-to-cart956 // we could check req.session.items && req.session.items.length957 // to print out a message958 if (req.session.items && req.session.items.length) {959 req.flash('info', 'You have %s items in your cart', req.session.items.length);960 }961 res.render('shopping-cart');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 962–963why, one step back962});963</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 964–966why, one step back964965<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>966fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 967why, one step back967<h3 id="migration-guide">Migration Guide</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 968–970why, one step back968969<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>970fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 971why, one step back971<h3 id="req.header()">req.header(key[, defaultValue])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 972–976why, one step back972973<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>974975<pre><code>req.header('Host');976req.header('host');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 977–978why, one step back977req.header('Accept', '*/*');978</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 979–987why, one step back979980<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>981982<pre><code>// sent Referrer: http://google.com983984req.header('Referer');985// => "http://google.com"986987req.header('Referrer');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 988–989why, one step back988// => "http://google.com"989</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 990why, one step back990fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 991why, one step back991<h3 id="req.accepts()">req.accepts(type)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 992–996why, one step back992993<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>994995<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise996the 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 997–998why, one step back997may pass the subtype such as “html” which is then converted internally998to “text/html” using the mime lookup table.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 999–1012why, one step back9991000<pre><code>// Accept: text/html1001req.accepts('html');1002// => true10031004// Accept: text/*; application/json1005req.accepts('html');1006req.accepts('text/html');1007req.accepts('text/plain');1008req.accepts('application/json');1009// => true10101011req.accepts('image/png');1012req.accepts('png');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1013–1014why, one step back1013// => false1014</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1015why, one step back1015fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1016why, one step back1016<h3 id="req.is()">req.is(type)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1017–1031why, one step back10171018<p>Check if the incoming request contains the <em>Content-Type</em>1019header field, and it contains the give mime <em>type</em>.</p>10201021<pre><code> // With Content-Type: text/html; charset=utf-81022 req.is('html');1023 req.is('text/html');1024 // => true10251026 // When Content-Type is application/json1027 req.is('json');1028 req.is('application/json');1029 // => true10301031 req.is('html');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1032–1033why, one step back1032 // => false1033</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1034–1036why, one step back10341035<p>Ad-hoc callbacks can also be registered with Express, to perform1036assertions again the request, for example if we need an expressivefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1037why, one step back1037way to check if our incoming request is an image, we can register <em>“an image”</em>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1038–1041why, one step back1038callback:</p>10391040<pre><code> app.is('an image', function(req){1041 return 0 == req.headers['content-type'].indexOf('image');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1042–1043why, one step back1042 });1043</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1044–1045why, one step back10441045<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 1046why, one step back1046such as <em>“image/jpeg”</em>, <em>“image/png”</em>, etc.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1047–1053why, one step back10471048<pre><code> app.post('/image/upload', function(req, res, next){1049 if (req.is('an image')) {1050 // do something1051 } else {1052 next();1053 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1054–1055why, one step back1054 });1055</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1056–1059why, one step back10561057<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you1058can perform any request assertion you wish.</p>1059fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1060why, one step back1060<p>Wildcard matches can also be made, simplifying our example above for <em>“an image”</em>, by asserting the <em>subtype</em> only:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1061why, one step back1061fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1062–1063why, one step back1062<pre><code>req.is('image/*');1063</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1064why, one step back1064fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1065why, one step back1065<p>We may also assert the <em>type</em> as shown below, which would return true for <em>“application/json”</em>, and <em>“text/json”</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1066why, one step back1066fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1067–1068why, one step back1067<pre><code>req.is('*/json');1068</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1069why, one step back1069fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1070why, one step back1070<h3 id="req.param()">req.param(name[, default])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1071–1073why, one step back10711072<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>1073fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1074–1078why, one step back1074<ul>1075<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>1076<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1077<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1078</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1079why, one step back1079fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1080why, one step back1080migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1081–1084why, one step back1081<p>To utilize urlencoded request bodies, <em>req.body</em>1082should be an object. This can be done by using1083the _express.bodyParser middleware.</p>1084fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1085why, one step back1085<h3 id="req.flash()">req.flash(type[, msg])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1086–1100why, one step back10861087<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>10881089<pre><code>req.flash('info', 'email sent');1090req.flash('error', 'email delivery failed');1091req.flash('info', 'email re-sent');1092// => 210931094req.flash('info');1095// => ['email sent', 'email re-sent']10961097req.flash('info');1098// => []10991100req.flash();fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1101–1102why, one step back1101// => { error: ['email delivery failed'], info: [] }1102</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1103–1105why, one step back11031104<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>1105fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1106–1107why, one step back1106<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1107</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1108why, one step back1108fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1109why, one step back1109<h3 id="req.isxmlhttprequest">req.isXMLHttpRequest</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1110–1114why, one step back11101111<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1112to see if it was issued by an <em>XMLHttpRequest</em>:</p>11131114<pre><code>req.xhrfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1115–1116why, one step back1115req.isXMLHttpRequest1116</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1117why, one step back1117fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1118why, one step back1118<h3 id="res.header()">res.header(key[, val])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1119–1128why, one step back11191120<p>Get or set the response header <em>key</em>.</p>11211122<pre><code>res.header('Content-Length');1123// => undefined11241125res.header('Content-Length', 123);1126// => 12311271128res.header('Content-Length');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1129–1130why, one step back1129// => 1231130</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1131why, one step back1131fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1132why, one step back1132<h3 id="res.charset">res.charset</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1133why, one step back1133fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1134why, one step back1134<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 1135–1136why, one step back11351136<pre><code>res.charset = 'ISO-8859-1';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1137–1138why, one step back1137res.render('users');1138</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1139–1142why, one step back11391140<p>or before responding with <code>res.send()</code>:</p>11411142<pre><code>res.charset = 'ISO-8859-1';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1143–1144why, one step back1143res.send(str);1144</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1145why, one step back1145fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1146why, one step back1146<p>or with node’s <code>res.end()</code>:</p>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1147–1149why, one step back11471148<pre><code>res.charset = 'ISO-8859-1';1149res.header('Content-Type', 'text/plain');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1150–1151why, one step back1150res.end(str);1151</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1152why, one step back1152fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1153why, one step back1153<h3 id="res.contenttype()">res.contentType(type)</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1154why, one step back1154migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1155–1158why, one step back1155<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>11561157<pre><code> var filename = 'path/to/image.png';1158 res.contentType(filename);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1159–1160why, one step back1159 // Content-Type is now "image/png"1160</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1161why, one step back1161regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1162why, one step back1162<p>A literal <em>Content-Type</em> works as well:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1163why, one step back1163fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1164–1165why, one step back1164<pre><code> res.contentType('application/json');1165</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1166–1168why, one step back11661167<p>Or simply the extension without leading <code>.</code>:</p>1168fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1169–1170why, one step back1169<pre><code> res.contentType('json');1170</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1171why, one step back1171fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1172why, one step back1172<h3 id="res.attachment()">res.attachment([filename])</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1173why, one step back1173fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1174why, one step back1174<p>Sets the <em>Content-Disposition</em> response header to “attachment”, with optional <em>filename</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1175why, one step back1175fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1176–1177why, one step back1176<pre><code> res.attachment('path/to/my/image.png');1177</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1178why, one step back1178fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1179why, one step back1179<h3 id="res.sendfile()">res.sendfile(path[, options[, callback]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1180why, one step back1180fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1181why, one step back1181<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1182why, one step back1182fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1183–1184why, one step back1183<pre><code>res.sendfile('path/to/my.file');1184</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1185–1194why, one step back11851186<p>This method accepts an optional callback which is called when1187an 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>11881189<pre><code>res.sendfile(path, function(err){1190 if (err) {1191 next(err);1192 } else {1193 console.log('transferred %s', path);1194 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1195–1196why, one step back1195});1196</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1197–1201why, one step back11971198<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>11991200<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1201 // handlefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1202–1203why, one step back1202});1203</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1204why, one step back1204docsTj Holowaychukbefore adoption3588c1e
line 1205why, one step back1205<h3 id="res.download()">res.download(file[, filename[, callback[, callback2]]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1206–1209why, one step back12061207<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>12081209<pre><code>res.download('path/to/image.png');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1210–1211why, one step back1210res.download('path/to/image.png', 'foo.png');1211</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1212–1215why, one step back12121213<p>This is equivalent to:</p>12141215<pre><code>res.attachment(file);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1216–1217why, one step back1216res.sendfile(file);1217</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1218why, one step back1218docsTj Holowaychukbefore adoption3588c1e
line 1219why, one step back1219<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>. Within this callback you may still respond, as the header has not been sent.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1220–1222why, one step back12201221<pre><code>res.download(path, 'expenses.doc', function(err){1222 // handlefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1223–1224why, one step back1223});1224</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1225why, one step back1225docsTj Holowaychukbefore adoption3588c1e
lines 1226–1234why, one step back1226<p>An optional second callback, <em>callback2</em> may be given to allow you to act on connection related errors, however you should not attempt to respond.</p>12271228<pre><code>res.download(path, function(err){1229 // error or finished1230}, function(err){1231 // connection related error1232});1233</code></pre>1234fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1235why, one step back1235<h3 id="res.send()">res.send(body|status[, headers|status[, status]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1236–1245why, one step back12361237<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1238objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>12391240<pre><code> res.send(); // 2041241 res.send(new Buffer('wahoo'));1242 res.send({ some: 'json' });1243 res.send('<p>some html</p>');1244 res.send('Sorry, cant find that', 404);1245 res.send('text', { 'Content-Type': 'text/plain' }, 201);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1246–1247why, one step back1246 res.send(404);1247</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1248–1252why, one step back12481249<p>By default the <em>Content-Type</em> response header is set, however if explicitly1250assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1251it will not be set again.</p>1252fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1253why, one step back1253<p>Note that this method <em>end()</em>s the response, so you will want to use node’s <em>res.write()</em> for multiple writes or streaming.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1254why, one step back1254fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1255why, one step back1255<h3 id="res.redirect()">res.redirect(url[, status])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1256–1262why, one step back12561257<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>12581259<pre><code>res.redirect('/', 301);1260res.redirect('/account');1261res.redirect('http://google.com');1262res.redirect('home');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1263–1264why, one step back1263res.redirect('back');1264</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1265why, one step back1265fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1266why, one step back1266<p>Express supports “redirect mapping”, which by default provides <em>home</em>, and <em>back</em>.migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1267why, one step back1267The <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 1268why, one step back1268the “home” setting and defaults to “/”.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1269why, one step back1269fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1270why, one step back1270<h3 id="res.cookie()">res.cookie(name, val[, options])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1271–1274why, one step back12711272<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>12731274<pre><code>// "Remember me" for 15 minutes fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1275–1276why, one step back1275res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1276</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1277–1279why, one step back12771278<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>1279fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1280–1281why, one step back1280<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });1281</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1282why, one step back1282updated docsTj Holowaychukbefore adoption99b49d2
line 1283why, one step back1283<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieParser</em> middleware, which provides the <em>req.cookies</em> object:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1284–1288why, one step back12841285<pre><code>app.use(express.cookieParser());12861287app.get('/', function(req, res){1288 // use req.cookies.remembermefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1289–1290why, one step back1289});1290</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1291why, one step back1291docsTj Holowaychukbefore adoption3588c1e
line 1292why, one step back1292<h3 id="res.clearcookie()">res.clearCookie(name[, options])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1293why, one step back1293fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1294why, one step back1294<p>Clear cookie <em>name</em> by setting “expires” far in the past.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1295why, one step back1295fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1296–1297why, one step back1296<pre><code>res.clearCookie('rememberme');1297</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1298why, one step back1298fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1299why, one step back1299<h3 id="res.render()">res.render(view[, options[, fn]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1300–1304why, one step back13001301<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1302When a callback function is given a response will <em>not</em> be made1303automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>1304fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1305why, one step back1305<p>The <em>options</em> passed are the local variables as well, for example if we want to expose “user” to the view, and prevent a local we do so within the same object:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1306–1307why, one step back13061307<pre><code>var user = { name: 'tj' };fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1308–1309why, one step back1308res.render('index', { layout: false, user: user });1309</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1310why, one step back1310fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1311why, one step back1311<h3 id="res.partial()">res.partial(view[, options])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1312–1315why, one step back13121313<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1314to the view as a local variable.</p>1315fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1316–1318why, one step back1316<ul>1317<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1318<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1319why, one step back1319fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1320–1330why, one step back1320<ul>1321<li>as: ‘something’ will add the <em>something</em> local variable</li>1322<li>as: this will use the collection value as the template context</li>1323<li>as: global will merge the collection value’s properties with <em>locals</em></li>1324</ul>1325</li>1326<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1327For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1328</ul>13291330migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1331–1338why, one step back1331<p>The following are equivalent, and the name of collection value when passed1332to the partial will be <em>movie</em> as derived from the name.</p>13331334<pre><code>partial('theatre/movie.jade', { collection: movies });1335partial('theatre/movie.jade', movies);1336partial('movie.jade', { collection: movies });1337partial('movie.jade', movies);1338partial('movie', movies);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1339–1340why, one step back1339// In view: movie.director1340</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1341why, one step back1341fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1342why, one step back1342<p>To change the local from <em>movie</em> to <em>video</em> we can use the “as” option:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1343–1344why, one step back13431344<pre><code>partial('movie', { collection: movies, as: 'video' });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1345–1346why, one step back1345// In view: video.director1346</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1347–1351why, one step back13471348<p>Also we can make our movie the value of <em>this</em> within our view so that instead1349of <em>movie.director</em> we could use <em>this.director</em>.</p>13501351<pre><code>partial('movie', { collection: movies, as: this });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1352–1353why, one step back1352// In view: this.director1353</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1354why, one step back1354fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1355why, one step back1355<p>Another alternative is to “expand” the properties of the collection item intomigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1356–1358why, one step back1356pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>13571358<pre><code>partial('movie', { collection: movies, as: global });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1359–1360why, one step back1359// In view: director1360</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1361–1373why, one step back13611362<p>This same logic applies to a single partial object usage:</p>13631364<pre><code>partial('movie', { object: movie, as: this });1365// In view: this.director13661367partial('movie', { object: movie, as: global });1368// In view: director13691370partial('movie', { object: movie, as: 'video' });1371// In view: video.director13721373partial('movie', { object: movie });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1374–1375why, one step back1374// In view: movie.director1375</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1376why, one step back1376fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1377why, one step back1377<p>When a non-collection (does <em>not</em> have <em>.length</em>) is passed as the second argument, it is assumed to be the <em>object</em>, after which the object’s local variable name is derived from the view name:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1378why, one step back1378regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1379–1380why, one step back1379<pre><code>var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1380partial('movie', movie)fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1381–1382why, one step back1381// => In view: movie.director1382</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1383why, one step back1383fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1384why, one step back1384<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 1385–1386why, one step back13851386<pre><code>var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1387–1388why, one step back1387partial('movie', movie)1388</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1389–1393why, one step back13891390<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>13911392<pre><code> partial('movie', { locals: { movie: movie }})1393 partial('movie', { movie: movie })fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1394–1395why, one step back1394 partial('movie', { object: movie })1395</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1396why, one step back1396migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1397–1409why, one step back1397<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>13981399<pre><code>app.get('/users', function(req, res){1400 if (req.xhr) {1401 // respond with the each user in the collection1402 // passed to the "user" view1403 res.partial('user', users);1404 } else {1405 // respond with layout, and users page1406 // which internally does partial('user', users)1407 // along with other UI1408 res.render('users', { users: users });1409 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1410–1411why, one step back1410});1411</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1412why, one step back1412fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1413why, one step back1413<h3 id="res.local()">res.local(name[, val])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1414–1427why, one step back14141415<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>14161417<pre><code> app.all('/movie/:id', function(req, res, next){1418 Movie.get(req.params.id, function(err, movie){1419 // Assigns res.locals.movie = movie1420 res.local('movie', movie);1421 });1422 });14231424 app.get('/movie/:id', function(req, res){1425 // movie is already a local, however we1426 // can pass more if we wish1427 res.render('movie', { displayReviews: true });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1428–1429why, one step back1428 });1429</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1430why, one step back1430fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1431why, one step back1431<h3 id="res.locals()">res.locals(obj)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1432why, one step back1432regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1433–1437why, one step back1433<p> Assign several locals with the given <em>obj</em>. The following are equivalent:</p>14341435<pre><code> res.local('foo', bar);1436 res.local('bar', baz);1437fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1438–1439why, one step back1438 res.locals({ foo: bar, bar, baz });1439</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1440why, one step back1440fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1441why, one step back1441<h3 id="app.set()">app.set(name[, val])</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1442why, one step back1442migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1443–1447why, one step back1443<p>Apply an application level setting <em>name</em> to <em>val</em>, or1444get the value of <em>name</em> when <em>val</em> is not present:</p>14451446<pre><code>app.set('views', __dirname + '/views');1447app.set('views');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1448–1449why, one step back1448// => ...path...1449</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1450–1453why, one step back14501451<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>14521453<pre><code>app.settings.viewsfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1454–1455why, one step back1454// => ...path...1455</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1456why, one step back1456fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1457why, one step back1457<h3 id="app.enable()">app.enable(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1458–1465why, one step back14581459<p>Enable the given setting <em>name</em>:</p>14601461<pre><code>app.enable('some arbitrary setting');1462app.set('some arbitrary setting');1463// => true14641465app.enabled('some arbitrary setting');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1466–1467why, one step back1466// => true1467</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1468why, one step back1468fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1469why, one step back1469<h3 id="app.enabled()">app.enabled(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1470–1477why, one step back14701471<p>Check if setting <em>name</em> is enabled:</p>14721473<pre><code>app.enabled('view cache');1474// => false14751476app.enable('view cache');1477app.enabled('view cache');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1478–1479why, one step back1478// => true1479</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1480why, one step back1480fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1481why, one step back1481<h3 id="app.disable()">app.disable(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1482–1489why, one step back14821483<p>Disable the given setting <em>name</em>:</p>14841485<pre><code>app.disable('some setting');1486app.set('some setting');1487// => false14881489app.disabled('some setting');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1490–1491why, one step back1490// => false1491</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1492why, one step back1492fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1493why, one step back1493<h3 id="app.disabled()">app.disabled(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1494–1503why, one step back14941495<p>Check if setting <em>name</em> is disabled:</p>14961497<pre><code>app.enable('view cache');14981499app.disabled('view cache');1500// => false15011502app.disable('view cache');1503app.disabled('view cache');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1504–1505why, one step back1504// => true1505</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1506why, one step back1506fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1507why, one step back1507<h3 id="app.configure()">app.configure(env|function[, function])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1508–1516why, one step back15081509<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>15101511<pre><code>app.configure(function(){1512 // executed for each env1513});15141515app.configure('development', function(){1516 // executed for 'development' onlyfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1517–1518why, one step back1517});1518</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1519why, one step back1519fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1520why, one step back1520<h3 id="app.redirect()">app.redirect(name, val)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1521–1523why, one step back15211522<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>1523fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1524–1525why, one step back1524<pre><code>app.redirect('google', 'http://google.com');1525</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1526–1528why, one step back15261527<p>Now in a route we may call:</p>1528fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1529why, one step back1529<p> res.redirect(‘google’);</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1530–1534why, one step back15301531<p>We may also map dynamic redirects:</p>15321533<pre><code>app.redirect('comments', function(req, res){1534 return '/post/' + req.params.id + '/comments';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1535–1536why, one step back1535});1536</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1537–1543why, one step back15371538<p>So now we may do the following, and the redirect will dynamically adjust to1539the context of the request. If we called this route with <em>GET /post/12</em> our1540redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>15411542<pre><code>app.get('/post/:id', function(req, res){1543 res.redirect('comments');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1544–1545why, one step back1544});1545</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1546–1548why, one step back15461547<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>1548fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1549–1550why, one step back1549<pre><code>res.redirect('/posts');1550</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1551why, one step back1551fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1552why, one step back1552<h3 id="app.error()">app.error(function)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1553–1559why, one step back15531554<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1555Note that we may set several error handlers by making several calls to this method, however the handler1556should call <em>next(err)</em> if it does not wish to deal with the exception:</p>15571558<pre><code>app.error(function(err, req, res, next){1559 res.send(err.message, 500);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1560–1561why, one step back1560});1561</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1562why, one step back1562fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1563why, one step back1563<h3 id="app.helpers()">app.helpers(obj)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1564–1566why, one step back15641565<p>Registers static view helpers.</p>1566updated docsTj Holowaychukbefore adoption99b49d2
lines 1567–1571why, one step back1567<pre><code>app.helpers({1568 name: function(first, last){ return first + ', ' + last }1569 , firstName: 'tj'1570 , lastName: 'holowaychuk'1571});fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1572–1573why, one step back1572</code></pre>1573migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1574–1576why, one step back1574<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1575as well as the <em>name()</em> function exposed.</p>1576fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1577–1578why, one step back1577<pre><code><%= name(firstName, lastName) %>1578</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1579why, one step back1579updated docsTj Holowaychukbefore adoption99b49d2
lines 1580–1583why, one step back1580<p>Express also provides a few locals by default:</p>15811582<pre><code>- `settings` the app's settings object1583- `filename` the view's filenamedocsTj Holowaychukbefore adoption3588c1e
line 1584why, one step back1584- `layout(path)` specify the layout from within a viewupdated docsTj Holowaychukbefore adoption99b49d2
lines 1585–1588why, one step back1585</code></pre>15861587<p>This method is aliased as <em>app.locals()</em>.</p>1588fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1589why, one step back1589<h3 id="app.dynamichelpers()">app.dynamicHelpers(obj)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1590–1599why, one step back15901591<p>Registers dynamic view helpers. Dynamic view helpers1592are simply functions which accept <em>req</em>, <em>res</em>, and are1593evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1594becomes the local variable it is associated with.</p>15951596<pre><code>app.dynamicHelpers({1597 session: function(req, res){1598 return req.session;1599 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1600–1601why, one step back1600});1601</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1602–1604why, one step back16021603<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>1604fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1605why, one step back1605<pre><code><%= session.name %>updated docsTj Holowaychukbefore adoption99b49d2
lines 1606–1709why, one step back1606</code></pre>16071608<h3 id="app.lookup">app.lookup</h3>16091610<p> The <em>app.lookup</em> http methods returns an array of callback functions1611 associated with the given <em>path</em>.</p>16121613<p> Suppose we define the following routes:</p>16141615<pre><code> app.get('/user/:id', function(){});1616 app.put('/user/:id', function(){});1617 app.get('/user/:id/:op?', function(){});1618</code></pre>16191620<p> We can utilize this lookup functionality to check which routes1621 have been defined, which can be extremely useful for higher level1622 frameworks built on Express.</p>16231624<pre><code> app.lookup.get('/user/:id');1625 // => [Function]16261627 app.lookup.get('/user/:id/:op?');1628 // => [Function]16291630 app.lookup.put('/user/:id');1631 // => [Function]16321633 app.lookup.all('/user/:id');1634 // => [Function, Function]16351636 app.lookup.all('/hey');1637 // => []1638</code></pre>16391640<p> To alias <em>app.lookup.VERB()</em>, we can simply invoke <em>app.VERB()</em>1641 without a callback, as a shortcut, for example the following are1642 equivalent:</p>16431644<pre><code> app.lookup.get('/user');1645 app.get('/user');1646</code></pre>16471648<p> Each function returned has the following properties:</p>16491650<pre><code> var fn = app.get('/user/:id/:op?')[0];16511652 fn.regexp1653 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i16541655 fn.keys1656 // => ['id', 'op']16571658 fn.path1659 // => '/user/:id/:op?'16601661 fn.method1662 // => 'GET'1663</code></pre>16641665<h3 id="app.match">app.match</h3>16661667<p> The <em>app.match</em> http methods return an array of callback functions1668 which match the given <em>url</em>, which may include a query string etc. This1669 is useful when you want reflect on which routes have the opportunity to1670 respond.</p>16711672<p> Suppose we define the following routes:</p>16731674<pre><code> app.get('/user/:id', function(){});1675 app.put('/user/:id', function(){});1676 app.get('/user/:id/:op?', function(){});1677</code></pre>16781679<p> Our match against <strong>GET</strong> will return two functions, since the <em>:op</em>1680 in our second route is optional.</p>16811682<pre><code> app.match.get('/user/1');1683 // => [Function, Function]1684</code></pre>16851686<p> This second call returns only the callback for <em>/user/:id/:op?</em>.</p>16871688<pre><code> app.match.get('/user/23/edit');1689 // => [Function]1690</code></pre>16911692<p> We can also use <em>all()</em> to disregard the http method:</p>16931694<pre><code> app.match.all('/user/20');1695 // => [Function, Function, Function]1696</code></pre>16971698<p> Each function matched has the following properties:</p>16991700<pre><code> var fn = app.match.get('/user/23/edit')[0];17011702 fn.keys1703 // => ['id', 'op']17041705 fn.params1706 // => { id: '23', op: 'edit' }17071708 fn.method1709 // => 'GET'fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1710why, one step back1710</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1711why, one step back1711fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1712why, one step back1712<h3 id="app.mounted()">app.mounted(fn)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1713–1723why, one step back17131714<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>17151716<pre><code>var app = express.createServer(),1717 blog = express.createServer();17181719blog.mounted(function(parent){1720 // parent is app1721 // "this" is blog1722});1723fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1724–1725why, one step back1724app.use(blog);1725</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1726why, one step back1726fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1727why, one step back1727<h3 id="app.register()">app.register(ext, exports)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1728–1729why, one step back17281729<p>Register the given template engine <em>exports</em>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1730why, one step back1730as <em>ext</em>. For example we may wish to map “.html”migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1731–1732why, one step back1731files to jade:</p>1732fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1733–1734why, one step back1733<pre><code> app.register('.html', require('jade'));1734</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1735–1737why, one step back17351736<p>This is also useful for libraries that may not1737match extensions correctly. For example my haml.jsfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1738–1739why, one step back1738library is installed from npm as “hamljs” so instead1739of layout.hamljs, we can register the engine as “.haml”:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1740why, one step back1740fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1741–1742why, one step back1741<pre><code> app.register('.haml', require('haml-js'));1742</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1743–1747why, one step back17431744<p>For engines that do not comply with the Express1745specification, we can also wrap their api this way. Below1746we map <em>.md</em> to render markdown files, rendering the html once1747since it will not change on subsequent calls, and support local substitutionfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1748why, one step back1748in the form of “{name}”.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1749–1758why, one step back17491750<pre><code> app.register('.md', {1751 compile: function(str, options){1752 var html = md.toHTML(str);1753 return function(locals){1754 return html.replace(/\{([^}]+)\}/g, function(_, name){1755 return locals[name];1756 });1757 };1758 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1759–1760why, one step back1759 });1760</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1761why, one step back1761fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1762why, one step back1762<h3 id="app.listen()">app.listen([port[, host]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1763–1764why, one step back17631764<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 1765why, one step back1765connections will be accepted via <em>INADDR_ANY</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1766–1768why, one step back17661767<pre><code>app.listen();1768app.listen(3000);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1769–1770why, one step back1769app.listen(3000, 'n.n.n.n');1770</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1771–1773why, one step back17711772<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>1773fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1774–1775why, one step back1774<pre><code>app.listen('/tmp/express.sock');1775</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1776–1785why, one step back17761777<p>Then try it out:</p>17781779<pre><code>$ telnet /tmp/express.sock1780GET / HTTP/1.117811782HTTP/1.1 200 OK1783Content-Type: text/plain1784Content-Length: 111785fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1786–1787why, one step back1786Hello World1787</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1788–1791why, one step back1788 </div>1789 </div>1790 </body>1791</html>