guide.html
This file
Path
docs/guide.html
1,805 lines · 63.4 KiB · HTML
Last changed by
fixed docs charsetTj Holowaychukbefore adoptionfe6c583
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–3why, one step back1<html>2 <head>3 <title>Express - node web framework</title>fixed docs charsetTj Holowaychukbefore adoptionfe6c583
line 4why, one step back4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 5–182why, one step back5 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>6 <style>7 #tagline {8 margin-left: 75px;9 margin-bottom: 30px;10 color: rgba(255,255,255,0.7); }11 html {12 background: #1c1c1c url(images/bg.tile.jpg); }1314 body {15 margin: 0;16 padding-bottom: 30px;17 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";18 font-size: 14px;19 line-height: 1.5;20 -webkit-font-smoothing: antialiased;21 background: url(images/bg.jpg) 50% 0 no-repeat;22 color: #8b8b8b; }2324 * {25 outline: none; }2627 em {28 color: white; }2930 a img {31 border: none !important; }3233 a {34 font-weight: bold;35 text-decoration: none;36 color: white;37 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;38 -webkit-transition-duration: 0.15s;39 -webkit-transition-timing-function: ease-out; }40 a:hover {41 opacity: 0.8; }4243 h1, h2, h3, h4 {44 margin: 45px 0 0 0;45 color: white;46 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4748 h3 {49 font-size: 18px; }50 h4 {51 margin-left: 10px;52 font-size: 14px;53 }5455 pre {56 margin: 20px 10px;57 padding: 25px 20px;58 background: rgba(0,0,0,0.5);59 border: 1px solid #323232;60 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);62 -webkit-border-radius: 5px;63 -moz-border-radius: 5px; }6465 code {66 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6768 ul {69 margin: 15px 0;70 padding: 0 0 0 35px; }71 ul li {72 margin: 0;73 padding: 2px 0;74 list-style: square; }75 ul li ul {76 margin: 0;77 padding-left: 12px;78 }7980 .man-name, #Express { display:none; }8182 .sect {83 margin-left: 40px; }84 img {85 margin-left: 20px;86 margin-bottom: 15px;87 }8889 #logo {90 display: block;91 margin-left: 30%;92 margin-bottom: 30px;93 width: 194px;94 height: 51px;95 background: url(images/logo.png) 0 0 no-repeat;96 text-indent: -99999px; }97 #logo:hover {98 opacity: 0.7; }99 #logo:active {100 opacity: 0.3; }101102 #ribbon {103 position: fixed;104 top: 0;105 right: 0;106 z-index: 2; }107108 #wrapper {109 width: 100%;110 min-height: 800px;111 background: url(images/top.png) 0 0 repeat-x; }112113 #container {114 margin: 0 auto;115 padding-top: 80px;116 width: 550px; }117118 #toc {119 position: fixed;120 top: 0;121 left: 0;122 margin: 0 0 0 15px;123 padding: 15px;124 height: 100%;125 background: rgba(0,0,0,0.2);126 overflow: auto;127 border-right: 1px solid rgba(255,255,255,0.05);128 }129 #toc li {130 padding: 0;131 list-style: none;132 }133 #toc li a {134 font-size: 11px;135 }136 #menu {137 margin-left: 75px;138 padding: 0;139 padding-bottom: 30px; }140 #menu li {141 display: inline;142 list-style: none; }143 #menu li a {144 display: block;145 float: left;146 margin: 0 2px;147 padding: 3px 15px;148 background: rgba(0,0,0,0.2);149 -webkit-border-radius: 8px;150 -moz-border-radius: 8px;151 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);153 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;154 -webkit-transition-duration: 0.15s;155 -webkit-transition-timing-function: ease-out; }156 #menu li a:hover,157 #menu li a.active {158 background: rgba(0,0,0,0.5); }159 #menu li a:active {160 background: rgba(0,0,0,0.1);161 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);162 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }163 </style>164 <script>165 $(function(){166 $('.section').hide();167 $('.toggle, a.section-title').toggle(function(){168 $(this).siblings('ul').fadeIn(300);169 return false;170 }, function(){171 $(this).siblings('ul').fadeOut(300);172 return false;173 });174 });175 </script>176 </head>177 <body>178 <a href='http://github.com/visionmedia/express'> 179 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 180 </a>181 <div id="wrapper">182 <div id="container"><ul id="toc">fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 183–200why, one step back183<li><a href="#installation">Installation</a></li>184<li><a href="#creating-a server">Creating A Server</a></li>185<li><a href="#creating-an https server">Creating An HTTPS Server</a></li>186<li><a href="#configuration">Configuration</a></li>187<li><a href="#settings">Settings</a></li>188<li><a href="#routing">Routing</a></li>189<li><a href="#passing-route control">Passing Route Control</a></li>190<li><a href="#middleware">Middleware</a></li>191<li><a href="#route-middleware">Route Middleware</a></li>192<li><a href="#http-methods">HTTP Methods</a></li>193<li><a href="#error-handling">Error Handling</a></li>194<li><a href="#route-param pre-conditions">Route Param Pre-conditions</a></li>195<li><a href="#view-rendering">View Rendering</a></li>196<li><a href="#view-partials">View Partials</a></li>197<li><a href="#view-lookup">View Lookup</a></li>198<li><a href="#template-engines">Template Engines</a></li>199<li><a href="#session-support">Session Support</a></li>200<li><a href="#migration-guide">Migration Guide</a></li>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 201why, one step back201<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 202–205why, one step back202<li><a href="#req.header()">header()</a></li>203<li><a href="#req.accepts()">accepts()</a></li>204<li><a href="#req.is()">is()</a></li>205<li><a href="#req.param()">param()</a></li>updated docsTj Holowaychukbefore adoption652e166
line 206why, one step back206<li><a href="#req.get()">get()</a></li>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 207–208why, one step back207<li><a href="#req.flash()">flash()</a></li>208<li><a href="#req.isxmlhttprequest">isXMLHttpRequest</a></li>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 209–210why, one step back209</ul></li>210<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 211–224why, one step back211<li><a href="#res.header()">header()</a></li>212<li><a href="#res.charset">charset</a></li>213<li><a href="#res.contenttype()">contentType()</a></li>214<li><a href="#res.attachment()">attachment()</a></li>215<li><a href="#res.sendfile()">sendfile()</a></li>216<li><a href="#res.download()">download()</a></li>217<li><a href="#res.send()">send()</a></li>218<li><a href="#res.redirect()">redirect()</a></li>219<li><a href="#res.cookie()">cookie()</a></li>220<li><a href="#res.clearcookie()">clearCookie()</a></li>221<li><a href="#res.render()">render()</a></li>222<li><a href="#res.partial()">partial()</a></li>223<li><a href="#res.local()">local()</a></li>224<li><a href="#res.locals()">locals()</a></li>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 225–226why, one step back225</ul></li>226<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 227–236why, one step back227<li><a href="#app.set()">set()</a></li>228<li><a href="#app.enable()">enable()</a></li>229<li><a href="#app.enabled()">enabled()</a></li>230<li><a href="#app.disable()">disable()</a></li>231<li><a href="#app.disabled()">disabled()</a></li>232<li><a href="#app.configure()">configure()</a></li>233<li><a href="#app.redirect()">redirect()</a></li>234<li><a href="#app.error()">error()</a></li>235<li><a href="#app.helpers()">helpers()</a></li>236<li><a href="#app.dynamichelpers()">dynamicHelpers()</a></li>updated docsTj Holowaychukbefore adoption99b49d2
lines 237–238why, one step back237<li><a href="#app.lookup">lookup</a></li>238<li><a href="#app.match">match</a></li>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 239–241why, one step back239<li><a href="#app.mounted()">mounted()</a></li>240<li><a href="#app.register()">register()</a></li>241<li><a href="#app.listen()">listen()</a></li>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 242–254why, one step back242</ul></li>243</ul>244 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 245 <p id="tagline">246 High performance, high class web development for247 <a href="http://nodejs.org">Node.js</a>248 </p>249 <ul id="menu">250 <li><a href="index.html">Home</a></li>251 <li><a href="guide.html">Guide</a></li>252 <li><a href="screencasts.html">Screencasts</a></li>253 <li><a href="applications.html">Applications</a></li>254 </ul>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 255why, one step back255<h3 id="installation">Installation</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 256why, one step back256fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 257–258why, one step back257<pre><code>$ npm install express258</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 259why, one step back259generate docsTj Holowaychukbefore adoptionff7d5ff
lines 260–284why, one step back260<p>or to access the <code>express(1)</code> executable install globally:</p>261262<pre><code>$ npm install -g express263</code></pre>264265<h2>Quick Start</h2>266267<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>268269<p> Create the app:</p>270271<pre><code>$ npm install -g express272$ express /tmp/foo && cd /tmp/foo273</code></pre>274275<p> Install dependencies:</p>276277<pre><code>$ npm install -d278</code></pre>279280<p> Start the server:</p>281282<pre><code>$ node app.js283</code></pre>284fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 285why, one step back285<h3 id="creating-a server">Creating A Server</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 286–294why, one step back286287<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>288289<pre><code>var app = require('express').createServer();290291app.get('/', function(req, res){292 res.send('hello world');293});294fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 295–296why, one step back295app.listen(3000);296</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 297why, one step back297fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 298why, one step back298<h3 id="creating-an https server">Creating An HTTPS Server</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 299–300why, one step back299300<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 301why, one step back301 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 302why, one step back302fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 303–304why, one step back303<pre><code> var app = require('express').createServer({ key: ... });304</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 305why, one step back305fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 306why, one step back306<h3 id="configuration">Configuration</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 307–309why, one step back307308<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers309can 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 310why, one step back310<em>configure()</em> is called without an environment name it will be run in <em>every</em> environmentmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 311–318why, one step back311prior to the environment specific callback.</p>312313<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces314in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.315Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,316otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>317318<pre><code>app.configure(function(){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 319–321why, one step back319 app.use(express.methodOverride());320 app.use(express.bodyParser());321 app.use(app.router);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 322–324why, one step back322});323324app.configure('development', function(){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 325–326why, one step back325 app.use(express.static(__dirname + '/public'));326 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 327–330why, one step back327});328329app.configure('production', function(){330 var oneYear = 31557600000;regenerated docsTj Holowaychukbefore adoptiondd7158a
line 331why, one step back331 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 332why, one step back332 app.use(express.errorHandler());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 333–334why, one step back333});334</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 335–350why, one step back335336<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>337338<pre><code> app.configure(function(){339 app.set('views', __dirname + '/views');340 app.set('views');341 // => "/absolute/path/to/views"342343 app.enable('some feature');344 // same as app.set('some feature', true);345346 app.disable('some feature');347 // same as app.set('some feature', false);348349 app.enabled('some feature')350 // => falsefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 351–352why, one step back351 });352</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 353why, one step back353fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 354why, one step back354<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 355why, one step back355fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 356–357why, one step back356<pre><code>$ NODE_ENV=production node app.js357</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 358–360why, one step back358359<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>360fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 361why, one step back361<h3 id="settings">Settings</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 362–364why, one step back362363<p>Express supports the following settings out of the box:</p>364fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 365–369why, one step back365<ul>366<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>367<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>368<li><em>view engine</em> Default view engine name for views rendered without extensions</li>369<li><em>view options</em> An object specifying global view options</li>docsTj Holowaychukbefore adoption3588c1e
lines 370–371why, one step back370<li><em>view cache</em> Enable view caching (enabled in production)</li>371<li><em>case sensitive routes</em> Enable case-sensitive routing</li>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 372why, one step back372</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 373–374why, one step back373374fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 375–376why, one step back375<h3 id="routing">Routing</h3>376migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 377why, one step back377<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 378–379why, one step back378For example we may want to render a user’s account for the path <em>/user/12</em>, this379can be done by defining the route below. The values associated to the named placeholdersmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 380–382why, one step back380are available as <code>req.params</code>.</p>381382<pre><code>app.get('/user/:id', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 383–385why, one step back383 res.send('user ' + req.params.id);384});385</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 386why, one step back386docsTj Holowaychukbefore adoption3588c1e
line 387why, one step back387<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For examplemigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 388–389why, one step back388when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>389fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 390–391why, one step back390<pre><code>\/user\/([^\/]+)\/?391</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 392–393why, one step back392393<p>Regular expression literals may also be passed for complex uses. Since capturefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 394why, one step back394groups 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 395–397why, one step back395396<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){397 res.send(req.params);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 398–399why, one step back398});399</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 400–409why, one step back400401<p>Curl requests against the previously defined route:</p>402403<pre><code> $ curl http://dev:3000/user404 [null,null]405 $ curl http://dev:3000/users406 [null,null]407 $ curl http://dev:3000/users/1408 ["1",null]409 $ curl http://dev:3000/users/1..15fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 410–411why, one step back410 ["1","15"]411</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 412–445why, one step back412413<p>Below are some route examples, and the associated paths that they414may consume:</p>415416<pre><code> "/user/:id"417 /user/12418419 "/users/:id?"420 /users/5421 /users422423 "/files/*"424 /files/jquery.js425 /files/javascripts/jquery.js426427 "/file/*.*"428 /files/jquery.js429 /files/javascripts/jquery.js430431 "/user/:id/:operation?"432 /user/1433 /user/1/edit434435 "/products.:format"436 /products.json437 /products.xml438439 "/products.:format?"440 /products.json441 /products.xml442 /products443444 "/user/:id.:format?"445 /user/12fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 446–447why, one step back446 /user/12.json447</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 448–459why, one step back448449<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>450451<pre><code>var express = require('express')452 , app = express.createServer();453454app.use(express.bodyParser());455456app.post('/', function(req, res){457 res.send(req.body);458});459fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 460–461why, one step back460app.listen(3000);461</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 462why, one step back462docsTj Holowaychukbefore adoption3588c1e
line 463why, one step back463<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 464why, one step back464fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 465why, one step back465<h3 id="passing-route control">Passing Route Control</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 466–471why, one step back466467<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,468the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,469and 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>470471<pre><code>app.get('/users/:id?', function(req, res, next){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 472–477why, one step back472 var id = req.params.id;473 if (id) {474 // do something475 } else {476 next();477 }migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 478–480why, one step back478});479480app.get('/users', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 481–483why, one step back481 // do something else482});483</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 484–516why, one step back484485<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>486487<pre><code>var express = require('express')488 , app = express.createServer();489490var users = [{ name: 'tj' }];491492app.all('/user/:id/:op?', function(req, res, next){493 req.user = users[req.params.id];494 if (req.user) {495 next();496 } else {497 next(new Error('cannot find user ' + req.params.id));498 }499});500501app.get('/user/:id', function(req, res){502 res.send('viewing ' + req.user.name);503});504505app.get('/user/:id/edit', function(req, res){506 res.send('editing ' + req.user.name);507});508509app.put('/user/:id', function(req, res){510 res.send('updating ' + req.user.name);511});512513app.get('*', function(req, res){514 res.send('what???', 404);515});516fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 517–518why, one step back517app.listen(3000); 518</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 519why, one step back519fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 520why, one step back520<h3 id="middleware">Middleware</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 521–527why, one step back521522<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be523passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>524525<pre><code> var express = require('express');526527var app = express.createServer(fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 528–531why, one step back528 express.logger()529 , express.bodyParser()530 );531</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 532–534why, one step back532533<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>534generate docsTj Holowaychukbefore adoptionff7d5ff
line 535why, one step back535<pre><code>app.use(express.logger({ format: ':method :url' }));fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 536why, one step back536</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 537why, one step back537fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 538why, one step back538<p>Typically with connect middleware you would <em>require(‘connect’)</em> like so:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 539–541why, one step back539540<pre><code>var connect = require('connect');541app.use(connect.logger());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 542–543why, one step back542app.use(connect.bodyParser());543</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 544–547why, one step back544545<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>546547<pre><code>app.use(express.logger());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 548–549why, one step back548app.use(express.bodyParser());549</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 550why, one step back550docsTj Holowaychukbefore adoption3588c1e
lines 551–578why, one step back551<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>552553<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>554555<pre><code>app.use(express.logger(...));556app.use(express.bodyParser(...));557app.use(express.cookieParser(...));558app.use(express.session(...));559app.use(app.router);560app.use(express.static(...));561app.use(express.errorHandler(...));562</code></pre>563564<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>565566<pre><code>var downloads = {};567568app.use(app.router);569app.use(express.static(__dirname + '/public'));570571app.get('/*', function(req, res, next){572 var file = req.params[0];573 downloads[file] = downloads[file] || 0;574 downloads[file]++;575 next();576});577</code></pre>578fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 579why, one step back579<h3 id="route-middleware">Route Middleware</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 580–582why, one step back580581<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>582fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 583why, one step back583<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 584–589why, one step back584585<pre><code>app.get('/user/:id', function(req, res, next){586 loadUser(req.params.id, function(err, user){587 if (err) return next(err);588 res.send('Viewing user ' + user.name);589 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 590–591why, one step back590});591</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 592why, one step back592fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 593why, one step back593<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 594–607why, one step back594595<pre><code>function loadUser(req, res, next) {596 // You would fetch your user from the db597 var user = users[req.params.id];598 if (user) {599 req.user = user;600 next();601 } else {602 next(new Error('Failed to load user ' + req.params.id));603 }604}605606app.get('/user/:id', loadUser, function(req, res){607 res.send('Viewing user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 608–609why, one step back608});609</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 610–620why, one step back610611<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>612613<pre><code>function andRestrictToSelf(req, res, next) {614 req.authenticatedUser.id == req.user.id615 ? next()616 : next(new Error('Unauthorized'));617}618619app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){620 res.send('Editing user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 621–622why, one step back621});622</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 623–635why, one step back623624<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>625626<pre><code>function andRestrictTo(role) {627 return function(req, res, next) {628 req.authenticatedUser.role == role629 ? next()630 : next(new Error('Unauthorized'));631 }632}633634app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){635 res.send('Deleted user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 636–637why, one step back636});637</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 638why, one step back638fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 639why, one step back639<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 640–649why, one step back640641<pre><code>var a = [middleware1, middleware2]642 , b = [middleware3, middleware4]643 , all = [a, b];644645app.get('/foo', a, function(){});646app.get('/bar', a, function(){});647648app.get('/', a, middleware3, middleware4, function(){});649app.get('/', a, b, function(){});fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 650–651why, one step back650app.get('/', all, function(){});651</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 652–654why, one step back652653<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>654docsTj Holowaychukbefore adoption3588c1e
lines 655–656why, one step back655<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>656fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 657why, one step back657<h3 id="http-methods">HTTP Methods</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 658–660why, one step back658659<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>660fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 661why, one step back661<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 662–666why, one step back662663<pre><code> <form method="post" action="/">664 <input type="text" name="user[name]" />665 <input type="text" name="user[email]" />666 <input type="submit" value="Submit" />fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 667–668why, one step back667 </form>668</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 669why, one step back669fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 670why, one step back670<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 671why, one step back671fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 672–673why, one step back672<pre><code>app.use(express.bodyParser());673</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 674–679why, one step back674675<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>676677<pre><code>app.post('/', function(req, res){678 console.log(req.body.user);679 res.redirect('back');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 680–681why, one step back680});681</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 682why, one step back682fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 683why, one step back683<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 684–685why, one step back684685<pre><code>app.use(express.bodyParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 686–687why, one step back686app.use(express.methodOverride());687</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 688–700why, one step back688689<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>690691<pre><code><form method="post" action="/">692 <input type="hidden" name="_method" value="put" />693 <input type="text" name="user[name]" />694 <input type="text" name="user[email]" />695 <input type="submit" value="Submit" /> 696</form>697698app.put('/', function(){699 console.log(req.body.user);700 res.redirect('back');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 701–702why, one step back701});702</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 703why, one step back703fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 704why, one step back704<h3 id="error-handling">Error Handling</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 705–715why, one step back705706<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,707or passed to <em>next(err)</em>. Below is an example which serves different pages based on our708ad-hoc <em>NotFound</em> exception:</p>709710<pre><code>function NotFound(msg){711 this.name = 'NotFound';712 Error.call(this, msg);713 Error.captureStackTrace(this, arguments.callee);714}715fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 716why, one step back716NotFound.prototype.__proto__ = Error.prototype;migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 717–723why, one step back717718app.get('/404', function(req, res){719 throw new NotFound;720});721722app.get('/500', function(req, res){723 throw new Error('keyboard cat!');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 724–725why, one step back724});725</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 726–731why, one step back726727<p>We can call <em>app.error()</em> several times as shown below.728Here we check for an instanceof <em>NotFound</em> and show the729404 page, or we pass on to the next error handler.</p>730731<p>Note that these handlers can be defined anywhere, as theyfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 732why, one step back732will be placed below the route handlers on <em>listen()</em>. Thismigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 733–741why, one step back733allows for definition within <em>configure()</em> blocks so we can734handle exceptions in different ways based on the environment.</p>735736<pre><code>app.error(function(err, req, res, next){737 if (err instanceof NotFound) {738 res.render('404.jade');739 } else {740 next(err);741 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 742–743why, one step back742});743</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 744–745why, one step back744745<p>Here we assume all errors as 500 for the simplicity offixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 746why, one step back746this 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 747–751why, one step back747748<pre><code>app.error(function(err, req, res){749 res.render('500.jade', {750 error: err751 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 752–753why, one step back752});753</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 754–755why, one step back754755<p>Our apps could also utilize the Connect <em>errorHandler</em> middlewarefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 756–757why, one step back756to report on exceptions. For example if we wish to output exceptions757in “development” mode to <em>stderr</em> we can use:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 758why, one step back758fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 759–760why, one step back759<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));760</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 761–764why, one step back761762<p>Also during development we may want fancy html pages to show exceptions763that are passed or thrown, so we can set <em>showStack</em> to true:</p>764fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 765–766why, one step back765<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));766</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 767–770why, one step back767768<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>769is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>770fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 771why, one step back771<h3 id="route-param pre-conditions">Route Param Pre-conditions</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 772–779why, one step back772773<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>774775<pre><code>app.get('/user/:userId', function(req, res, next){776 User.get(req.params.userId, function(err, user){777 if (err) return next(err);778 res.send('user ' + user.name);779 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 780–781why, one step back780}); 781</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 782–791why, one step back782783<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>784785<pre><code>app.param('userId', function(req, res, next, id){786 User.get(id, function(err, user){787 if (err) return next(err);788 if (!user) return next(new Error('failed to find user'));789 req.user = user;790 next();791 });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 792–793why, one step back792});793</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 794–798why, one step back794795<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>796797<pre><code>app.get('/user/:userId', function(req, res){798 res.send('user ' + req.user.name);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 799–800why, one step back799});800</code></pre>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<h3 id="view-rendering">View Rendering</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 803why, one step back803fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 804why, one step back804<p>View filenames take the form “<name>.<engine>”, where <engine> is the namemigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 805why, one step back805of 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 806–807why, one step back806tell 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 behaviour807<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 808–809why, one step back808809<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 810why, one step back810and 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 811–813why, one step back811the <em>body</em> local variable in <em>layout.jade</em>.</p>812813<pre><code>app.get('/', function(req, res){fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 814–816why, one step back814 res.render('index.jade', { title: 'My Site' });815});816</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 817–820why, one step back817818<p>The new <em>view engine</em> setting allows us to specify our default template engine,819so for example when using jade we could set:</p>820fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 821–822why, one step back821<pre><code>app.set('view engine', 'jade');822</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 823–825why, one step back823824<p>Allowing us to render with:</p>825fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 826–827why, one step back826<pre><code>res.render('index');827</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 828–830why, one step back828829<p>vs:</p>830fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 831–832why, one step back831<pre><code>res.render('index.jade');832</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 833–836why, one step back833834<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still835mix and match template engines:</p>836fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 837–838why, one step back837<pre><code>res.render('another-page.ejs');838</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 839–843why, one step back839840<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>841842<pre><code>app.set('view options', {843 layout: falsefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 844–845why, one step back844});845</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 846–848why, one step back846847<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>848fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 849–850why, one step back849<pre><code>res.render('myview.ejs', { layout: true });850</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 851–853why, one step back851852<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>853fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 854–855why, one step back854<pre><code>res.render('page', { layout: 'mylayout' });855</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 856–858why, one step back856857<p>Otherwise we must specify the extension:</p>858fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 859–860why, one step back859<pre><code>res.render('page', { layout: 'mylayout.jade' });860</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 861–863why, one step back861862<p>These paths may also be absolute:</p>863fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 864–865why, one step back864<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });865</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 866–871why, one step back866867<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>868869<pre><code>app.set('view options', {870 open: '{{',871 close: '}}'fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 872–873why, one step back872});873</code></pre>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<h3 id="view-partials">View Partials</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 876why, one step back876fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 877why, one step back877<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 878why, one step back878in a view to display comments, we could use partial collection:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 879why, one step back879fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 880–881why, one step back880<pre><code>partial('comment', { collection: comments });881</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 882why, one step back882regenerated docsTj Holowaychukbefore adoptiondd7158a
line 883why, one step back883<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 884why, one step back884fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 885–886why, one step back885<pre><code>partial('comment', comments);886</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 887why, one step back887fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 888why, one step back888<p>When using the partial collection support a few “magic” locals are providedmigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 889–890why, one step back889for free:</p>890fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 891–896why, one step back891<ul>892<li><em>firstInCollection</em> true if this is the first object</li>893<li><em>indexInCollection</em> index of the object in the collection</li>894<li><em>lastInCollection</em> true if this is the last object</li>895<li><em>collectionLength</em> length of the collection</li>896</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 897–898why, one step back897898fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 899–900why, one step back899<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>900migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 901–904why, one step back901<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>902903<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>904fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 905why, one step back905<h3 id="view-lookup">View Lookup</h3>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>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 908why, one step back908fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 909why, one step back909<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 910why, one step back910fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 911why, one step back911<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 912why, one step back912fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 913why, one step back913<h3 id="template-engines">Template Engines</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 914–916why, one step back914915<p>Below are a few template engines commonly used with Express:</p>916fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 917–923why, one step back917<ul>918<li><a href="http://github.com/visionmedia/haml.js">Haml</a> haml implementation</li>919<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>920<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>921<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>922<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>923</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 924–925why, one step back924925fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 926why, one step back926<h3 id="session-support">Session Support</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 927why, one step back927fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 928–929why, one step back928<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>929migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 930why, one step back930<pre><code>app.use(express.cookieParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 931–932why, one step back931app.use(express.session({ secret: "keyboard cat" }));932</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 933–935why, one step back933934<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>935Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4
line 936why, one step back936<pre><code>var RedisStore = require('connect-redis')(express);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 937why, one step back937app.use(express.cookieParser());fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 938–939why, one step back938app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));939</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 940–942why, one step back940941<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>942Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4
line 943why, one step back943<pre><code>var RedisStore = require('connect-redis')(express);migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 944–963why, one step back944app.use(express.bodyParser());945app.use(express.cookieParser());946app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));947948app.post('/add-to-cart', function(req, res){949 // Perhaps we posted several items with a form950 // (use the bodyParser() middleware for this)951 var items = req.body.items;952 req.session.items = items;953 res.redirect('back');954});955956app.get('/add-to-cart', function(req, res){957 // When redirected back to GET /add-to-cart958 // we could check req.session.items && req.session.items.length959 // to print out a message960 if (req.session.items && req.session.items.length) {961 req.flash('info', 'You have %s items in your cart', req.session.items.length);962 }963 res.render('shopping-cart');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 964–965why, one step back964});965</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 966–968why, one step back966967<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>968fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 969why, one step back969<h3 id="migration-guide">Migration Guide</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 970–972why, one step back970971<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>972fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 973why, one step back973<h3 id="req.header()">req.header(key[, defaultValue])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 974–978why, one step back974975<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>976977<pre><code>req.header('Host');978req.header('host');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 979–980why, one step back979req.header('Accept', '*/*');980</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 981–989why, one step back981982<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>983984<pre><code>// sent Referrer: http://google.com985986req.header('Referer');987// => "http://google.com"988989req.header('Referrer');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 990–991why, one step back990// => "http://google.com"991</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 992why, one step back992fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 993why, one step back993<h3 id="req.accepts()">req.accepts(type)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 994–998why, one step back994995<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>996997<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise998the 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 999–1000why, one step back999may pass the subtype such as “html” which is then converted internally1000to “text/html” using the mime lookup table.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1001–1014why, one step back10011002<pre><code>// Accept: text/html1003req.accepts('html');1004// => true10051006// Accept: text/*; application/json1007req.accepts('html');1008req.accepts('text/html');1009req.accepts('text/plain');1010req.accepts('application/json');1011// => true10121013req.accepts('image/png');1014req.accepts('png');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1015–1016why, one step back1015// => false1016</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1017why, one step back1017fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1018why, one step back1018<h3 id="req.is()">req.is(type)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1019–1033why, one step back10191020<p>Check if the incoming request contains the <em>Content-Type</em>1021header field, and it contains the give mime <em>type</em>.</p>10221023<pre><code> // With Content-Type: text/html; charset=utf-81024 req.is('html');1025 req.is('text/html');1026 // => true10271028 // When Content-Type is application/json1029 req.is('json');1030 req.is('application/json');1031 // => true10321033 req.is('html');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1034–1035why, one step back1034 // => false1035</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1036–1038why, one step back10361037<p>Ad-hoc callbacks can also be registered with Express, to perform1038assertions again the request, for example if we need an expressivefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1039why, one step back1039way to check if our incoming request is an image, we can register <em>“an image”</em>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1040–1043why, one step back1040callback:</p>10411042<pre><code> app.is('an image', function(req){1043 return 0 == req.headers['content-type'].indexOf('image');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1044–1045why, one step back1044 });1045</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1046–1047why, one step back10461047<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 1048why, one step back1048such as <em>“image/jpeg”</em>, <em>“image/png”</em>, etc.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1049–1055why, one step back10491050<pre><code> app.post('/image/upload', function(req, res, next){1051 if (req.is('an image')) {1052 // do something1053 } else {1054 next();1055 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1056–1057why, one step back1056 });1057</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1058–1061why, one step back10581059<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you1060can perform any request assertion you wish.</p>1061fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1062why, one step back1062<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 1063why, one step back1063fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1064–1065why, one step back1064<pre><code>req.is('image/*');1065</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1066why, one step back1066fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1067why, one step back1067<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 1068why, one step back1068fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1069–1070why, one step back1069<pre><code>req.is('*/json');1070</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1071why, one step back1071fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1072why, one step back1072<h3 id="req.param()">req.param(name[, default])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1073–1075why, one step back10731074<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>1075fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1076–1080why, one step back1076<ul>1077<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>1078<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1079<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1080</ul>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1081why, one step back1081fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1082why, one step back1082migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1083–1085why, one step back1083<p>To utilize urlencoded request bodies, <em>req.body</em>1084should be an object. This can be done by using1085the _express.bodyParser middleware.</p>updated docsTj Holowaychukbefore adoption652e166
lines 1086–1097why, one step back10861087<h3 id="req.get()">req.get(field, param)</h3>10881089<p> Get <em>field</em>’s <em>param</em> value, defaulting to ‘’ when the <em>param</em>1090 or <em>field</em> is not present.</p>10911092<pre><code> req.get('content-disposition', 'filename');1093 // => "something.png"10941095 req.get('Content-Type', 'boundary');1096 // => "--foo-bar-baz"1097</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1098why, one step back1098fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1099why, one step back1099<h3 id="req.flash()">req.flash(type[, msg])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1100–1114why, one step back11001101<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>11021103<pre><code>req.flash('info', 'email sent');1104req.flash('error', 'email delivery failed');1105req.flash('info', 'email re-sent');1106// => 211071108req.flash('info');1109// => ['email sent', 'email re-sent']11101111req.flash('info');1112// => []11131114req.flash();fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1115–1116why, one step back1115// => { error: ['email delivery failed'], info: [] }1116</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1117–1119why, one step back11171118<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>1119fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1120–1121why, one step back1120<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1121</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1122why, one step back1122fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1123why, one step back1123<h3 id="req.isxmlhttprequest">req.isXMLHttpRequest</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1124–1128why, one step back11241125<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1126to see if it was issued by an <em>XMLHttpRequest</em>:</p>11271128<pre><code>req.xhrfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1129–1130why, one step back1129req.isXMLHttpRequest1130</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.header()">res.header(key[, val])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1133–1142why, one step back11331134<p>Get or set the response header <em>key</em>.</p>11351136<pre><code>res.header('Content-Length');1137// => undefined11381139res.header('Content-Length', 123);1140// => 12311411142res.header('Content-Length');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1143–1144why, one step back1143// => 1231144</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1145why, one step back1145fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1146why, one step back1146<h3 id="res.charset">res.charset</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1147why, one step back1147fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1148why, one step back1148<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 1149–1150why, one step back11491150<pre><code>res.charset = 'ISO-8859-1';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1151–1152why, one step back1151res.render('users');1152</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1153–1156why, one step back11531154<p>or before responding with <code>res.send()</code>:</p>11551156<pre><code>res.charset = 'ISO-8859-1';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1157–1158why, one step back1157res.send(str);1158</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1159why, one step back1159fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1160why, one step back1160<p>or with node’s <code>res.end()</code>:</p>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1161–1163why, one step back11611162<pre><code>res.charset = 'ISO-8859-1';1163res.header('Content-Type', 'text/plain');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1164–1165why, one step back1164res.end(str);1165</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1166why, one step back1166fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1167why, one step back1167<h3 id="res.contenttype()">res.contentType(type)</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1168why, one step back1168migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1169–1172why, one step back1169<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>11701171<pre><code> var filename = 'path/to/image.png';1172 res.contentType(filename);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1173–1174why, one step back1173 // Content-Type is now "image/png"1174</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1175why, one step back1175regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1176why, one step back1176<p>A literal <em>Content-Type</em> works as well:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1177why, one step back1177fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1178–1179why, one step back1178<pre><code> res.contentType('application/json');1179</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1180–1182why, one step back11801181<p>Or simply the extension without leading <code>.</code>:</p>1182fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1183–1184why, one step back1183<pre><code> res.contentType('json');1184</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1185why, one step back1185fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1186why, one step back1186<h3 id="res.attachment()">res.attachment([filename])</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1187why, one step back1187fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1188why, one step back1188<p>Sets the <em>Content-Disposition</em> response header to “attachment”, with optional <em>filename</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1189why, one step back1189fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1190–1191why, one step back1190<pre><code> res.attachment('path/to/my/image.png');1191</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1192why, one step back1192fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1193why, one step back1193<h3 id="res.sendfile()">res.sendfile(path[, options[, callback]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1194why, one step back1194fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1195why, one step back1195<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1196why, one step back1196fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1197–1198why, one step back1197<pre><code>res.sendfile('path/to/my.file');1198</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1199–1208why, one step back11991200<p>This method accepts an optional callback which is called when1201an 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>12021203<pre><code>res.sendfile(path, function(err){1204 if (err) {1205 next(err);1206 } else {1207 console.log('transferred %s', path);1208 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1209–1210why, one step back1209});1210</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1211–1215why, one step back12111212<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>12131214<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1215 // handlefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1216–1217why, one step back1216});1217</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1218why, one step back1218docsTj Holowaychukbefore adoption3588c1e
line 1219why, one step back1219<h3 id="res.download()">res.download(file[, filename[, callback[, callback2]]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1220–1223why, one step back12201221<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>12221223<pre><code>res.download('path/to/image.png');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1224–1225why, one step back1224res.download('path/to/image.png', 'foo.png');1225</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1226–1229why, one step back12261227<p>This is equivalent to:</p>12281229<pre><code>res.attachment(file);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1230–1231why, one step back1230res.sendfile(file);1231</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1232why, one step back1232docsTj Holowaychukbefore adoption3588c1e
line 1233why, one step back1233<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 1234–1236why, one step back12341235<pre><code>res.download(path, 'expenses.doc', function(err){1236 // handlefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1237–1238why, one step back1237});1238</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1239why, one step back1239docsTj Holowaychukbefore adoption3588c1e
lines 1240–1248why, one step back1240<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>12411242<pre><code>res.download(path, function(err){1243 // error or finished1244}, function(err){1245 // connection related error1246});1247</code></pre>1248fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1249why, one step back1249<h3 id="res.send()">res.send(body|status[, headers|status[, status]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1250–1259why, one step back12501251<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1252objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>12531254<pre><code> res.send(); // 2041255 res.send(new Buffer('wahoo'));1256 res.send({ some: 'json' });1257 res.send('<p>some html</p>');1258 res.send('Sorry, cant find that', 404);1259 res.send('text', { 'Content-Type': 'text/plain' }, 201);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1260–1261why, one step back1260 res.send(404);1261</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1262–1266why, one step back12621263<p>By default the <em>Content-Type</em> response header is set, however if explicitly1264assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1265it will not be set again.</p>1266fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1267why, one step back1267<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 1268why, one step back1268fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1269why, one step back1269<h3 id="res.redirect()">res.redirect(url[, status])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1270–1276why, one step back12701271<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>12721273<pre><code>res.redirect('/', 301);1274res.redirect('/account');1275res.redirect('http://google.com');1276res.redirect('home');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1277–1278why, one step back1277res.redirect('back');1278</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1279why, one step back1279fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1280why, one step back1280<p>Express supports “redirect mapping”, which by default provides <em>home</em>, and <em>back</em>.migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1281why, one step back1281The <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 1282why, one step back1282the “home” setting and defaults to “/”.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1283why, one step back1283fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1284why, one step back1284<h3 id="res.cookie()">res.cookie(name, val[, options])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1285–1288why, one step back12851286<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>12871288<pre><code>// "Remember me" for 15 minutes fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1289–1290why, one step back1289res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1290</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1291–1293why, one step back12911292<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>1293fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1294–1295why, one step back1294<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });1295</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1296why, one step back1296updated docsTj Holowaychukbefore adoption99b49d2
line 1297why, one step back1297<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 1298–1302why, one step back12981299<pre><code>app.use(express.cookieParser());13001301app.get('/', function(req, res){1302 // use req.cookies.remembermefixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1303–1304why, one step back1303});1304</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1305why, one step back1305docsTj Holowaychukbefore adoption3588c1e
line 1306why, one step back1306<h3 id="res.clearcookie()">res.clearCookie(name[, options])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1307why, one step back1307fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1308why, one step back1308<p>Clear cookie <em>name</em> by setting “expires” far in the past.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1309why, one step back1309fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1310–1311why, one step back1310<pre><code>res.clearCookie('rememberme');1311</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1312why, one step back1312fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1313why, one step back1313<h3 id="res.render()">res.render(view[, options[, fn]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1314–1318why, one step back13141315<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1316When a callback function is given a response will <em>not</em> be made1317automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>1318fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1319why, one step back1319<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 1320–1321why, one step back13201321<pre><code>var user = { name: 'tj' };fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1322–1323why, one step back1322res.render('index', { layout: false, user: user });1323</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1324why, one step back1324fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1325why, one step back1325<h3 id="res.partial()">res.partial(view[, options])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1326–1329why, one step back13261327<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1328to the view as a local variable.</p>1329fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1330–1332why, one step back1330<ul>1331<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1332<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 1333why, one step back1333fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1334–1344why, one step back1334<ul>1335<li>as: ‘something’ will add the <em>something</em> local variable</li>1336<li>as: this will use the collection value as the template context</li>1337<li>as: global will merge the collection value’s properties with <em>locals</em></li>1338</ul>1339</li>1340<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1341For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1342</ul>13431344migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1345–1352why, one step back1345<p>The following are equivalent, and the name of collection value when passed1346to the partial will be <em>movie</em> as derived from the name.</p>13471348<pre><code>partial('theatre/movie.jade', { collection: movies });1349partial('theatre/movie.jade', movies);1350partial('movie.jade', { collection: movies });1351partial('movie.jade', movies);1352partial('movie', movies);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1353–1354why, one step back1353// In view: movie.director1354</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1355why, one step back1355fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1356why, one step back1356<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 1357–1358why, one step back13571358<pre><code>partial('movie', { collection: movies, as: 'video' });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1359–1360why, one step back1359// In view: video.director1360</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1361–1365why, one step back13611362<p>Also we can make our movie the value of <em>this</em> within our view so that instead1363of <em>movie.director</em> we could use <em>this.director</em>.</p>13641365<pre><code>partial('movie', { collection: movies, as: this });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1366–1367why, one step back1366// In view: this.director1367</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1368why, one step back1368fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1369why, one step back1369<p>Another alternative is to “expand” the properties of the collection item intomigration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1370–1372why, one step back1370pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>13711372<pre><code>partial('movie', { collection: movies, as: global });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1373–1374why, one step back1373// In view: director1374</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1375–1387why, one step back13751376<p>This same logic applies to a single partial object usage:</p>13771378<pre><code>partial('movie', { object: movie, as: this });1379// In view: this.director13801381partial('movie', { object: movie, as: global });1382// In view: director13831384partial('movie', { object: movie, as: 'video' });1385// In view: video.director13861387partial('movie', { object: movie });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1388–1389why, one step back1388// In view: movie.director1389</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1390why, one step back1390fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1391why, one step back1391<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 1392why, one step back1392regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1393–1394why, one step back1393<pre><code>var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1394partial('movie', movie)fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1395–1396why, one step back1395// => In view: movie.director1396</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1397why, one step back1397fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1398why, one step back1398<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 1399–1400why, one step back13991400<pre><code>var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1401–1402why, one step back1401partial('movie', movie)1402</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1403–1407why, one step back14031404<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>14051406<pre><code> partial('movie', { locals: { movie: movie }})1407 partial('movie', { movie: movie })fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1408–1409why, one step back1408 partial('movie', { object: movie })1409</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1410why, one step back1410migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1411–1423why, one step back1411<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>14121413<pre><code>app.get('/users', function(req, res){1414 if (req.xhr) {1415 // respond with the each user in the collection1416 // passed to the "user" view1417 res.partial('user', users);1418 } else {1419 // respond with layout, and users page1420 // which internally does partial('user', users)1421 // along with other UI1422 res.render('users', { users: users });1423 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1424–1425why, one step back1424});1425</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1426why, one step back1426fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1427why, one step back1427<h3 id="res.local()">res.local(name[, val])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1428–1441why, one step back14281429<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>14301431<pre><code> app.all('/movie/:id', function(req, res, next){1432 Movie.get(req.params.id, function(err, movie){1433 // Assigns res.locals.movie = movie1434 res.local('movie', movie);1435 });1436 });14371438 app.get('/movie/:id', function(req, res){1439 // movie is already a local, however we1440 // can pass more if we wish1441 res.render('movie', { displayReviews: true });fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1442–1443why, one step back1442 });1443</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1444why, one step back1444fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1445why, one step back1445<h3 id="res.locals()">res.locals(obj)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1446why, one step back1446regenerated docsTj Holowaychukbefore adoptiondd7158a
lines 1447–1451why, one step back1447<p> Assign several locals with the given <em>obj</em>. The following are equivalent:</p>14481449<pre><code> res.local('foo', bar);1450 res.local('bar', baz);1451fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1452–1453why, one step back1452 res.locals({ foo: bar, bar, baz });1453</code></pre>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1454why, one step back1454fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1455why, one step back1455<h3 id="app.set()">app.set(name[, val])</h3>regenerated docsTj Holowaychukbefore adoptiondd7158a
line 1456why, one step back1456migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1457–1461why, one step back1457<p>Apply an application level setting <em>name</em> to <em>val</em>, or1458get the value of <em>name</em> when <em>val</em> is not present:</p>14591460<pre><code>app.set('views', __dirname + '/views');1461app.set('views');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1462–1463why, one step back1462// => ...path...1463</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1464–1467why, one step back14641465<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>14661467<pre><code>app.settings.viewsfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1468–1469why, one step back1468// => ...path...1469</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1470why, one step back1470fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1471why, one step back1471<h3 id="app.enable()">app.enable(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1472–1479why, one step back14721473<p>Enable the given setting <em>name</em>:</p>14741475<pre><code>app.enable('some arbitrary setting');1476app.set('some arbitrary setting');1477// => true14781479app.enabled('some arbitrary setting');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1480–1481why, one step back1480// => true1481</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1482why, one step back1482fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1483why, one step back1483<h3 id="app.enabled()">app.enabled(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1484–1491why, one step back14841485<p>Check if setting <em>name</em> is enabled:</p>14861487<pre><code>app.enabled('view cache');1488// => false14891490app.enable('view cache');1491app.enabled('view cache');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1492–1493why, one step back1492// => true1493</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1494why, one step back1494fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1495why, one step back1495<h3 id="app.disable()">app.disable(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1496–1503why, one step back14961497<p>Disable the given setting <em>name</em>:</p>14981499<pre><code>app.disable('some setting');1500app.set('some setting');1501// => false15021503app.disabled('some setting');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1504–1505why, one step back1504// => false1505</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.disabled()">app.disabled(name)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1508–1517why, one step back15081509<p>Check if setting <em>name</em> is disabled:</p>15101511<pre><code>app.enable('view cache');15121513app.disabled('view cache');1514// => false15151516app.disable('view cache');1517app.disabled('view cache');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1518–1519why, one step back1518// => true1519</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1520why, one step back1520fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1521why, one step back1521<h3 id="app.configure()">app.configure(env|function[, function])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1522–1530why, one step back15221523<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>15241525<pre><code>app.configure(function(){1526 // executed for each env1527});15281529app.configure('development', function(){1530 // executed for 'development' onlyfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1531–1532why, one step back1531});1532</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1533why, one step back1533fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1534why, one step back1534<h3 id="app.redirect()">app.redirect(name, val)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1535–1537why, one step back15351536<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>1537fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1538–1539why, one step back1538<pre><code>app.redirect('google', 'http://google.com');1539</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1540–1542why, one step back15401541<p>Now in a route we may call:</p>1542fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1543why, one step back1543<p> res.redirect(‘google’);</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1544–1548why, one step back15441545<p>We may also map dynamic redirects:</p>15461547<pre><code>app.redirect('comments', function(req, res){1548 return '/post/' + req.params.id + '/comments';fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1549–1550why, one step back1549});1550</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1551–1557why, one step back15511552<p>So now we may do the following, and the redirect will dynamically adjust to1553the context of the request. If we called this route with <em>GET /post/12</em> our1554redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>15551556<pre><code>app.get('/post/:id', function(req, res){1557 res.redirect('comments');fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1558–1559why, one step back1558});1559</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1560–1562why, one step back15601561<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>1562fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1563–1564why, one step back1563<pre><code>res.redirect('/posts');1564</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1565why, one step back1565fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1566why, one step back1566<h3 id="app.error()">app.error(function)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1567–1573why, one step back15671568<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1569Note that we may set several error handlers by making several calls to this method, however the handler1570should call <em>next(err)</em> if it does not wish to deal with the exception:</p>15711572<pre><code>app.error(function(err, req, res, next){1573 res.send(err.message, 500);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1574–1575why, one step back1574});1575</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1576why, one step back1576fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1577why, one step back1577<h3 id="app.helpers()">app.helpers(obj)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1578–1580why, one step back15781579<p>Registers static view helpers.</p>1580updated docsTj Holowaychukbefore adoption99b49d2
lines 1581–1585why, one step back1581<pre><code>app.helpers({1582 name: function(first, last){ return first + ', ' + last }1583 , firstName: 'tj'1584 , lastName: 'holowaychuk'1585});fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1586–1587why, one step back1586</code></pre>1587migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1588–1590why, one step back1588<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1589as well as the <em>name()</em> function exposed.</p>1590fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1591–1592why, one step back1591<pre><code><%= name(firstName, lastName) %>1592</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1593why, one step back1593updated docsTj Holowaychukbefore adoption99b49d2
lines 1594–1597why, one step back1594<p>Express also provides a few locals by default:</p>15951596<pre><code>- `settings` the app's settings object1597- `filename` the view's filenamedocsTj Holowaychukbefore adoption3588c1e
line 1598why, one step back1598- `layout(path)` specify the layout from within a viewupdated docsTj Holowaychukbefore adoption99b49d2
lines 1599–1602why, one step back1599</code></pre>16001601<p>This method is aliased as <em>app.locals()</em>.</p>1602fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1603why, one step back1603<h3 id="app.dynamichelpers()">app.dynamicHelpers(obj)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1604–1613why, one step back16041605<p>Registers dynamic view helpers. Dynamic view helpers1606are simply functions which accept <em>req</em>, <em>res</em>, and are1607evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1608becomes the local variable it is associated with.</p>16091610<pre><code>app.dynamicHelpers({1611 session: function(req, res){1612 return req.session;1613 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1614–1615why, one step back1614});1615</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1616–1618why, one step back16161617<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>1618fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1619why, one step back1619<pre><code><%= session.name %>updated docsTj Holowaychukbefore adoption99b49d2
lines 1620–1723why, one step back1620</code></pre>16211622<h3 id="app.lookup">app.lookup</h3>16231624<p> The <em>app.lookup</em> http methods returns an array of callback functions1625 associated with the given <em>path</em>.</p>16261627<p> Suppose we define the following routes:</p>16281629<pre><code> app.get('/user/:id', function(){});1630 app.put('/user/:id', function(){});1631 app.get('/user/:id/:op?', function(){});1632</code></pre>16331634<p> We can utilize this lookup functionality to check which routes1635 have been defined, which can be extremely useful for higher level1636 frameworks built on Express.</p>16371638<pre><code> app.lookup.get('/user/:id');1639 // => [Function]16401641 app.lookup.get('/user/:id/:op?');1642 // => [Function]16431644 app.lookup.put('/user/:id');1645 // => [Function]16461647 app.lookup.all('/user/:id');1648 // => [Function, Function]16491650 app.lookup.all('/hey');1651 // => []1652</code></pre>16531654<p> To alias <em>app.lookup.VERB()</em>, we can simply invoke <em>app.VERB()</em>1655 without a callback, as a shortcut, for example the following are1656 equivalent:</p>16571658<pre><code> app.lookup.get('/user');1659 app.get('/user');1660</code></pre>16611662<p> Each function returned has the following properties:</p>16631664<pre><code> var fn = app.get('/user/:id/:op?')[0];16651666 fn.regexp1667 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i16681669 fn.keys1670 // => ['id', 'op']16711672 fn.path1673 // => '/user/:id/:op?'16741675 fn.method1676 // => 'GET'1677</code></pre>16781679<h3 id="app.match">app.match</h3>16801681<p> The <em>app.match</em> http methods return an array of callback functions1682 which match the given <em>url</em>, which may include a query string etc. This1683 is useful when you want reflect on which routes have the opportunity to1684 respond.</p>16851686<p> Suppose we define the following routes:</p>16871688<pre><code> app.get('/user/:id', function(){});1689 app.put('/user/:id', function(){});1690 app.get('/user/:id/:op?', function(){});1691</code></pre>16921693<p> Our match against <strong>GET</strong> will return two functions, since the <em>:op</em>1694 in our second route is optional.</p>16951696<pre><code> app.match.get('/user/1');1697 // => [Function, Function]1698</code></pre>16991700<p> This second call returns only the callback for <em>/user/:id/:op?</em>.</p>17011702<pre><code> app.match.get('/user/23/edit');1703 // => [Function]1704</code></pre>17051706<p> We can also use <em>all()</em> to disregard the http method:</p>17071708<pre><code> app.match.all('/user/20');1709 // => [Function, Function, Function]1710</code></pre>17111712<p> Each function matched has the following properties:</p>17131714<pre><code> var fn = app.match.get('/user/23/edit')[0];17151716 fn.keys1717 // => ['id', 'op']17181719 fn.params1720 // => { id: '23', op: 'edit' }17211722 fn.method1723 // => 'GET'fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1724why, one step back1724</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1725why, one step back1725fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1726why, one step back1726<h3 id="app.mounted()">app.mounted(fn)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1727–1737why, one step back17271728<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>17291730<pre><code>var app = express.createServer(),1731 blog = express.createServer();17321733blog.mounted(function(parent){1734 // parent is app1735 // "this" is blog1736});1737fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1738–1739why, one step back1738app.use(blog);1739</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1740why, one step back1740fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1741why, one step back1741<h3 id="app.register()">app.register(ext, exports)</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1742–1743why, one step back17421743<p>Register the given template engine <em>exports</em>fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1744why, one step back1744as <em>ext</em>. For example we may wish to map “.html”migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1745–1746why, one step back1745files to jade:</p>1746fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1747–1748why, one step back1747<pre><code> app.register('.html', require('jade'));1748</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1749–1751why, one step back17491750<p>This is also useful for libraries that may not1751match extensions correctly. For example my haml.jsfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1752–1753why, one step back1752library is installed from npm as “hamljs” so instead1753of layout.hamljs, we can register the engine as “.haml”:</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1754why, one step back1754fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1755–1756why, one step back1755<pre><code> app.register('.haml', require('haml-js'));1756</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1757–1761why, one step back17571758<p>For engines that do not comply with the Express1759specification, we can also wrap their api this way. Below1760we map <em>.md</em> to render markdown files, rendering the html once1761since it will not change on subsequent calls, and support local substitutionfixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1762why, one step back1762in the form of “{name}”.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1763–1772why, one step back17631764<pre><code> app.register('.md', {1765 compile: function(str, options){1766 var html = md.toHTML(str);1767 return function(locals){1768 return html.replace(/\{([^}]+)\}/g, function(_, name){1769 return locals[name];1770 });1771 };1772 }fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1773–1774why, one step back1773 });1774</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
line 1775why, one step back1775fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
line 1776why, one step back1776<h3 id="app.listen()">app.listen([port[, host]])</h3>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1777–1778why, one step back17771778<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 1779why, one step back1779connections will be accepted via <em>INADDR_ANY</em>.</p>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1780–1782why, one step back17801781<pre><code>app.listen();1782app.listen(3000);fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1783–1784why, one step back1783app.listen(3000, 'n.n.n.n');1784</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1785–1787why, one step back17851786<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>1787fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1788–1789why, one step back1788<pre><code>app.listen('/tmp/express.sock');1789</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1790–1799why, one step back17901791<p>Then try it out:</p>17921793<pre><code>$ telnet /tmp/express.sock1794GET / HTTP/1.117951796HTTP/1.1 200 OK1797Content-Type: text/plain1798Content-Length: 111799fixed docs due to markdown-js not supporting htmlTj Holowaychukbefore adoptiona75e60a
lines 1800–1801why, one step back1800Hello World1801</code></pre>migration docs for partialsTj Holowaychukbefore adoptioncdbd8af
lines 1802–1805why, one step back1802 </div>1803 </div>1804 </body>1805</html>