guide.html
This file
Path
docs/guide.html
1,286 lines · 43.2 KiB · HTML
Last changed by
Finished app page (for now)Tj Holowaychukbefore adoption7cbb737
History of this fileTake it
The walk stopped after 200 commits: lines older than 75661a2 point at it.
Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1–3why, one step back1<html>2 <head>3 <title>Express - node web framework</title>Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
line 4why, one step back4 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 5–18why, one step back5 <style>6 #tagline {7 margin-left: 75px;8 margin-bottom: 30px;9 color: rgba(255,255,255,0.7); }10 html {11 background: #1c1c1c url(images/bg.tile.jpg); }1213 body {14 margin: 0;15 padding-bottom: 30px;16 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";17 font-size: 14px;18 line-height: 1.5;antialiased textTj Holowaychukbefore adoption8d80f23
line 19why, one step back19 -webkit-font-smoothing: antialiased;Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 20–41why, one step back20 background: url(images/bg.jpg) 50% 0 no-repeat;21 color: #8b8b8b; }2223 * {24 outline: none; }2526 em {27 color: white; }2829 a img {30 border: none !important; }3132 a {33 font-weight: bold;34 text-decoration: none;35 color: white;36 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;37 -webkit-transition-duration: 0.15s;38 -webkit-transition-timing-function: ease-out; }39 a:hover {40 opacity: 0.8; }41HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
line 42why, one step back42 h1, h2, h3, h4 {Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 43–48why, one step back43 margin: 45px 0 0 0;44 color: white;45 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4647 h3 {48 font-size: 18px; }HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 49–52why, one step back49 h4 {50 margin-left: 10px;51 font-size: 14px;52 }Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 53–73why, one step back5354 pre {55 margin: 20px 10px;56 padding: 25px 20px;57 background: rgba(0,0,0,0.5);58 border: 1px solid #323232;59 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);60 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -webkit-border-radius: 5px;62 -moz-border-radius: 5px; }6364 code {65 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6667 ul {68 margin: 15px 0;69 padding: 0 0 0 35px; }70 ul li {71 margin: 0;72 padding: 2px 0;73 list-style: square; }Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 74–77why, one step back74 ul li ul {75 margin: 0;76 padding-left: 12px;77 }Route callback signature changedTj Holowaychukbefore adoption75661a2
line 78why, one step back78Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 79–80why, one step back79 .man-name, #Express { display:none; }80Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 81–82why, one step back81 .sect {82 margin-left: 40px; }Finished app page (for now)Tj Holowaychukbefore adoption7cbb737
lines 83–86why, one step back83 img {84 margin-left: 20px;85 margin-bottom: 15px;86 }Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 87–113why, one step back8788 #logo {89 display: block;90 margin-left: 30%;91 margin-bottom: 30px;92 width: 194px;93 height: 51px;94 background: url(images/logo.png) 0 0 no-repeat;95 text-indent: -99999px; }96 #logo:hover {97 opacity: 0.7; }98 #logo:active {99 opacity: 0.3; }100101 #ribbon {102 position: fixed;103 top: 0;104 right: 0;105 z-index: 2; }106107 #wrapper {108 width: 100%;109 min-height: 800px;110 background: url(images/top.png) 0 0 repeat-x; }111112 #container {113 margin: 0 auto;Regenerated docs againTj Holowaychukbefore adoption8ead901
line 114why, one step back114 padding-top: 80px;Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 115–118why, one step back115 width: 550px; }116117 #toc {118 position: fixed;Regenerated docs againTj Holowaychukbefore adoption8ead901
line 119why, one step back119 top: 0;Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 120–124why, one step back120 left: 0;121 margin: 0 0 0 15px;122 padding: 15px;123 height: 100%;124 background: rgba(0,0,0,0.2);Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 125why, one step back125 overflow: auto;Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 126–162why, one step back126 border-right: 1px solid rgba(255,255,255,0.05);127 }128 #toc li {129 padding: 0;130 list-style: none;131 }132 #toc li a {133 font-size: 11px;134 }135 #menu {136 margin-left: 65px;137 padding: 0;138 padding-bottom: 30px; }139 #menu li {140 display: inline;141 list-style: none; }142 #menu li a {143 display: block;144 float: left;145 margin: 0 2px;146 padding: 3px 15px;147 background: rgba(0,0,0,0.2);148 -webkit-border-radius: 8px;149 -moz-border-radius: 8px;150 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);151 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;153 -webkit-transition-duration: 0.15s;154 -webkit-transition-timing-function: ease-out; }155 #menu li a:hover,156 #menu li a.active {157 background: rgba(0,0,0,0.5); }158 #menu li a:active {159 background: rgba(0,0,0,0.1);160 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);161 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }162 </style>Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 163–174why, one step back163 <script>164 $(function(){165 $('.section').hide();166 $('.toggle, a.section-title').toggle(function(){167 $(this).siblings('ul').fadeIn(300);168 return false;169 }, function(){170 $(this).siblings('ul').fadeOut(300);171 return false;172 });173 });174 </script>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 175–187why, one step back175 </head>176 <body>177 <a href='http://github.com/visionmedia/express'> 178 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 179 </a>180 <div id="wrapper">181 <div id="container"><ul id="toc">182<li><a href="#Installation">Installation</a></li>183<li><a href="#Creating-An-Application">Creating An Application</a></li>184<li><a href="#Configuration">Configuration</a></li>185<li><a href="#Settings">Settings</a></li>186<li><a href="#Routing">Routing</a></li>187<li><a href="#Passing-Route-Control">Passing Route Control</a></li>Regenerated docsTj Holowaychukbefore adoption090debe
line 188why, one step back188<li><a href="#Middleware">Middleware</a></li>Regenerated docsTj Holowaychukbefore adoption334a18a
line 189why, one step back189<li><a href="#Route-Middleware">Route Middleware</a></li>HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
line 190why, one step back190<li><a href="#HTTP-Methods">HTTP Methods</a></li>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 191–194why, one step back191<li><a href="#Error-Handling">Error Handling</a></li>192<li><a href="#View-Rendering">View Rendering</a></li>193<li><a href="#View-Partials">View Partials</a></li>194<li><a href="#Template-Engines">Template Engines</a></li>Rebuilt docsTj Holowaychukbefore adoption2724ce3
line 195why, one step back195<li><a href="#Session-Support">Session Support</a></li>Started apps sectionTj Holowaychukbefore adoptiond3f139c
line 196why, one step back196<li><a href="#Migration-Guide">Migration Guide</a></li>Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 197–229why, one step back197<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">198<li><a href="#req-header-key-defaultValue-">header()</a></li>199<li><a href="#req-accepts-type-">accepts()</a></li>200<li><a href="#req-param-name-">param()</a></li>201<li><a href="#req-flash-type-msg-">flash()</a></li>202<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>203</ul></li>204<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">205<li><a href="#res-header-key-val-">header()</a></li>206<li><a href="#res-contentType-type-">contentType()</a></li>207<li><a href="#res-attachment-filename-">attachment()</a></li>208<li><a href="#res-sendfile-path-">sendfile()</a></li>209<li><a href="#res-download-file-filename-">download()</a></li>210<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>211<li><a href="#res-redirect-url-status-">redirect()</a></li>212<li><a href="#res-cookie-name-val-options-">cookie()</a></li>213<li><a href="#res-clearCookie-name-">clearCookie()</a></li>214<li><a href="#res-render-view-options-fn-">render()</a></li>215<li><a href="#res-partial-view-options-">partial()</a></li>216</ul></li>217<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">218<li><a href="#app-set-name-val-">set()</a></li>219<li><a href="#app-enable-name-">enable()</a></li>220<li><a href="#app-disable-name-">disable()</a></li>221<li><a href="#app-configure-env-function-function-">configure()</a></li>222<li><a href="#app-redirect-name-val-">redirect()</a></li>223<li><a href="#app-error-function-">error()</a></li>224<li><a href="#app-helpers-obj-">helpers()</a></li>225<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>226<li><a href="#app-mounted-fn-">mounted()</a></li>227<li><a href="#app-register-ext-exports-">register()</a></li>228<li><a href="#app-listen-port-host-">listen()</a></li>229</ul></li>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 230–239why, one step back230</ul>231 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 232 <p id="tagline">233 High performance, high class web development for234 <a href="http://nodejs.org">Node.js</a>235 </p>236 <ul id="menu">237 <li><a href="index.html">Home</a></li>238 <li><a href="guide.html">Guide</a></li>239 <li><a href="contrib.html">Contributing</a></li>Started apps sectionTj Holowaychukbefore adoptiond3f139c
line 240why, one step back240 <li><a href="applications.html">Applications</a></li>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 241–242why, one step back241 </ul>242<div class='mp'>Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 243–246why, one step back243<h2 id="Express">Express</h2>244<p class="man-name">245 <code>guide</code>246</p>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 247–255why, one step back247<h3 id="Installation">Installation</h3>248249<p>curl:</p>250251<pre><code>$ curl -# http://expressjs.com/install.sh | sh252</code></pre>253254<p>npm:</p>255Added "Apps using express" section, PM me to add to the listTj Holowaychukbefore adoption7328842
line 256why, one step back256<pre><code>$ npm install expressRoute callback signature changedTj Holowaychukbefore adoption75661a2
lines 257–293why, one step back257</code></pre>258259<p>git clone, first update the submodules:</p>260261<pre><code>$ git submodule update --init262$ make install263$ make install-support264</code></pre>265266<h3 id="Creating-An-Application">Creating An Application</h3>267268<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however269follows the same idiom by providing <em>express.createServer()</em> as shown below. This means270that you can utilize Express server's transparently with other libraries.</p>271272<pre><code>var app = require('express').createServer();273274app.get('/', function(req, res){275 res.send('hello world');276});277278app.listen(3000);279</code></pre>280281<h3 id="Configuration">Configuration</h3>282283<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers284can use the <em>configure()</em> method to setup needs required by the current environment. When285<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment286prior to the environment specific callback.</p>287288<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces289in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.290Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,291otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>292293<pre><code>app.configure(function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 294–295why, one step back294 app.use(express.methodOverride());295 app.use(express.bodyDecoder());Route callback signature changedTj Holowaychukbefore adoption75661a2
line 296why, one step back296 app.use(app.router);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 297why, one step back297 app.use(express.staticProvider(__dirname + '/public'));Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 298–300why, one step back298});299300app.configure('development', function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 301why, one step back301 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 302–304why, one step back302});303304app.configure('production', function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 305why, one step back305 app.use(express.errorHandler());Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 306–323why, one step back306});307</code></pre>308309<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>310311<pre><code>app.configure(function(){312 app.set('views', __dirname + '/views');313 app.set('views');314 // => "... views directory ..."315316 app.enable('some feature');317 // same as app.set('some feature', true);318319 app.disable('some feature');320 // same as app.set('some feature', false);321});322</code></pre>323Rebuilt docsTj Holowaychukbefore adoption2724ce3
line 324why, one step back324<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>Route callback signature changedTj Holowaychukbefore adoption75661a2
line 325why, one step back325Rebuilt docsTj Holowaychukbefore adoption2724ce3
line 326why, one step back326<pre><code>$ NODE_ENV=production node app.jsRoute callback signature changedTj Holowaychukbefore adoption75661a2
lines 327–328why, one step back327</code></pre>328Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 329–330why, one step back329<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>330Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 331–339why, one step back331<h3 id="Settings">Settings</h3>332333<p>Express supports the following settings out of the box:</p>334335<ul>336<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>337<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>338<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>339<li><em>view engine</em> Default view engine name for views rendered without extensions</li>Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 340–341why, one step back340<li><em>view options</em> An object specifying global view options</li>341<li><em>partials</em> Root view partials directory defaulting to <em>views</em>/partials.</li>Updated docsTj Holowaychukbefore adoptionf0eab06
line 342why, one step back342<li><em>stream threshold</em> Bytesize indicating when a file should be streamed for <em>res.sendfile()</em> using <em>fs.ReadStream()</em> and <em>sys.pump()</em>.</li>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 343–349why, one step back343</ul>344345346<h3 id="Routing">Routing</h3>347348<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.349For example we may want to render a user's account for the path <em>/user/12</em>, thisUpdated docsTj Holowaychukbefore adoptiond691ecb
lines 350–351why, one step back350can be done by defining the route below. The values associated to the named placeholders351are available as <code>req.params</code>.</p>Route callback signature changedTj Holowaychukbefore adoption75661a2
line 352why, one step back352Updated docsTj Holowaychukbefore adoptiond691ecb
lines 353–354why, one step back353<pre><code>app.get('/user/:id', function(req, res){354 res.send('user ' + req.params.id);Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 355–364why, one step back355});356</code></pre>357358<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example359when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>360361<pre><code>\/user\/([^\/]+)\/?362</code></pre>363364<p>Regular expression literals may also be passed for complex uses. Since captureUpdated docsTj Holowaychukbefore adoptiond691ecb
line 365why, one step back365groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>.</p>Route callback signature changedTj Holowaychukbefore adoption75661a2
line 366why, one step back366Updated docsTj Holowaychukbefore adoptiond691ecb
lines 367–368why, one step back367<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){368 res.send(req.params);Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 369–417why, one step back369});370</code></pre>371372<p>Curl requests against the previously defined route:</p>373374<pre><code> $ curl http://dev:3000/user375 [null,null]376 $ curl http://dev:3000/users377 [null,null]378 $ curl http://dev:3000/users/1379 ["1",null]380 $ curl http://dev:3000/users/1..15381 ["1","15"]382</code></pre>383384<p>Below are some route examples, and the associated paths that they385may consume:</p>386387<pre><code> "/user/:id"388 /user/12389390 "/users/:id?"391 /users/5392 /users393394 "/files/*"395 /files/jquery.js396 /files/javascripts/jquery.js397398 "/file/*.*"399 /files/jquery.js400 /files/javascripts/jquery.js401402 "/user/:id/:operation?"403 /user/1404 /user/1/edit405406 "/products.:format"407 /products.json408 /products.xml409410 "/products.:format?"411 /products.json412 /products.xml413 /products414</code></pre>415416<h3 id="Passing-Route-Control">Passing Route Control</h3>417Updated docsTj Holowaychukbefore adoptiond691ecb
lines 418–419why, one step back418<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,419the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,Regenerated docsTj Holowaychukbefore adoption334a18a
line 420why, one step back420and middleware continue to be invoked. 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>.</p>Route callback signature changedTj Holowaychukbefore adoption75661a2
line 421why, one step back421Updated docsTj Holowaychukbefore adoptionb819366
line 422why, one step back422<pre><code>app.get('/users/:id?', function(req, res, next){Updated docsTj Holowaychukbefore adoptiond691ecb
lines 423–424why, one step back423 var id = req.params.id;424 if (id) {Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 425–430why, one step back425 // do something426 } else {427 next();428 }429});430Updated docsTj Holowaychukbefore adoptiond691ecb
line 431why, one step back431app.get('/users', function(req, res){Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 432–434why, one step back432 // do something else433});434</code></pre>Regenerated docsTj Holowaychukbefore adoption334a18a
line 435why, one step back435Regenerated docsTj Holowaychukbefore adoption090debe
lines 436–464why, one step back436<h3 id="Middleware">Middleware</h3>437438<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be439passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>440441<pre><code> var express = require('express');442443var app = express.createServer(444 express.logger(),445 express.bodyDecoder()446 );447</code></pre>448449<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>450451<pre><code>app.use(express.logger({ format: ':method :uri' }));452</code></pre>453454<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>455456<pre><code>var connect = require('connect');457app.use(connect.logger());458</code></pre>459460<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>461462<pre><code>app.use(express.logger());463</code></pre>464Regenerated docsTj Holowaychukbefore adoption334a18a
lines 465–468why, one step back465<h3 id="Route-Middleware">Route Middleware</h3>466467<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>468Regenerated docsTj Holowaychukbefore adoption0faac20
line 469why, one step back469<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>Regenerated docsTj Holowaychukbefore adoption334a18a
line 470why, one step back470Regenerated docsTj Holowaychukbefore adoption0faac20
lines 471–472why, one step back471<pre><code>app.get('/user/:id', function(req, res, next){472 loadUser(req.params.id, function(err, user){Regenerated guideTj Holowaychukbefore adoptionab3337d
lines 473–474why, one step back473 if (err) return next(err);474 res.send('Viewing user ' + user.name);Regenerated docsTj Holowaychukbefore adoption0faac20
lines 475–476why, one step back475 });476});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 477–480why, one step back477</code></pre>478479<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>480Regenerated docsTj Holowaychukbefore adoption0faac20
lines 481–490why, one step back481<pre><code>function loadUser(req, res, next) {482 // You would fetch your user from the db483 var user = users[req.params.id];484 if (user) {485 req.user = user;486 next();487 } else {488 next(new Error('Failed to load user ' + req.params.id));489 }490}Regenerated docsTj Holowaychukbefore adoption334a18a
line 491why, one step back491Regenerated docsTj Holowaychukbefore adoption0faac20
lines 492–494why, one step back492app.get('/user/:id', loadUser, function(req, res){493 res.send('Viewing user ' + req.user.name);494});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 495–498why, one step back495</code></pre>496497<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>498Regenerated docsTj Holowaychukbefore adoption0faac20
lines 499–500why, one step back499<pre><code>function andRestrictToSelf(req, res, next) {500 req.authenticatedUser.id == req.user.idRegenerated guideTj Holowaychukbefore adoptionab3337d
lines 501–502why, one step back501 ? next()502 : next(new Error('Unauthorized'));Regenerated docsTj Holowaychukbefore adoption0faac20
line 503why, one step back503}Regenerated docsTj Holowaychukbefore adoption334a18a
line 504why, one step back504Regenerated docsTj Holowaychukbefore adoption0faac20
lines 505–507why, one step back505app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){506 res.send('Editing user ' + req.user.name);507});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 508–511why, one step back508</code></pre>509510<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>511Regenerated docsTj Holowaychukbefore adoption0faac20
lines 512–514why, one step back512<pre><code>function andRestrictTo(role) {513 return function(req, res, next) {514 req.authenticatedUser.role == roleRegenerated guideTj Holowaychukbefore adoptionab3337d
lines 515–516why, one step back515 ? next()516 : next(new Error('Unauthorized'));Regenerated docsTj Holowaychukbefore adoption0faac20
lines 517–518why, one step back517 }518}Regenerated docsTj Holowaychukbefore adoption334a18a
line 519why, one step back519Regenerated docsTj Holowaychukbefore adoption0faac20
lines 520–522why, one step back520app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){521 res.send('Deleted user ' + req.user.name);522});Regenerated docsTj Holowaychukbefore adoption334a18a
lines 523–526why, one step back523</code></pre>524525<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>526Regenerated docsTj Holowaychukbefore adoption0faac20
lines 527–529why, one step back527<pre><code>var a = [middleware1, middleware2]528 , b = [middleware3, middleware4]529 , all = [a, b];Regenerated docsTj Holowaychukbefore adoption334a18a
line 530why, one step back530Regenerated docsTj Holowaychukbefore adoption0faac20
lines 531–532why, one step back531app.get('/foo', a, function(){});532app.get('/bar', a, function(){});Regenerated docsTj Holowaychukbefore adoption334a18a
line 533why, one step back533Regenerated docsTj Holowaychukbefore adoption0faac20
lines 534–537why, one step back534app.get('/', a, middleware3, middleware4, function(){});535app.get('/', a, b, function(){});536app.get('/', all, function(){});537</code></pre>Regenerated docsTj Holowaychukbefore adoption334a18a
lines 538–539why, one step back538539<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>Route callback signature changedTj Holowaychukbefore adoption75661a2
line 540why, one step back540HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 541–546why, one step back541<h3 id="HTTP-Methods">HTTP Methods</h3>542543<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>544545<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>546Regenerated guideTj Holowaychukbefore adoptionab3337d
lines 547–551why, one step back547<pre><code> <form method="post" action="/">548 <input type="text" name="user[name]" />549 <input type="text" name="user[email]" />550 <input type="submit" value="Submit" />551 </form>HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 552–585why, one step back552</code></pre>553554<p>By default Express does not know what to do with this request body, so we should add the <em>bodyDecoder</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>555556<pre><code>app.use(express.bodyDecoder());557</code></pre>558559<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>560561<pre><code>app.post('/', function(req, res){562 console.log(req.body.user);563 res.redirect('back');564});565</code></pre>566567<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>bodyDecoder</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>568569<pre><code>app.use(express.bodyDecoder());570app.use(express.methodOverride());571</code></pre>572573<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>574575<pre><code><form method="post" action="/">576 <input type="hidden" name="_method" value="put" />577 <input type="text" name="user[name]" />578 <input type="text" name="user[email]" />579 <input type="submit" value="Submit" /> 580</form>581582app.put('/', function(){583 console.log(req.body.user);584 res.redirect('back');585});Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 586–587why, one step back586</code></pre>587Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 588–614why, one step back588<h3 id="Error-Handling">Error Handling</h3>589590<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,591or passed to <em>next(err)</em>. Below is an example which serves different pages based on our592ad-hoc <em>NotFound</em> exception:</p>593594<pre><code>function NotFound(msg){595 this.name = 'NotFound';596 Error.call(this, msg);597 Error.captureStackTrace(this, arguments.callee);598}599600sys.inherits(NotFound, Error);601602app.get('/404', function(req, res){603 throw new NotFound;604});605606app.get('/500', function(req, res){607 throw new Error('keyboard cat!');608});609</code></pre>610611<p>We can call <em>app.error()</em> several times as shown below.612Here we check for an instanceof <em>NotFound</em> and show the613404 page, or we pass on to the next error handler.</p>614Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 615–619why, one step back615<p>Note that these handlers can be defined anywhere, as they616will be placed below the route handlers on <em>listen()</em>. This617allows for definition within <em>configure()</em> blocks so we can618handle exceptions in different ways based on the environment.</p>619Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 620–644why, one step back620<pre><code>app.error(function(err, req, res, next){621 if (err instanceof NotFound) {622 res.render('404.jade');623 } else {624 next(err);625 }626});627</code></pre>628629<p>Here we assume all errors as 500 for the simplicity of630this demo, however you can choose whatever you like</p>631632<pre><code>app.error(function(err, req, res){633 res.render('500.jade', {634 locals: {635 error: err636 } 637 });638});639</code></pre>640641<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware642to report on exceptions. For example if we wish to output exceptions643in "development" mode to <em>stderr</em> we can use:</p>644Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 645why, one step back645<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 646–650why, one step back646</code></pre>647648<p>Also during development we may want fancy html pages to show exceptions649that are passed or thrown, so we can set <em>showStack</em> to true:</p>650Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 651why, one step back651<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 652–660why, one step back652</code></pre>653654<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>655is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>656657<h3 id="View-Rendering">View Rendering</h3>658659<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name660of the module that will be required. For example the view <em>layout.ejs</em> willAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 661–662why, one step back661tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.render(str, options)</em> to comply with Express, however662<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.</p>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 663–696why, one step back663664<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,665and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as666the <em>body</em> local variable in <em>layout.haml</em>.</p>667668<pre><code>app.get('/', function(req, res){669 res.render('index.haml', {670 locals: { title: 'My Site' }671 });672});673</code></pre>674675<p>The new <em>view engine</em> setting allows us to specify our default template engine,676so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>677678<pre><code>app.set('view engine', 'jade');679</code></pre>680681<p>Allowing us to render with:</p>682683<pre><code>res.render('index');684</code></pre>685686<p>vs:</p>687688<pre><code>res.render('index.jade');689</code></pre>690691<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still692mix and match template engines:</p>693694<pre><code>res.render('another-page.ejs');695</code></pre>696Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 697–708why, one step back697<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>698699<pre><code>app.set('view options', {700 layout: false701});702</code></pre>703704<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>705706<pre><code>res.render('myview.ejs', { layout: true });707</code></pre>708Rebuilt docsTj Holowaychukbefore adoption2724ce3
lines 709–723why, one step back709<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>710711<pre><code>res.render('page', { layout: 'mylayout' });712</code></pre>713714<p>Otherwise we must specify the extension:</p>715716<pre><code>res.render('page', { layout: 'mylayout.jade' });717</code></pre>718719<p>These paths may also be absolute:</p>720721<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });722</code></pre>723Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 724–731why, one step back724<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>725726<pre><code>app.set('view options', {727 open: '{{',728 close: '}}'729});730</code></pre>731Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 732–749why, one step back732<h3 id="View-Partials">View Partials</h3>733734<p>The Express view system has built-in support for partials and collections, which are735sort of "mini" views representing a document fragment. For example rather than iterating736in a view to display comments, we would use a partial with collection support:</p>737738<pre><code>partial('comment.haml', { collection: comments });739</code></pre>740741<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,742however if we wished we could use an ejs partial, within a haml view for example.</p>743744<pre><code>partial('comment', { collection: comments });745</code></pre>746747<p>And once again even further, when rendering a collection we can simply pass748an array, if no other options are desired:</p>749Regenerated docsTj Holowaychukbefore adoption2a40cec
line 750why, one step back750<pre><code>partial('comment', comments);Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 751–758why, one step back751</code></pre>752753<p>When using the partial collection support a few "magic" variables are provided754for free:</p>755756<ul>757<li><em>firstInCollection</em> True if this is the first object</li>758<li><em>indexInCollection</em> Index of the object in the collection</li>Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
line 759why, one step back759<li><em>lastInCollection</em> True if this is the last object</li>Regenerated docsTj Holowaychukbefore adoption2a40cec
line 760why, one step back760<li><em>collectionLength</em> Length of the collection</li>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 761–763why, one step back761</ul>762763Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 764–765why, one step back764<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>765Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 766–770why, one step back766<h3 id="Template-Engines">Template Engines</h3>767768<p>Below are a few template engines commonly used with Express:</p>769770<ul>Merge branch 'fix-toc'Tj Holowaychukbefore adoptionbb18f87
lines 771–772why, one step back771<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>772<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>Route callback signature changedTj Holowaychukbefore adoption75661a2
line 773why, one step back773<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>Regenerated docsTj Holowaychukbefore adoption2a40cec
line 774why, one step back774<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 775–776why, one step back775</ul>776Rebuilt docsTj Holowaychukbefore adoption2724ce3
lines 777–791why, one step back777778<h3 id="Session-Support">Session Support</h3>779780<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieDecoder</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>781782<pre><code>app.use(express.cookieDecoder());783app.use(express.session());784</code></pre>785786<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>787788<pre><code>var RedisStore = require('connect-redis');789app.use(express.cookieDecoder());790app.use(express.session({ store: new RedisStore }));791</code></pre>Route callback signature changedTj Holowaychukbefore adoption75661a2
line 792why, one step back792Regenerated guideTj Holowaychukbefore adoptionf179979
lines 793–795why, one step back793<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>794795<pre><code>var RedisStore = require('connect-redis');Regenerated docsTj Holowaychukbefore adoption1c9831a
line 796why, one step back796app.use(express.bodyDecoder());Regenerated guideTj Holowaychukbefore adoptionf179979
lines 797–819why, one step back797app.use(express.cookieDecoder());798app.use(express.session({ store: new RedisStore }));799800app.post('/add-to-cart', function(req, res){801 // Perhaps we posted several items with a form802 // (use the bodyDecoder() middleware for this)803 var items = req.body.items;804 req.session.items = items;805 res.redirect('back');806});807808app.get('/add-to-cart', function(req, res){809 // When redirected back to GET /add-to-cart810 // we could check req.session.items && req.session.items.length811 // to print out a message812 if (req.session.items && req.session.items.length) {813 req.flash('info', 'You have %s items in your cart', req.session.items.length);814 }815 res.render('shopping-cart');816});817</code></pre>818819<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/session.html">Connect Session</a> documentation.</p>Started apps sectionTj Holowaychukbefore adoptiond3f139c
lines 820–823why, one step back820821<h3 id="Migration-Guide">Migration Guide</h3>822823<p> Pre-beta Express developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application.</p>Regenerated guideTj Holowaychukbefore adoptionf179979
line 824why, one step back824Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 825–863why, one step back825<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>826827<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>828829<pre><code>req.header('Host');830req.header('host');831req.header('Accept', '*/*');832</code></pre>833834<h3 id="req-accepts-type-">req.accepts(type)</h3>835836<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>837838<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise839the given <em>type</em> is matched by an exact match, and then subtypes. You840may pass the subtype such as "html" which is then converted internally841to "text/html" using the mime lookup table.</p>842843<pre><code>// Accept: text/html844req.accepts('html');845// => true846847// Accept: text/*; application/json848req.accepts('html');849req.accepts('text/html');850req.accepts('text/plain');851req.accepts('application/json');852// => true853854req.accepts('image/png');855req.accepts('png');856// => false857</code></pre>858859<h3 id="req-param-name-">req.param(name)</h3>860861<p>Return the value of param <em>name</em> when present.</p>862863<ul>Updated docsTj Holowaychukbefore adoptiond691ecb
lines 864–866why, one step back864<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>865<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>866<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 867–871why, one step back867</ul>868869870<p>To utilize urlencoded request bodies, <em>req.body</em>871should be an object. This can be done by usingAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
line 872why, one step back872the <em>express.bodyDecoder</em> middleware.</p>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 873–892why, one step back873874<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>875876<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>877878<pre><code>req.flash('info', 'email sent');879req.flash('error', 'email delivery failed');880req.flash('info', 'email re-sent');881// => 2882883req.flash('info');884// => ['email sent', 'email re-sent']885886req.flash('info');887// => []888889req.flash();890// => { error: ['email delivery failed'], info: [] }891</code></pre>892Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 893–897why, one step back893<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>894895<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);896</code></pre>897Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 898–943why, one step back898<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>899900<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header901to see if it was issued by an <em>XMLHttpRequest</em>:</p>902903<pre><code>req.xhr904req.isXMLHttpRequest905</code></pre>906907<h3 id="res-header-key-val-">res.header(key[, val])</h3>908909<p>Get or set the response header <em>key</em>.</p>910911<pre><code>res.header('Content-Length');912// => undefined913914res.header('Content-Length', 123);915// => 123916917res.header('Content-Length');918// => 123919</code></pre>920921<h3 id="res-contentType-type-">res.contentType(type)</h3>922923<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>924925<pre><code> var filename = 'path/to/image.png';926 res.contentType(filename);927 // res.headers['Content-Type'] is now "image/png"928</code></pre>929930<h3 id="res-attachment-filename-">res.attachment([filename])</h3>931932<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>933934<pre><code> res.attachment('path/to/my/image.png');935</code></pre>936937<h3 id="res-sendfile-path-">res.sendfile(path)</h3>938939<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>940941<pre><code>res.sendfile('path/to/my.file');942</code></pre>943Updated docsTj Holowaychukbefore adoptionf0eab06
lines 944–955why, one step back944<p>This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has <strong>not</strong> been streamed, <em>next(err)</em> will be called on an exception.</p>945946<pre><code>res.sendfile(path, function(err, path){947 if (err) {948 // handle the error949 } else {950 console.log('transferred %s', path);951 }952});953</code></pre>954955<p>When the filesize exceeds the <em>stream threshold</em> (defaulting to 32k), the file will be streamed using <em>fs.ReadStream</em> and <em>sys.pump()</em>.</p>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 956–976why, one step back956957<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>958959<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>960961<pre><code>res.download('path/to/image.png');962res.download('path/to/image.png', 'foo.png');963</code></pre>964965<p>This is equivalent to:</p>966967<pre><code>res.attachment(file);968res.sendfile(file);969</code></pre>970971<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>972973<p>The <code>res.send()</code> method is a high level response utility allowing you to pass974objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status975code based responses. The following are all valid uses:</p>976Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 977–978why, one step back977<pre><code> res.send(); // 204978 res.send(new Buffer('wahoo'));Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 979–1004why, one step back979 res.send({ some: 'json' });980 res.send('<p>some html</p>');981 res.send('Sorry, cant find that', 404);982 res.send('text', { 'Content-Type': 'text/plain' }, 201);983 res.send(404);984</code></pre>985986<p>By default the <em>Content-Type</em> response header is set, however if explicitly987assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>988it will not be set again.</p>989990<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>991992<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>993994<pre><code>res.redirect('/', 301);995res.redirect('/account');996res.redirect('http://google.com');997res.redirect('home');998res.redirect('back');999</code></pre>10001001<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1002The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1003the "home" setting and defaults to "/".</p>1004Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1005–1028why, one step back1005<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>10061007<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>10081009<pre><code>// "Remember me" for 15 minutes 1010res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1011</code></pre>10121013<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>10141015<pre><code>app.use(express.cookieDecoder());10161017app.get('/', function(req, res){1018 // use req.cookies.rememberme1019});1020</code></pre>10211022<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>10231024<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>10251026<pre><code>res.clearCookie('rememberme');1027</code></pre>1028Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1029–1038why, one step back1029<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>10301031<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1032When a callback function is given a response will <em>not</em> be made1033automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>10341035<p> Most engines accept one or more of the following options,1036 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>10371038<ul>HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
line 1039why, one step back1039<li><em>scope</em> Template evaluation context (value of <em>this</em>)</li>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1040–1041why, one step back1040<li><em>locals</em> Object containing local variables</li>1041<li><em>debug</em> Output debugging information</li>Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
lines 1042–1043why, one step back1042<li><em>status</em> Response status code, defaults to 200</li>1043<li><em>headers</em> Response headers object</li>Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1044–1068why, one step back1044</ul>104510461047<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>10481049<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1050to the view as a local variable.</p>10511052<ul>1053<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>10541055<ul>1056<li>as: 'something' will add the <em>something</em> local variable</li>1057<li>as: this will use the collection value as the template context</li>1058<li>as: global will merge the collection value's properties with <em>locals</em></li>1059</ul>1060</li>1061<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1062For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1063</ul>106410651066<p>The following are equivalent, and the name of collection value when passed1067to the partial will be <em>movie</em> as derived from the name.</p>1068Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 1069–1071why, one step back1069<pre><code>partial('theatre/movie.jade', { collection: movies });1070partial('theatre/movie.jade', movies);1071partial('movie.jade', { collection: movies });Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1072–1101why, one step back1072partial('movie.jade', movies);1073partial('movie', movies);1074// In view: movie.director1075</code></pre>10761077<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>10781079<pre><code>partial('movie', { collection: movies, as: 'video' });1080// In view: video.director1081</code></pre>10821083<p>Also we can make our movie the value of <em>this</em> within our view so that instead1084of <em>movie.director</em> we could use <em>this.director</em>.</p>10851086<pre><code>partial('movie', { collection: movies, as: this });1087// In view: this.director1088</code></pre>10891090<p>Another alternative is to "explode" the properties of the collection item into1091pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>10921093<pre><code>partials('movie', { collection: movies, as: global });1094// In view: director1095</code></pre>10961097<h3 id="app-set-name-val-">app.set(name[, val])</h3>10981099<p>Apply an application level setting <em>name</em> to <em>val</em>, or1100get the value of <em>name</em> when <em>val</em> is not present:</p>1101Updated docsTj Holowaychukbefore adoption3234329
lines 1102–1104why, one step back1102<pre><code>app.set('views', __dirname + '/views');1103app.set('views');1104// => ...path...Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1105–1150why, one step back1105</code></pre>11061107<h3 id="app-enable-name-">app.enable(name)</h3>11081109<p>Enable the given setting <em>name</em>:</p>11101111<pre><code>app.enable('some arbitrary setting');1112app.set('some arbitrary setting');1113// => true1114</code></pre>11151116<h3 id="app-disable-name-">app.disable(name)</h3>11171118<p>Disable the given setting <em>name</em>:</p>11191120<pre><code>app.disable('some setting');1121app.set('some setting');1122// => false1123</code></pre>11241125<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>11261127<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>11281129<pre><code>app.configure(function(){1130 // executed for each env1131});11321133app.configure('development', function(){1134 // executed for 'development' only1135});1136</code></pre>11371138<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>11391140<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>11411142<pre><code>app.redirect('google', 'http://google.com');1143</code></pre>11441145<p>Now in a route we may call:</p>11461147<p> res.redirect('google');</p>11481149<p>We may also map dynamic redirects:</p>1150Updated docsTj Holowaychukbefore adoptiond691ecb
lines 1151–1152why, one step back1151<pre><code>app.redirect('comments', function(req, res){1152 return '/post/' + req.params.id + '/comments';Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1153–1195why, one step back1153});1154</code></pre>11551156<p>So now we may do the following, and the redirect will dynamically adjust to1157the context of the request. If we called this route with <em>GET /post/12</em> our1158redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>11591160<pre><code>app.get('/post/:id', function(req, res){1161 res.redirect('comments');1162});1163</code></pre>11641165<h3 id="app-error-function-">app.error(function)</h3>11661167<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1168Note that we may set several error handlers by making several calls to this method, however the handler1169should call <em>next(err)</em> if it does not wish to deal with the exception:</p>11701171<pre><code>app.error(function(err, req, res, next){1172 res.send(err.message, 500);1173});1174</code></pre>11751176<h3 id="app-helpers-obj-">app.helpers(obj)</h3>11771178<p>Registers static view helpers.</p>11791180<pre><code>app.helpers({1181 name: function(first, last){ return first + ', ' + last },1182 firstName: 'tj',1183 lastName: 'holowaychuk'1184});1185</code></pre>11861187<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1188as well as the <em>name()</em> function exposed.</p>11891190<pre><code><%= name(firstName, lastName) %>1191</code></pre>11921193<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>11941195<p>Registers dynamic view helpers. Dynamic view helpersUpdated docsTj Holowaychukbefore adoptiond691ecb
line 1196why, one step back1196are simply functions which accept <em>req</em>, <em>res</em>, and areRoute callback signature changedTj Holowaychukbefore adoption75661a2
lines 1197–1200why, one step back1197evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1198becomes the local variable it is associated with.</p>11991200<pre><code>app.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 1201why, one step back1201 session: function(req, res){Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1202–1224why, one step back1202 return req.session;1203 }1204});1205</code></pre>12061207<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>12081209<pre><code><%= session.name %>1210</code></pre>12111212<h3 id="app-mounted-fn-">app.mounted(fn)</h3>12131214<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>12151216<pre><code>var app = express.createServer(),1217 blog = express.createServer();12181219blog.mounted(function(parent){1220 // parent is app1221 // "this" is blog1222});12231224app.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1225–1249why, one step back1225</code></pre>12261227<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>12281229<p>Register the given template engine <em>exports</em>1230as <em>ext</em>. For example we may wish to map ".html"1231files to jade:</p>12321233<pre><code> app.register('.html', require('jade'));1234</code></pre>12351236<p>This is also useful for libraries that may not1237match extensions correctly. For example my haml.js1238library is installed from npm as "hamljs" so instead1239of layout.hamljs, we can register the engine as ".haml":</p>12401241<pre><code> app.register('.haml', require('haml-js'));1242</code></pre>12431244<p>For engines that do not comply with the Express1245specification, we can also wrap their api this way.</p>12461247<pre><code> app.register('.foo', {1248 render: function(str, options) {1249 // perhaps their api isRegenerated docsTj Holowaychukbefore adoption5152823
line 1250why, one step back1250 // return foo.toHTML(str, options);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1251–1252why, one step back1251 }1252 });Route callback signature changedTj Holowaychukbefore adoption75661a2
lines 1253–1286why, one step back1253</code></pre>12541255<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>12561257<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1258connections will be accepted via <em>INADDR_ANY</em>.</p>12591260<pre><code>app.listen();1261app.listen(3000);1262app.listen(3000, 'n.n.n.n');1263</code></pre>12641265<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>12661267<pre><code>app.listen('/tmp/express.sock');1268</code></pre>12691270<p>Then try it out:</p>12711272<pre><code>$ telnet /tmp/express.sock1273GET / HTTP/1.112741275HTTP/1.1 200 OK1276Content-Type: text/plain1277Content-Length: 1112781279Hello World1280</code></pre>12811282</div>1283 </div>1284 </div>1285 </body>1286</html>