guide.html
This file
Path
docs/guide.html
1,415 lines · 47.4 KiB · HTML
Last changed by
Added screencasts pageTj Holowaychukbefore adoption4144af3
History of this fileTake it
The walk stopped after 200 commits: lines older than 090debe point at it.
Regenerated docsTj Holowaychukbefore adoption090debe
lines 1–82why, one step back1<html>2 <head>3 <title>Express - node web framework</title>4 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>5 <style>6 #tagline {7 margin-left: 75px;8 margin-bottom: 30px;9 color: rgba(255,255,255,0.7); }10 html {11 background: #1c1c1c url(images/bg.tile.jpg); }1213 body {14 margin: 0;15 padding-bottom: 30px;16 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";17 font-size: 14px;18 line-height: 1.5;19 -webkit-font-smoothing: antialiased;20 background: url(images/bg.jpg) 50% 0 no-repeat;21 color: #8b8b8b; }2223 * {24 outline: none; }2526 em {27 color: white; }2829 a img {30 border: none !important; }3132 a {33 font-weight: bold;34 text-decoration: none;35 color: white;36 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;37 -webkit-transition-duration: 0.15s;38 -webkit-transition-timing-function: ease-out; }39 a:hover {40 opacity: 0.8; }4142 h1, h2, h3, h4 {43 margin: 45px 0 0 0;44 color: white;45 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4647 h3 {48 font-size: 18px; }49 h4 {50 margin-left: 10px;51 font-size: 14px;52 }5354 pre {55 margin: 20px 10px;56 padding: 25px 20px;57 background: rgba(0,0,0,0.5);58 border: 1px solid #323232;59 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);60 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -webkit-border-radius: 5px;62 -moz-border-radius: 5px; }6364 code {65 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6667 ul {68 margin: 15px 0;69 padding: 0 0 0 35px; }70 ul li {71 margin: 0;72 padding: 2px 0;73 list-style: square; }74 ul li ul {75 margin: 0;76 padding-left: 12px;77 }7879 .man-name, #Express { display:none; }8081 .sect {82 margin-left: 40px; }Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc
lines 83–86why, one step back83 img {84 margin-left: 20px;85 margin-bottom: 15px;86 }Regenerated docsTj Holowaychukbefore adoption090debe
lines 87–135why, 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;114 padding-top: 80px;115 width: 550px; }116117 #toc {118 position: fixed;119 top: 0;120 left: 0;121 margin: 0 0 0 15px;122 padding: 15px;123 height: 100%;124 background: rgba(0,0,0,0.2);125 overflow: auto;126 border-right: 1px solid rgba(255,255,255,0.05);127 }128 #toc li {129 padding: 0;130 list-style: none;131 }132 #toc li a {133 font-size: 11px;134 }135 #menu {Added screencasts pageTj Holowaychukbefore adoption4144af3
line 136why, one step back136 margin-left: 80px;Regenerated docsTj Holowaychukbefore adoption090debe
lines 137–195why, one step back137 padding: 0;138 padding-bottom: 30px; }139 #menu li {140 display: inline;141 list-style: none; }142 #menu li a {143 display: block;144 float: left;145 margin: 0 2px;146 padding: 3px 15px;147 background: rgba(0,0,0,0.2);148 -webkit-border-radius: 8px;149 -moz-border-radius: 8px;150 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);151 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;153 -webkit-transition-duration: 0.15s;154 -webkit-transition-timing-function: ease-out; }155 #menu li a:hover,156 #menu li a.active {157 background: rgba(0,0,0,0.5); }158 #menu li a:active {159 background: rgba(0,0,0,0.1);160 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);161 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }162 </style>163 <script>164 $(function(){165 $('.section').hide();166 $('.toggle, a.section-title').toggle(function(){167 $(this).siblings('ul').fadeIn(300);168 return false;169 }, function(){170 $(this).siblings('ul').fadeOut(300);171 return false;172 });173 });174 </script>175 </head>176 <body>177 <a href='http://github.com/visionmedia/express'> 178 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 179 </a>180 <div id="wrapper">181 <div id="container"><ul id="toc">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>188<li><a href="#Middleware">Middleware</a></li>189<li><a href="#Route-Middleware">Route Middleware</a></li>190<li><a href="#HTTP-Methods">HTTP Methods</a></li>191<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>195<li><a href="#Session-Support">Session Support</a></li>Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc
line 196why, one step back196<li><a href="#Migration-Guide">Migration Guide</a></li>Regenerated docsTj Holowaychukbefore adoption090debe
lines 197–199why, 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>Added req.is() docsTj Holowaychukbefore adoption806aefa
line 200why, one step back200<li><a href="#req-is-type-">is()</a></li>Regenerated docsTj Holowaychukbefore adoption090debe
lines 201–239why, one step back201<li><a href="#req-param-name-">param()</a></li>202<li><a href="#req-flash-type-msg-">flash()</a></li>203<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>204</ul></li>205<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">206<li><a href="#res-header-key-val-">header()</a></li>207<li><a href="#res-contentType-type-">contentType()</a></li>208<li><a href="#res-attachment-filename-">attachment()</a></li>209<li><a href="#res-sendfile-path-">sendfile()</a></li>210<li><a href="#res-download-file-filename-">download()</a></li>211<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>212<li><a href="#res-redirect-url-status-">redirect()</a></li>213<li><a href="#res-cookie-name-val-options-">cookie()</a></li>214<li><a href="#res-clearCookie-name-">clearCookie()</a></li>215<li><a href="#res-render-view-options-fn-">render()</a></li>216<li><a href="#res-partial-view-options-">partial()</a></li>217</ul></li>218<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">219<li><a href="#app-set-name-val-">set()</a></li>220<li><a href="#app-enable-name-">enable()</a></li>221<li><a href="#app-disable-name-">disable()</a></li>222<li><a href="#app-configure-env-function-function-">configure()</a></li>223<li><a href="#app-redirect-name-val-">redirect()</a></li>224<li><a href="#app-error-function-">error()</a></li>225<li><a href="#app-helpers-obj-">helpers()</a></li>226<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>227<li><a href="#app-mounted-fn-">mounted()</a></li>228<li><a href="#app-register-ext-exports-">register()</a></li>229<li><a href="#app-listen-port-host-">listen()</a></li>230</ul></li>231</ul>232 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 233 <p id="tagline">234 High performance, high class web development for235 <a href="http://nodejs.org">Node.js</a>236 </p>237 <ul id="menu">238 <li><a href="index.html">Home</a></li>239 <li><a href="guide.html">Guide</a></li>Added screencasts pageTj Holowaychukbefore adoption4144af3
line 240why, one step back240 <li><a href="screencasts.html">Screencasts</a></li>Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc
line 241why, one step back241 <li><a href="applications.html">Applications</a></li>Regenerated docsTj Holowaychukbefore adoption090debe
lines 242–322why, one step back242 </ul>243<div class='mp'>244<h2 id="Express">Express</h2>245<p class="man-name">246 <code>guide</code>247</p>248<h3 id="Installation">Installation</h3>249250<p>curl:</p>251252<pre><code>$ curl -# http://expressjs.com/install.sh | sh253</code></pre>254255<p>npm:</p>256257<pre><code>$ npm install express258</code></pre>259260<h3 id="Creating-An-Application">Creating An Application</h3>261262<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however263follows the same idiom by providing <em>express.createServer()</em> as shown below. This means264that you can utilize Express server's transparently with other libraries.</p>265266<pre><code>var app = require('express').createServer();267268app.get('/', function(req, res){269 res.send('hello world');270});271272app.listen(3000);273</code></pre>274275<h3 id="Configuration">Configuration</h3>276277<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers278can use the <em>configure()</em> method to setup needs required by the current environment. When279<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment280prior to the environment specific callback.</p>281282<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces283in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.284Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,285otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>286287<pre><code>app.configure(function(){288 app.use(express.methodOverride());289 app.use(express.bodyDecoder());290 app.use(app.router);291 app.use(express.staticProvider(__dirname + '/public'));292});293294app.configure('development', function(){295 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));296});297298app.configure('production', function(){299 app.use(express.errorHandler());300});301</code></pre>302303<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>304305<pre><code>app.configure(function(){306 app.set('views', __dirname + '/views');307 app.set('views');308 // => "... views directory ..."309310 app.enable('some feature');311 // same as app.set('some feature', true);312313 app.disable('some feature');314 // same as app.set('some feature', false);315});316</code></pre>317318<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>319320<pre><code>$ NODE_ENV=production node app.js321</code></pre>322Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 323–324why, one step back323<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>324Regenerated docsTj Holowaychukbefore adoption090debe
lines 325–408why, one step back325<h3 id="Settings">Settings</h3>326327<p>Express supports the following settings out of the box:</p>328329<ul>330<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>331<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>332<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>333<li><em>view engine</em> Default view engine name for views rendered without extensions</li>334<li><em>view options</em> An object specifying global view options</li>335<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>336</ul>337338339<h3 id="Routing">Routing</h3>340341<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.342For example we may want to render a user's account for the path <em>/user/12</em>, this343can be done by defining the route below. The values associated to the named placeholders344are available as <code>req.params</code>.</p>345346<pre><code>app.get('/user/:id', function(req, res){347 res.send('user ' + req.params.id);348});349</code></pre>350351<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example352when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>353354<pre><code>\/user\/([^\/]+)\/?355</code></pre>356357<p>Regular expression literals may also be passed for complex uses. Since capture358groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>.</p>359360<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){361 res.send(req.params);362});363</code></pre>364365<p>Curl requests against the previously defined route:</p>366367<pre><code> $ curl http://dev:3000/user368 [null,null]369 $ curl http://dev:3000/users370 [null,null]371 $ curl http://dev:3000/users/1372 ["1",null]373 $ curl http://dev:3000/users/1..15374 ["1","15"]375</code></pre>376377<p>Below are some route examples, and the associated paths that they378may consume:</p>379380<pre><code> "/user/:id"381 /user/12382383 "/users/:id?"384 /users/5385 /users386387 "/files/*"388 /files/jquery.js389 /files/javascripts/jquery.js390391 "/file/*.*"392 /files/jquery.js393 /files/javascripts/jquery.js394395 "/user/:id/:operation?"396 /user/1397 /user/1/edit398399 "/products.:format"400 /products.json401 /products.xml402403 "/products.:format?"404 /products.json405 /products.xml406 /products407</code></pre>408Rebuilt docsTj Holowaychukbefore adoptiond017c3e
lines 409–422why, one step back409<p>For example we can <strong>POST</strong> some json, and echo the json back using the <em>bodyDecoder</em> middleware which will parse json request bodies (as well as others), and place the result in <em>req.body</em>:</p>410411<pre><code>var express = require('express')412 , app = express.createServer();413414app.use(express.bodyDecoder());415416app.post('/', function(req, res){417 res.send(req.body);418});419420app.listen(3000);421</code></pre>422Regenerated docsTj Holowaychukbefore adoption090debe
lines 423–442why, one step back423<h3 id="Passing-Route-Control">Passing Route Control</h3>424425<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,426the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,427and 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>428429<pre><code>app.get('/users/:id?', function(req, res, next){430 var id = req.params.id;431 if (id) {432 // do something433 } else {434 next();435 }436});437438app.get('/users', function(req, res){439 // do something else440});441</code></pre>442Rebuilt docsTj Holowaychukbefore adoptiond017c3e
lines 443–477why, one step back443<p>Express 1.0 also introduces the <em>all()</em> method, which provides a route callback matching any HTTP method. This is useful in many ways, one example being the loading of resources before executing subsequent routes as shown below:</p>444445<pre><code>var express = require('express')446 , app = express.createServer();447448var users = [{ name: 'tj' }];449450app.all('/user/:id/:op?', function(req, res, next){451 req.user = users[req.params.id];452 if (req.user) {453 next();454 } else {455 next(new Error('cannot find user ' + req.params.id));456 }457});458459app.get('/user/:id', function(req, res){460 res.send('viewing ' + req.user.name);461});462463app.get('/user/:id/edit', function(req, res){464 res.send('editing ' + req.user.name);465});466467app.put('/user/:id', function(req, res){468 res.send('updating ' + req.user.name);469});470471app.get('*', function(req, res){472 res.send('what???', 404);473});474475app.listen(3000); 476</code></pre>477Regenerated docsTj Holowaychukbefore adoption090debe
lines 478–510why, one step back478<h3 id="Middleware">Middleware</h3>479480<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be481passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>482483<pre><code> var express = require('express');484485var app = express.createServer(486 express.logger(),487 express.bodyDecoder()488 );489</code></pre>490491<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>492493<pre><code>app.use(express.logger({ format: ':method :uri' }));494</code></pre>495496<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>497498<pre><code>var connect = require('connect');499app.use(connect.logger());500</code></pre>501502<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>503504<pre><code>app.use(express.logger());505</code></pre>506507<h3 id="Route-Middleware">Route Middleware</h3>508509<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>510Regenerated docsTj Holowaychukbefore adoption0faac20
line 511why, one step back511<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 adoption090debe
line 512why, one step back512Regenerated docsTj Holowaychukbefore adoption0faac20
lines 513–514why, one step back513<pre><code>app.get('/user/:id', function(req, res, next){514 loadUser(req.params.id, function(err, user){Regenerated guideTj Holowaychukbefore adoptionab3337d
lines 515–516why, one step back515 if (err) return next(err);516 res.send('Viewing user ' + user.name);Regenerated docsTj Holowaychukbefore adoption0faac20
lines 517–518why, one step back517 });518});Regenerated docsTj Holowaychukbefore adoption090debe
lines 519–522why, one step back519</code></pre>520521<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>522Regenerated docsTj Holowaychukbefore adoption0faac20
lines 523–532why, one step back523<pre><code>function loadUser(req, res, next) {524 // You would fetch your user from the db525 var user = users[req.params.id];526 if (user) {527 req.user = user;528 next();529 } else {530 next(new Error('Failed to load user ' + req.params.id));531 }532}Regenerated docsTj Holowaychukbefore adoption090debe
line 533why, one step back533Regenerated docsTj Holowaychukbefore adoption0faac20
lines 534–536why, one step back534app.get('/user/:id', loadUser, function(req, res){535 res.send('Viewing user ' + req.user.name);536});Regenerated docsTj Holowaychukbefore adoption090debe
lines 537–540why, one step back537</code></pre>538539<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>540Regenerated docsTj Holowaychukbefore adoption0faac20
lines 541–542why, one step back541<pre><code>function andRestrictToSelf(req, res, next) {542 req.authenticatedUser.id == req.user.idRegenerated guideTj Holowaychukbefore adoptionab3337d
lines 543–544why, one step back543 ? next()544 : next(new Error('Unauthorized'));Regenerated docsTj Holowaychukbefore adoption0faac20
line 545why, one step back545}Regenerated docsTj Holowaychukbefore adoption090debe
line 546why, one step back546Regenerated docsTj Holowaychukbefore adoption0faac20
lines 547–549why, one step back547app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){548 res.send('Editing user ' + req.user.name);549});Regenerated docsTj Holowaychukbefore adoption090debe
lines 550–553why, one step back550</code></pre>551552<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>553Regenerated docsTj Holowaychukbefore adoption0faac20
lines 554–556why, one step back554<pre><code>function andRestrictTo(role) {555 return function(req, res, next) {556 req.authenticatedUser.role == roleRegenerated guideTj Holowaychukbefore adoptionab3337d
lines 557–558why, one step back557 ? next()558 : next(new Error('Unauthorized'));Regenerated docsTj Holowaychukbefore adoption0faac20
lines 559–560why, one step back559 }560}Regenerated docsTj Holowaychukbefore adoption090debe
line 561why, one step back561Regenerated docsTj Holowaychukbefore adoption0faac20
lines 562–564why, one step back562app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){563 res.send('Deleted user ' + req.user.name);564});Regenerated docsTj Holowaychukbefore adoption090debe
lines 565–568why, one step back565</code></pre>566567<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>568Regenerated docsTj Holowaychukbefore adoption0faac20
lines 569–571why, one step back569<pre><code>var a = [middleware1, middleware2]570 , b = [middleware3, middleware4]571 , all = [a, b];Regenerated docsTj Holowaychukbefore adoption090debe
line 572why, one step back572Regenerated docsTj Holowaychukbefore adoption0faac20
lines 573–574why, one step back573app.get('/foo', a, function(){});574app.get('/bar', a, function(){});Regenerated docsTj Holowaychukbefore adoption090debe
line 575why, one step back575Regenerated docsTj Holowaychukbefore adoption0faac20
lines 576–579why, one step back576app.get('/', a, middleware3, middleware4, function(){});577app.get('/', a, b, function(){});578app.get('/', all, function(){});579</code></pre>Regenerated docsTj Holowaychukbefore adoption090debe
lines 580–588why, one step back580581<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>582583<h3 id="HTTP-Methods">HTTP Methods</h3>584585<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>586587<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>588Regenerated guideTj Holowaychukbefore adoptionab3337d
lines 589–593why, one step back589<pre><code> <form method="post" action="/">590 <input type="text" name="user[name]" />591 <input type="text" name="user[email]" />592 <input type="submit" value="Submit" />593 </form>Regenerated docsTj Holowaychukbefore adoption090debe
lines 594–791why, one step back594</code></pre>595596<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>597598<pre><code>app.use(express.bodyDecoder());599</code></pre>600601<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>602603<pre><code>app.post('/', function(req, res){604 console.log(req.body.user);605 res.redirect('back');606});607</code></pre>608609<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>610611<pre><code>app.use(express.bodyDecoder());612app.use(express.methodOverride());613</code></pre>614615<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>616617<pre><code><form method="post" action="/">618 <input type="hidden" name="_method" value="put" />619 <input type="text" name="user[name]" />620 <input type="text" name="user[email]" />621 <input type="submit" value="Submit" /> 622</form>623624app.put('/', function(){625 console.log(req.body.user);626 res.redirect('back');627});628</code></pre>629630<h3 id="Error-Handling">Error Handling</h3>631632<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,633or passed to <em>next(err)</em>. Below is an example which serves different pages based on our634ad-hoc <em>NotFound</em> exception:</p>635636<pre><code>function NotFound(msg){637 this.name = 'NotFound';638 Error.call(this, msg);639 Error.captureStackTrace(this, arguments.callee);640}641642sys.inherits(NotFound, Error);643644app.get('/404', function(req, res){645 throw new NotFound;646});647648app.get('/500', function(req, res){649 throw new Error('keyboard cat!');650});651</code></pre>652653<p>We can call <em>app.error()</em> several times as shown below.654Here we check for an instanceof <em>NotFound</em> and show the655404 page, or we pass on to the next error handler.</p>656657<p>Note that these handlers can be defined anywhere, as they658will be placed below the route handlers on <em>listen()</em>. This659allows for definition within <em>configure()</em> blocks so we can660handle exceptions in different ways based on the environment.</p>661662<pre><code>app.error(function(err, req, res, next){663 if (err instanceof NotFound) {664 res.render('404.jade');665 } else {666 next(err);667 }668});669</code></pre>670671<p>Here we assume all errors as 500 for the simplicity of672this demo, however you can choose whatever you like</p>673674<pre><code>app.error(function(err, req, res){675 res.render('500.jade', {676 locals: {677 error: err678 } 679 });680});681</code></pre>682683<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware684to report on exceptions. For example if we wish to output exceptions685in "development" mode to <em>stderr</em> we can use:</p>686687<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));688</code></pre>689690<p>Also during development we may want fancy html pages to show exceptions691that are passed or thrown, so we can set <em>showStack</em> to true:</p>692693<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));694</code></pre>695696<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>697is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>698699<h3 id="View-Rendering">View Rendering</h3>700701<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name702of the module that will be required. For example the view <em>layout.ejs</em> will703tell 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, however704<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>705706<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,707and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as708the <em>body</em> local variable in <em>layout.haml</em>.</p>709710<pre><code>app.get('/', function(req, res){711 res.render('index.haml', {712 locals: { title: 'My Site' }713 });714});715</code></pre>716717<p>The new <em>view engine</em> setting allows us to specify our default template engine,718so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>719720<pre><code>app.set('view engine', 'jade');721</code></pre>722723<p>Allowing us to render with:</p>724725<pre><code>res.render('index');726</code></pre>727728<p>vs:</p>729730<pre><code>res.render('index.jade');731</code></pre>732733<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still734mix and match template engines:</p>735736<pre><code>res.render('another-page.ejs');737</code></pre>738739<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>740741<pre><code>app.set('view options', {742 layout: false743});744</code></pre>745746<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>747748<pre><code>res.render('myview.ejs', { layout: true });749</code></pre>750751<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>752753<pre><code>res.render('page', { layout: 'mylayout' });754</code></pre>755756<p>Otherwise we must specify the extension:</p>757758<pre><code>res.render('page', { layout: 'mylayout.jade' });759</code></pre>760761<p>These paths may also be absolute:</p>762763<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });764</code></pre>765766<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>767768<pre><code>app.set('view options', {769 open: '{{',770 close: '}}'771});772</code></pre>773774<h3 id="View-Partials">View Partials</h3>775776<p>The Express view system has built-in support for partials and collections, which are777sort of "mini" views representing a document fragment. For example rather than iterating778in a view to display comments, we would use a partial with collection support:</p>779780<pre><code>partial('comment.haml', { collection: comments });781</code></pre>782783<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,784however if we wished we could use an ejs partial, within a haml view for example.</p>785786<pre><code>partial('comment', { collection: comments });787</code></pre>788789<p>And once again even further, when rendering a collection we can simply pass790an array, if no other options are desired:</p>791Regenerated docsTj Holowaychukbefore adoption2a40cec
line 792why, one step back792<pre><code>partial('comment', comments);Regenerated docsTj Holowaychukbefore adoption090debe
lines 793–801why, one step back793</code></pre>794795<p>When using the partial collection support a few "magic" variables are provided796for free:</p>797798<ul>799<li><em>firstInCollection</em> True if this is the first object</li>800<li><em>indexInCollection</em> Index of the object in the collection</li>801<li><em>lastInCollection</em> True if this is the last object</li>Regenerated docsTj Holowaychukbefore adoption2a40cec
line 802why, one step back802<li><em>collectionLength</em> Length of the collection</li>Regenerated docsTj Holowaychukbefore adoption090debe
lines 803–805why, one step back803</ul>804805Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 806–807why, one step back806<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>807Added screencasts pageTj Holowaychukbefore adoption4144af3
lines 808–809why, one step back808<p>NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead. For example do <em>not</em> implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates.</p>809Regenerated docsTj Holowaychukbefore adoption090debe
lines 810–817why, one step back810<h3 id="Template-Engines">Template Engines</h3>811812<p>Below are a few template engines commonly used with Express:</p>813814<ul>815<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>816<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>817<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>Regenerated docsTj Holowaychukbefore adoption2a40cec
line 818why, one step back818<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>Rebuilt docsTj Holowaychukbefore adoptiond017c3e
line 819why, one step back819<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>Regenerated docsTj Holowaychukbefore adoption090debe
lines 820–840why, one step back820</ul>821822823<h3 id="Session-Support">Session Support</h3>824825<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>826827<pre><code>app.use(express.cookieDecoder());828app.use(express.session());829</code></pre>830831<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>832833<pre><code>var RedisStore = require('connect-redis');834app.use(express.cookieDecoder());835app.use(express.session({ store: new RedisStore }));836</code></pre>837838<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>839840<pre><code>var RedisStore = require('connect-redis');Regenerated docsTj Holowaychukbefore adoption1c9831a
line 841why, one step back841app.use(express.bodyDecoder());Regenerated docsTj Holowaychukbefore adoption090debe
lines 842–864why, one step back842app.use(express.cookieDecoder());843app.use(express.session({ store: new RedisStore }));844845app.post('/add-to-cart', function(req, res){846 // Perhaps we posted several items with a form847 // (use the bodyDecoder() middleware for this)848 var items = req.body.items;849 req.session.items = items;850 res.redirect('back');851});852853app.get('/add-to-cart', function(req, res){854 // When redirected back to GET /add-to-cart855 // we could check req.session.items && req.session.items.length856 // to print out a message857 if (req.session.items && req.session.items.length) {858 req.flash('info', 'You have %s items in your cart', req.session.items.length);859 }860 res.render('shopping-cart');861});862</code></pre>863864<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>Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc
lines 865–868why, one step back865866<h3 id="Migration-Guide">Migration Guide</h3>867868<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 docsTj Holowaychukbefore adoption090debe
lines 869–901why, one step back869870<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>871872<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>873874<pre><code>req.header('Host');875req.header('host');876req.header('Accept', '*/*');877</code></pre>878879<h3 id="req-accepts-type-">req.accepts(type)</h3>880881<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>882883<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise884the given <em>type</em> is matched by an exact match, and then subtypes. You885may pass the subtype such as "html" which is then converted internally886to "text/html" using the mime lookup table.</p>887888<pre><code>// Accept: text/html889req.accepts('html');890// => true891892// Accept: text/*; application/json893req.accepts('html');894req.accepts('text/html');895req.accepts('text/plain');896req.accepts('application/json');897// => true898899req.accepts('image/png');900req.accepts('png');901// => falseAdded req.is() docsTj Holowaychukbefore adoption806aefa
lines 902–942why, one step back902</code></pre>903904<h3 id="req-is-type-">req.is(type)</h3>905906<p>Check if the incoming request contains the <em>Content-Type</em>907header field, and it contains the give mime <em>type</em>.</p>908909<pre><code> // With Content-Type: text/html; charset=utf-8910 req.is('html');911 req.is('text/html');912 // => true913914 // When Content-Type is application/json915 req.is('json');916 req.is('application/json');917 // => true918919 req.is('html');920 // => false921</code></pre>922923<p>Ad-hoc callbacks can also be registered with Express, to perform924assertions again the request, for example if we need an expressive925way to check if our incoming request is an image, we can register <em>"an image"</em>926callback:</p>927928<pre><code> app.is('an image', function(req){929 return 0 == req.headers['content-type'].indexOf('image');930 });931</code></pre>932933<p>Now within our route callbacks, we can use to to assert content types934such as <em>"image/jpeg"</em>, <em>"image/png"</em>, etc.</p>935936<pre><code> app.post('/image/upload', function(req, res, next){937 if (req.is('an image')) {938 // do something939 } else {940 next();941 }942 });Regenerated docsTj Holowaychukbefore adoption090debe
lines 943–944why, one step back943</code></pre>944Merge branch 'is'Tj Holowaychukbefore adoption7a71380
lines 945–957why, one step back945<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you946can perform any request assertion you wish.</p>947948<p>Wildcard matches can also be made, simplifying our example above for <em>"an image"</em>, by asserting the <em>subtype</em> only:</p>949950<pre><code>req.is('image/*');951</code></pre>952953<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>954955<pre><code>req.is('*/json');956</code></pre>957Regenerated docsTj Holowaychukbefore adoption090debe
lines 958–1087why, one step back958<h3 id="req-param-name-">req.param(name)</h3>959960<p>Return the value of param <em>name</em> when present.</p>961962<ul>963<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>964<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>965<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>966</ul>967968969<p>To utilize urlencoded request bodies, <em>req.body</em>970should be an object. This can be done by using971the <em>express.bodyDecoder</em> middleware.</p>972973<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>974975<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>976977<pre><code>req.flash('info', 'email sent');978req.flash('error', 'email delivery failed');979req.flash('info', 'email re-sent');980// => 2981982req.flash('info');983// => ['email sent', 'email re-sent']984985req.flash('info');986// => []987988req.flash();989// => { error: ['email delivery failed'], info: [] }990</code></pre>991992<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>993994<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);995</code></pre>996997<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>998999<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1000to see if it was issued by an <em>XMLHttpRequest</em>:</p>10011002<pre><code>req.xhr1003req.isXMLHttpRequest1004</code></pre>10051006<h3 id="res-header-key-val-">res.header(key[, val])</h3>10071008<p>Get or set the response header <em>key</em>.</p>10091010<pre><code>res.header('Content-Length');1011// => undefined10121013res.header('Content-Length', 123);1014// => 12310151016res.header('Content-Length');1017// => 1231018</code></pre>10191020<h3 id="res-contentType-type-">res.contentType(type)</h3>10211022<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>10231024<pre><code> var filename = 'path/to/image.png';1025 res.contentType(filename);1026 // res.headers['Content-Type'] is now "image/png"1027</code></pre>10281029<h3 id="res-attachment-filename-">res.attachment([filename])</h3>10301031<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>10321033<pre><code> res.attachment('path/to/my/image.png');1034</code></pre>10351036<h3 id="res-sendfile-path-">res.sendfile(path)</h3>10371038<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>10391040<pre><code>res.sendfile('path/to/my.file');1041</code></pre>10421043<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>10441045<pre><code>res.sendfile(path, function(err, path){1046 if (err) {1047 // handle the error1048 } else {1049 console.log('transferred %s', path);1050 }1051});1052</code></pre>10531054<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>10551056<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>10571058<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>10591060<pre><code>res.download('path/to/image.png');1061res.download('path/to/image.png', 'foo.png');1062</code></pre>10631064<p>This is equivalent to:</p>10651066<pre><code>res.attachment(file);1067res.sendfile(file);1068</code></pre>10691070<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>10711072<p>The <code>res.send()</code> method is a high level response utility allowing you to pass1073objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status1074code based responses. The following are all valid uses:</p>10751076<pre><code> res.send(); // 2041077 res.send(new Buffer('wahoo'));1078 res.send({ some: 'json' });1079 res.send('<p>some html</p>');1080 res.send('Sorry, cant find that', 404);1081 res.send('text', { 'Content-Type': 'text/plain' }, 201);1082 res.send(404);1083</code></pre>10841085<p>By default the <em>Content-Type</em> response header is set, however if explicitly1086assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1087it will not be set again.</p>Added screencasts pageTj Holowaychukbefore adoption4144af3
lines 1088–1089why, one step back10881089<p>Note that this method <em>end()</em> the response, so you will want to use node's <em>res.writeHead()</em> / <em>res.write()</em> for multiple writes or streaming.</p>Regenerated docsTj Holowaychukbefore adoption090debe
lines 1090–1153why, one step back10901091<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>10921093<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>10941095<pre><code>res.redirect('/', 301);1096res.redirect('/account');1097res.redirect('http://google.com');1098res.redirect('home');1099res.redirect('back');1100</code></pre>11011102<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1103The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1104the "home" setting and defaults to "/".</p>11051106<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>11071108<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>11091110<pre><code>// "Remember me" for 15 minutes 1111res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1112</code></pre>11131114<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>11151116<pre><code>app.use(express.cookieDecoder());11171118app.get('/', function(req, res){1119 // use req.cookies.rememberme1120});1121</code></pre>11221123<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>11241125<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>11261127<pre><code>res.clearCookie('rememberme');1128</code></pre>11291130<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>11311132<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1133When a callback function is given a response will <em>not</em> be made1134automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>11351136<p> Most engines accept one or more of the following options,1137 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>11381139<ul>1140<li><em>scope</em> Template evaluation context (value of <em>this</em>)</li>1141<li><em>locals</em> Object containing local variables</li>1142<li><em>debug</em> Output debugging information</li>1143<li><em>status</em> Response status code, defaults to 200</li>1144<li><em>headers</em> Response headers object</li>1145</ul>114611471148<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>11491150<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1151to the view as a local variable.</p>11521153<ul>Rebuilt docsTj Holowaychukbefore adoptiond017c3e
lines 1154–1155why, one step back1154<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1155<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>Regenerated docsTj Holowaychukbefore adoption090debe
lines 1156–1170why, one step back11561157<ul>1158<li>as: 'something' will add the <em>something</em> local variable</li>1159<li>as: this will use the collection value as the template context</li>1160<li>as: global will merge the collection value's properties with <em>locals</em></li>1161</ul>1162</li>1163<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1164For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1165</ul>116611671168<p>The following are equivalent, and the name of collection value when passed1169to the partial will be <em>movie</em> as derived from the name.</p>1170Regenerated docsTj Holowaychukbefore adoption2a40cec
lines 1171–1173why, one step back1171<pre><code>partial('theatre/movie.jade', { collection: movies });1172partial('theatre/movie.jade', movies);1173partial('movie.jade', { collection: movies });Regenerated docsTj Holowaychukbefore adoption090debe
lines 1174–1194why, one step back1174partial('movie.jade', movies);1175partial('movie', movies);1176// In view: movie.director1177</code></pre>11781179<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>11801181<pre><code>partial('movie', { collection: movies, as: 'video' });1182// In view: video.director1183</code></pre>11841185<p>Also we can make our movie the value of <em>this</em> within our view so that instead1186of <em>movie.director</em> we could use <em>this.director</em>.</p>11871188<pre><code>partial('movie', { collection: movies, as: this });1189// In view: this.director1190</code></pre>11911192<p>Another alternative is to "explode" the properties of the collection item into1193pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>1194Rebuilt docsTj Holowaychukbefore adoptiond017c3e
line 1195why, one step back1195<pre><code>partial('movie', { collection: movies, as: global });Regenerated docsTj Holowaychukbefore adoption090debe
lines 1196–1198why, one step back1196// In view: director1197</code></pre>1198Rebuilt docsTj Holowaychukbefore adoptiond017c3e
lines 1199–1219why, one step back1199<p>This same logic applies to a single partial object usage:</p>12001201<pre><code>partial('movie', { object: movie, as: this });1202// In view: this.director12031204partial('movie', { object: movie, as: global });1205// In view: director12061207partial('movie', { object: movie, as: 'video' });1208// In view: video.director12091210partial('movie', { object: movie });1211// In view: movie.director1212</code></pre>12131214<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>12151216<pre><code>partial('movie', movie);1217// => In view: movie.director1218</code></pre>1219Regenerated docsTj Holowaychukbefore adoption090debe
lines 1220–1226why, one step back1220<h3 id="app-set-name-val-">app.set(name[, val])</h3>12211222<p>Apply an application level setting <em>name</em> to <em>val</em>, or1223get the value of <em>name</em> when <em>val</em> is not present:</p>12241225<pre><code>app.set('views', __dirname + '/views');1226app.set('views');Rebuilt docsTj Holowaychukbefore adoptiond017c3e
lines 1227–1232why, one step back1227// => ...path...1228</code></pre>12291230<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>12311232<pre><code>app.settings.viewsRegenerated docsTj Holowaychukbefore adoption090debe
lines 1233–1378why, one step back1233// => ...path...1234</code></pre>12351236<h3 id="app-enable-name-">app.enable(name)</h3>12371238<p>Enable the given setting <em>name</em>:</p>12391240<pre><code>app.enable('some arbitrary setting');1241app.set('some arbitrary setting');1242// => true1243</code></pre>12441245<h3 id="app-disable-name-">app.disable(name)</h3>12461247<p>Disable the given setting <em>name</em>:</p>12481249<pre><code>app.disable('some setting');1250app.set('some setting');1251// => false1252</code></pre>12531254<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>12551256<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>12571258<pre><code>app.configure(function(){1259 // executed for each env1260});12611262app.configure('development', function(){1263 // executed for 'development' only1264});1265</code></pre>12661267<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>12681269<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>12701271<pre><code>app.redirect('google', 'http://google.com');1272</code></pre>12731274<p>Now in a route we may call:</p>12751276<p> res.redirect('google');</p>12771278<p>We may also map dynamic redirects:</p>12791280<pre><code>app.redirect('comments', function(req, res){1281 return '/post/' + req.params.id + '/comments';1282});1283</code></pre>12841285<p>So now we may do the following, and the redirect will dynamically adjust to1286the context of the request. If we called this route with <em>GET /post/12</em> our1287redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>12881289<pre><code>app.get('/post/:id', function(req, res){1290 res.redirect('comments');1291});1292</code></pre>12931294<h3 id="app-error-function-">app.error(function)</h3>12951296<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1297Note that we may set several error handlers by making several calls to this method, however the handler1298should call <em>next(err)</em> if it does not wish to deal with the exception:</p>12991300<pre><code>app.error(function(err, req, res, next){1301 res.send(err.message, 500);1302});1303</code></pre>13041305<h3 id="app-helpers-obj-">app.helpers(obj)</h3>13061307<p>Registers static view helpers.</p>13081309<pre><code>app.helpers({1310 name: function(first, last){ return first + ', ' + last },1311 firstName: 'tj',1312 lastName: 'holowaychuk'1313});1314</code></pre>13151316<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1317as well as the <em>name()</em> function exposed.</p>13181319<pre><code><%= name(firstName, lastName) %>1320</code></pre>13211322<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>13231324<p>Registers dynamic view helpers. Dynamic view helpers1325are simply functions which accept <em>req</em>, <em>res</em>, and are1326evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1327becomes the local variable it is associated with.</p>13281329<pre><code>app.dynamicHelpers({1330 session: function(req, res){1331 return req.session;1332 }1333});1334</code></pre>13351336<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>13371338<pre><code><%= session.name %>1339</code></pre>13401341<h3 id="app-mounted-fn-">app.mounted(fn)</h3>13421343<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>13441345<pre><code>var app = express.createServer(),1346 blog = express.createServer();13471348blog.mounted(function(parent){1349 // parent is app1350 // "this" is blog1351});13521353app.use(blog);1354</code></pre>13551356<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>13571358<p>Register the given template engine <em>exports</em>1359as <em>ext</em>. For example we may wish to map ".html"1360files to jade:</p>13611362<pre><code> app.register('.html', require('jade'));1363</code></pre>13641365<p>This is also useful for libraries that may not1366match extensions correctly. For example my haml.js1367library is installed from npm as "hamljs" so instead1368of layout.hamljs, we can register the engine as ".haml":</p>13691370<pre><code> app.register('.haml', require('haml-js'));1371</code></pre>13721373<p>For engines that do not comply with the Express1374specification, we can also wrap their api this way.</p>13751376<pre><code> app.register('.foo', {1377 render: function(str, options) {1378 // perhaps their api isRegenerated docsTj Holowaychukbefore adoption5152823
line 1379why, one step back1379 // return foo.toHTML(str, options);Regenerated docsTj Holowaychukbefore adoption090debe
lines 1380–1415why, one step back1380 }1381 });1382</code></pre>13831384<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>13851386<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1387connections will be accepted via <em>INADDR_ANY</em>.</p>13881389<pre><code>app.listen();1390app.listen(3000);1391app.listen(3000, 'n.n.n.n');1392</code></pre>13931394<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>13951396<pre><code>app.listen('/tmp/express.sock');1397</code></pre>13981399<p>Then try it out:</p>14001401<pre><code>$ telnet /tmp/express.sock1402GET / HTTP/1.114031404HTTP/1.1 200 OK1405Content-Type: text/plain1406Content-Length: 1114071408Hello World1409</code></pre>14101411</div>1412 </div>1413 </div>1414 </body>1415</html>