guide.html
This file
Path
docs/guide.html
1,488 lines · 50.8 KiB · HTML
Last changed by
Re-built docsTj Holowaychukbefore adoption8e63d04
History of this fileTake it
The walk stopped after 200 commits: lines older than c4ba1b0 point at it.
Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 1–135why, one step back1<html>2 <head>3 <title>Express - node web framework</title>4 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>5 <style>6 #tagline {7 margin-left: 75px;8 margin-bottom: 30px;9 color: rgba(255,255,255,0.7); }10 html {11 background: #1c1c1c url(images/bg.tile.jpg); }1213 body {14 margin: 0;15 padding-bottom: 30px;16 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";17 font-size: 14px;18 line-height: 1.5;19 -webkit-font-smoothing: antialiased;20 background: url(images/bg.jpg) 50% 0 no-repeat;21 color: #8b8b8b; }2223 * {24 outline: none; }2526 em {27 color: white; }2829 a img {30 border: none !important; }3132 a {33 font-weight: bold;34 text-decoration: none;35 color: white;36 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;37 -webkit-transition-duration: 0.15s;38 -webkit-transition-timing-function: ease-out; }39 a:hover {40 opacity: 0.8; }4142 h1, h2, h3, h4 {43 margin: 45px 0 0 0;44 color: white;45 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4647 h3 {48 font-size: 18px; }49 h4 {50 margin-left: 10px;51 font-size: 14px;52 }5354 pre {55 margin: 20px 10px;56 padding: 25px 20px;57 background: rgba(0,0,0,0.5);58 border: 1px solid #323232;59 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);60 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -webkit-border-radius: 5px;62 -moz-border-radius: 5px; }6364 code {65 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6667 ul {68 margin: 15px 0;69 padding: 0 0 0 35px; }70 ul li {71 margin: 0;72 padding: 2px 0;73 list-style: square; }74 ul li ul {75 margin: 0;76 padding-left: 12px;77 }7879 .man-name, #Express { display:none; }8081 .sect {82 margin-left: 40px; }83 img {84 margin-left: 20px;85 margin-bottom: 15px;86 }8788 #logo {89 display: block;90 margin-left: 30%;91 margin-bottom: 30px;92 width: 194px;93 height: 51px;94 background: url(images/logo.png) 0 0 no-repeat;95 text-indent: -99999px; }96 #logo:hover {97 opacity: 0.7; }98 #logo:active {99 opacity: 0.3; }100101 #ribbon {102 position: fixed;103 top: 0;104 right: 0;105 z-index: 2; }106107 #wrapper {108 width: 100%;109 min-height: 800px;110 background: url(images/top.png) 0 0 repeat-x; }111112 #container {113 margin: 0 auto;114 padding-top: 80px;115 width: 550px; }116117 #toc {118 position: fixed;119 top: 0;120 left: 0;121 margin: 0 0 0 15px;122 padding: 15px;123 height: 100%;124 background: rgba(0,0,0,0.2);125 overflow: auto;126 border-right: 1px solid rgba(255,255,255,0.05);127 }128 #toc li {129 padding: 0;130 list-style: none;131 }132 #toc li a {133 font-size: 11px;134 }135 #menu {Regenerated docsTj Holowaychukbefore adoptiond3abcaf
line 136why, one step back136 margin-left: 75px;Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 137–191why, 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>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
line 192why, one step back192<li><a href="#Route-Preconditions">Route Preconditions</a></li>Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 193–217why, one step back193<li><a href="#View-Rendering">View Rendering</a></li>194<li><a href="#View-Partials">View Partials</a></li>195<li><a href="#Template-Engines">Template Engines</a></li>196<li><a href="#Session-Support">Session Support</a></li>197<li><a href="#Migration-Guide">Migration Guide</a></li>198<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">199<li><a href="#req-header-key-defaultValue-">header()</a></li>200<li><a href="#req-accepts-type-">accepts()</a></li>201<li><a href="#req-is-type-">is()</a></li>202<li><a href="#req-param-name-">param()</a></li>203<li><a href="#req-flash-type-msg-">flash()</a></li>204<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>205</ul></li>206<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">207<li><a href="#res-header-key-val-">header()</a></li>208<li><a href="#res-contentType-type-">contentType()</a></li>209<li><a href="#res-attachment-filename-">attachment()</a></li>210<li><a href="#res-sendfile-path-">sendfile()</a></li>211<li><a href="#res-download-file-filename-">download()</a></li>212<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>213<li><a href="#res-redirect-url-status-">redirect()</a></li>214<li><a href="#res-cookie-name-val-options-">cookie()</a></li>215<li><a href="#res-clearCookie-name-">clearCookie()</a></li>216<li><a href="#res-render-view-options-fn-">render()</a></li>217<li><a href="#res-partial-view-options-">partial()</a></li>Re-built docsTj Holowaychukbefore adoption8e63d04
line 218why, one step back218<li><a href="#res-local-name-val-">local()</a></li>Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 219–241why, one step back219</ul></li>220<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">221<li><a href="#app-set-name-val-">set()</a></li>222<li><a href="#app-enable-name-">enable()</a></li>223<li><a href="#app-disable-name-">disable()</a></li>224<li><a href="#app-configure-env-function-function-">configure()</a></li>225<li><a href="#app-redirect-name-val-">redirect()</a></li>226<li><a href="#app-error-function-">error()</a></li>227<li><a href="#app-helpers-obj-">helpers()</a></li>228<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>229<li><a href="#app-mounted-fn-">mounted()</a></li>230<li><a href="#app-register-ext-exports-">register()</a></li>231<li><a href="#app-listen-port-host-">listen()</a></li>232</ul></li>233</ul>234 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 235 <p id="tagline">236 High performance, high class web development for237 <a href="http://nodejs.org">Node.js</a>238 </p>239 <ul id="menu">240 <li><a href="index.html">Home</a></li>241 <li><a href="guide.html">Guide</a></li>Added screencasts pageTj Holowaychukbefore adoption4144af3
line 242why, one step back242 <li><a href="screencasts.html">Screencasts</a></li>Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 243–359why, one step back243 <li><a href="applications.html">Applications</a></li>244 </ul>245<div class='mp'>246<h2 id="Express">Express</h2>247<p class="man-name">248 <code>guide</code>249</p>250<h3 id="Installation">Installation</h3>251252<p>curl:</p>253254<pre><code>$ curl -# http://expressjs.com/install.sh | sh255</code></pre>256257<p>npm:</p>258259<pre><code>$ npm install express260</code></pre>261262<h3 id="Creating-An-Application">Creating An Application</h3>263264<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however265follows the same idiom by providing <em>express.createServer()</em> as shown below. This means266that you can utilize Express server's transparently with other libraries.</p>267268<pre><code>var app = require('express').createServer();269270app.get('/', function(req, res){271 res.send('hello world');272});273274app.listen(3000);275</code></pre>276277<h3 id="Configuration">Configuration</h3>278279<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers280can use the <em>configure()</em> method to setup needs required by the current environment. When281<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment282prior to the environment specific callback.</p>283284<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces285in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.286Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,287otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>288289<pre><code>app.configure(function(){290 app.use(express.methodOverride());291 app.use(express.bodyDecoder());292 app.use(app.router);293 app.use(express.staticProvider(__dirname + '/public'));294});295296app.configure('development', function(){297 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));298});299300app.configure('production', function(){301 app.use(express.errorHandler());302});303</code></pre>304305<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>306307<pre><code>app.configure(function(){308 app.set('views', __dirname + '/views');309 app.set('views');310 // => "... views directory ..."311312 app.enable('some feature');313 // same as app.set('some feature', true);314315 app.disable('some feature');316 // same as app.set('some feature', false);317});318</code></pre>319320<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>321322<pre><code>$ NODE_ENV=production node app.js323</code></pre>324325<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>326327<h3 id="Settings">Settings</h3>328329<p>Express supports the following settings out of the box:</p>330331<ul>332<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>333<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>334<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>335<li><em>view engine</em> Default view engine name for views rendered without extensions</li>336<li><em>view options</em> An object specifying global view options</li>337<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>338</ul>339340341<h3 id="Routing">Routing</h3>342343<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.344For example we may want to render a user's account for the path <em>/user/12</em>, this345can be done by defining the route below. The values associated to the named placeholders346are available as <code>req.params</code>.</p>347348<pre><code>app.get('/user/:id', function(req, res){349 res.send('user ' + req.params.id);350});351</code></pre>352353<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example354when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>355356<pre><code>\/user\/([^\/]+)\/?357</code></pre>358359<p>Regular expression literals may also be passed for complex uses. Since captureRegenerated docsTj Holowaychukbefore adoptiond3abcaf
line 360why, one step back360groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>. So our first capture group would be <em>req.params[0]</em> and the second would follow as <em>req.params[1]</em>.</p>Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 361–408why, one step back361362<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){363 res.send(req.params);364});365</code></pre>366367<p>Curl requests against the previously defined route:</p>368369<pre><code> $ curl http://dev:3000/user370 [null,null]371 $ curl http://dev:3000/users372 [null,null]373 $ curl http://dev:3000/users/1374 ["1",null]375 $ curl http://dev:3000/users/1..15376 ["1","15"]377</code></pre>378379<p>Below are some route examples, and the associated paths that they380may consume:</p>381382<pre><code> "/user/:id"383 /user/12384385 "/users/:id?"386 /users/5387 /users388389 "/files/*"390 /files/jquery.js391 /files/javascripts/jquery.js392393 "/file/*.*"394 /files/jquery.js395 /files/javascripts/jquery.js396397 "/user/:id/:operation?"398 /user/1399 /user/1/edit400401 "/products.:format"402 /products.json403 /products.xml404405 "/products.:format?"406 /products.json407 /products.xml408 /productsRegenerated docsTj Holowaychukbefore adoptiond3abcaf
lines 409–412why, one step back409410 "/user/:id.:format?"411 /user/12412 /user/12.jsonUpdated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 413–414why, one step back413</code></pre>414Rebuilt docsTj Holowaychukbefore adoptiond017c3e
lines 415–427why, one step back415<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>416417<pre><code>var express = require('express')418 , app = express.createServer();419420app.use(express.bodyDecoder());421422app.post('/', function(req, res){423 res.send(req.body);424});425426app.listen(3000);427</code></pre>Regenerated docsTj Holowaychukbefore adoptiond3abcaf
lines 428–429why, one step back428429<p>Express 2.0.0-pre also supports named capture groups. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, however say for example we are limiting a user id to digits, we may use <em>'/user/:id(\d+)'</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>Rebuilt docsTj Holowaychukbefore adoptiond017c3e
line 430why, one step back430Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 431–450why, one step back431<h3 id="Passing-Route-Control">Passing Route Control</h3>432433<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,434the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,435and 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>436437<pre><code>app.get('/users/:id?', function(req, res, next){438 var id = req.params.id;439 if (id) {440 // do something441 } else {442 next();443 }444});445446app.get('/users', function(req, res){447 // do something else448});449</code></pre>450Rebuilt docsTj Holowaychukbefore adoptiond017c3e
lines 451–485why, one step back451<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>452453<pre><code>var express = require('express')454 , app = express.createServer();455456var users = [{ name: 'tj' }];457458app.all('/user/:id/:op?', function(req, res, next){459 req.user = users[req.params.id];460 if (req.user) {461 next();462 } else {463 next(new Error('cannot find user ' + req.params.id));464 }465});466467app.get('/user/:id', function(req, res){468 res.send('viewing ' + req.user.name);469});470471app.get('/user/:id/edit', function(req, res){472 res.send('editing ' + req.user.name);473});474475app.put('/user/:id', function(req, res){476 res.send('updating ' + req.user.name);477});478479app.get('*', function(req, res){480 res.send('what???', 404);481});482483app.listen(3000); 484</code></pre>485Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 486–705why, one step back486<h3 id="Middleware">Middleware</h3>487488<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be489passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>490491<pre><code> var express = require('express');492493var app = express.createServer(494 express.logger(),495 express.bodyDecoder()496 );497</code></pre>498499<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>500501<pre><code>app.use(express.logger({ format: ':method :uri' }));502</code></pre>503504<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>505506<pre><code>var connect = require('connect');507app.use(connect.logger());508</code></pre>509510<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>511512<pre><code>app.use(express.logger());513</code></pre>514515<h3 id="Route-Middleware">Route Middleware</h3>516517<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>518519<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>520521<pre><code>app.get('/user/:id', function(req, res, next){522 loadUser(req.params.id, function(err, user){523 if (err) return next(err);524 res.send('Viewing user ' + user.name);525 });526});527</code></pre>528529<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>530531<pre><code>function loadUser(req, res, next) {532 // You would fetch your user from the db533 var user = users[req.params.id];534 if (user) {535 req.user = user;536 next();537 } else {538 next(new Error('Failed to load user ' + req.params.id));539 }540}541542app.get('/user/:id', loadUser, function(req, res){543 res.send('Viewing user ' + req.user.name);544});545</code></pre>546547<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>548549<pre><code>function andRestrictToSelf(req, res, next) {550 req.authenticatedUser.id == req.user.id551 ? next()552 : next(new Error('Unauthorized'));553}554555app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){556 res.send('Editing user ' + req.user.name);557});558</code></pre>559560<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>561562<pre><code>function andRestrictTo(role) {563 return function(req, res, next) {564 req.authenticatedUser.role == role565 ? next()566 : next(new Error('Unauthorized'));567 }568}569570app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){571 res.send('Deleted user ' + req.user.name);572});573</code></pre>574575<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>576577<pre><code>var a = [middleware1, middleware2]578 , b = [middleware3, middleware4]579 , all = [a, b];580581app.get('/foo', a, function(){});582app.get('/bar', a, function(){});583584app.get('/', a, middleware3, middleware4, function(){});585app.get('/', a, b, function(){});586app.get('/', all, function(){});587</code></pre>588589<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>590591<h3 id="HTTP-Methods">HTTP Methods</h3>592593<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>594595<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>596597<pre><code> <form method="post" action="/">598 <input type="text" name="user[name]" />599 <input type="text" name="user[email]" />600 <input type="submit" value="Submit" />601 </form>602</code></pre>603604<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>605606<pre><code>app.use(express.bodyDecoder());607</code></pre>608609<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>610611<pre><code>app.post('/', function(req, res){612 console.log(req.body.user);613 res.redirect('back');614});615</code></pre>616617<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>618619<pre><code>app.use(express.bodyDecoder());620app.use(express.methodOverride());621</code></pre>622623<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>624625<pre><code><form method="post" action="/">626 <input type="hidden" name="_method" value="put" />627 <input type="text" name="user[name]" />628 <input type="text" name="user[email]" />629 <input type="submit" value="Submit" /> 630</form>631632app.put('/', function(){633 console.log(req.body.user);634 res.redirect('back');635});636</code></pre>637638<h3 id="Error-Handling">Error Handling</h3>639640<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,641or passed to <em>next(err)</em>. Below is an example which serves different pages based on our642ad-hoc <em>NotFound</em> exception:</p>643644<pre><code>function NotFound(msg){645 this.name = 'NotFound';646 Error.call(this, msg);647 Error.captureStackTrace(this, arguments.callee);648}649650sys.inherits(NotFound, Error);651652app.get('/404', function(req, res){653 throw new NotFound;654});655656app.get('/500', function(req, res){657 throw new Error('keyboard cat!');658});659</code></pre>660661<p>We can call <em>app.error()</em> several times as shown below.662Here we check for an instanceof <em>NotFound</em> and show the663404 page, or we pass on to the next error handler.</p>664665<p>Note that these handlers can be defined anywhere, as they666will be placed below the route handlers on <em>listen()</em>. This667allows for definition within <em>configure()</em> blocks so we can668handle exceptions in different ways based on the environment.</p>669670<pre><code>app.error(function(err, req, res, next){671 if (err instanceof NotFound) {672 res.render('404.jade');673 } else {674 next(err);675 }676});677</code></pre>678679<p>Here we assume all errors as 500 for the simplicity of680this demo, however you can choose whatever you like</p>681682<pre><code>app.error(function(err, req, res){683 res.render('500.jade', {684 locals: {685 error: err686 } 687 });688});689</code></pre>690691<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware692to report on exceptions. For example if we wish to output exceptions693in "development" mode to <em>stderr</em> we can use:</p>694695<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));696</code></pre>697698<p>Also during development we may want fancy html pages to show exceptions699that are passed or thrown, so we can set <em>showStack</em> to true:</p>700701<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));702</code></pre>703704<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>705is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
lines 706–746why, one step back706707<h3 id="Route-Preconditions">Route Preconditions</h3>708709<p>Route placeholder pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for <em>/user/:id</em>,we might typically do something like below:</p>710711<pre><code>app.get('/user/:userId', function(req, res, next){712 User.get(req.params.userId, function(err, user){713 if (err) return next(err);714 res.send('user ' + user.name);715 });716}); 717</code></pre>718719<p>With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>720721<pre><code>app.param('userId', function(req, res, next, id){722 User.get(id, function(err, user){723 if (err) return next(err);724 if (!user) return next(new Error('failed to find user'));725 req.user = user;726 next();727 });728});729</code></pre>730731<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>732733<pre><code>app.get('/user/:userId', function(req, res){734 res.send('user ' + req.user.name);735});736</code></pre>737738<p>For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to <em>next(err)</em>.</p>739740<pre><code>app.param('number', function(n){ return parseInt(n, 10); });741</code></pre>742743<p>We may also apply the same callback to several placeholders, for example a route GET <em>/commits/:from-:to</em> are both numbers, so we may define them as an array:</p>744745<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });746</code></pre>Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 747–856why, one step back747748<h3 id="View-Rendering">View Rendering</h3>749750<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name751of the module that will be required. For example the view <em>layout.ejs</em> will752tell 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, however753<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>754755<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,756and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as757the <em>body</em> local variable in <em>layout.haml</em>.</p>758759<pre><code>app.get('/', function(req, res){760 res.render('index.haml', {761 locals: { title: 'My Site' }762 });763});764</code></pre>765766<p>The new <em>view engine</em> setting allows us to specify our default template engine,767so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>768769<pre><code>app.set('view engine', 'jade');770</code></pre>771772<p>Allowing us to render with:</p>773774<pre><code>res.render('index');775</code></pre>776777<p>vs:</p>778779<pre><code>res.render('index.jade');780</code></pre>781782<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still783mix and match template engines:</p>784785<pre><code>res.render('another-page.ejs');786</code></pre>787788<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>789790<pre><code>app.set('view options', {791 layout: false792});793</code></pre>794795<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>796797<pre><code>res.render('myview.ejs', { layout: true });798</code></pre>799800<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>801802<pre><code>res.render('page', { layout: 'mylayout' });803</code></pre>804805<p>Otherwise we must specify the extension:</p>806807<pre><code>res.render('page', { layout: 'mylayout.jade' });808</code></pre>809810<p>These paths may also be absolute:</p>811812<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });813</code></pre>814815<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>816817<pre><code>app.set('view options', {818 open: '{{',819 close: '}}'820});821</code></pre>822823<h3 id="View-Partials">View Partials</h3>824825<p>The Express view system has built-in support for partials and collections, which are826sort of "mini" views representing a document fragment. For example rather than iterating827in a view to display comments, we would use a partial with collection support:</p>828829<pre><code>partial('comment.haml', { collection: comments });830</code></pre>831832<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,833however if we wished we could use an ejs partial, within a haml view for example.</p>834835<pre><code>partial('comment', { collection: comments });836</code></pre>837838<p>And once again even further, when rendering a collection we can simply pass839an array, if no other options are desired:</p>840841<pre><code>partial('comment', comments);842</code></pre>843844<p>When using the partial collection support a few "magic" variables are provided845for free:</p>846847<ul>848<li><em>firstInCollection</em> True if this is the first object</li>849<li><em>indexInCollection</em> Index of the object in the collection</li>850<li><em>lastInCollection</em> True if this is the last object</li>851<li><em>collectionLength</em> Length of the collection</li>852</ul>853854855<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>856Added screencasts pageTj Holowaychukbefore adoption4144af3
lines 857–858why, one step back857<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>858Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 859–867why, one step back859<h3 id="Template-Engines">Template Engines</h3>860861<p>Below are a few template engines commonly used with Express:</p>862863<ul>864<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>865<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>866<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>867<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>Rebuilt docsTj Holowaychukbefore adoptiond017c3e
line 868why, one step back868<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 869–1136why, one step back869</ul>870871872<h3 id="Session-Support">Session Support</h3>873874<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>875876<pre><code>app.use(express.cookieDecoder());877app.use(express.session());878</code></pre>879880<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>881882<pre><code>var RedisStore = require('connect-redis');883app.use(express.cookieDecoder());884app.use(express.session({ store: new RedisStore }));885</code></pre>886887<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>888889<pre><code>var RedisStore = require('connect-redis');890app.use(express.bodyDecoder());891app.use(express.cookieDecoder());892app.use(express.session({ store: new RedisStore }));893894app.post('/add-to-cart', function(req, res){895 // Perhaps we posted several items with a form896 // (use the bodyDecoder() middleware for this)897 var items = req.body.items;898 req.session.items = items;899 res.redirect('back');900});901902app.get('/add-to-cart', function(req, res){903 // When redirected back to GET /add-to-cart904 // we could check req.session.items && req.session.items.length905 // to print out a message906 if (req.session.items && req.session.items.length) {907 req.flash('info', 'You have %s items in your cart', req.session.items.length);908 }909 res.render('shopping-cart');910});911</code></pre>912913<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>914915<h3 id="Migration-Guide">Migration Guide</h3>916917<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>918919<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>920921<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>922923<pre><code>req.header('Host');924req.header('host');925req.header('Accept', '*/*');926</code></pre>927928<h3 id="req-accepts-type-">req.accepts(type)</h3>929930<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>931932<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise933the given <em>type</em> is matched by an exact match, and then subtypes. You934may pass the subtype such as "html" which is then converted internally935to "text/html" using the mime lookup table.</p>936937<pre><code>// Accept: text/html938req.accepts('html');939// => true940941// Accept: text/*; application/json942req.accepts('html');943req.accepts('text/html');944req.accepts('text/plain');945req.accepts('application/json');946// => true947948req.accepts('image/png');949req.accepts('png');950// => false951</code></pre>952953<h3 id="req-is-type-">req.is(type)</h3>954955<p>Check if the incoming request contains the <em>Content-Type</em>956header field, and it contains the give mime <em>type</em>.</p>957958<pre><code> // With Content-Type: text/html; charset=utf-8959 req.is('html');960 req.is('text/html');961 // => true962963 // When Content-Type is application/json964 req.is('json');965 req.is('application/json');966 // => true967968 req.is('html');969 // => false970</code></pre>971972<p>Ad-hoc callbacks can also be registered with Express, to perform973assertions again the request, for example if we need an expressive974way to check if our incoming request is an image, we can register <em>"an image"</em>975callback:</p>976977<pre><code> app.is('an image', function(req){978 return 0 == req.headers['content-type'].indexOf('image');979 });980</code></pre>981982<p>Now within our route callbacks, we can use to to assert content types983such as <em>"image/jpeg"</em>, <em>"image/png"</em>, etc.</p>984985<pre><code> app.post('/image/upload', function(req, res, next){986 if (req.is('an image')) {987 // do something988 } else {989 next();990 }991 });992</code></pre>993994<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you995can perform any request assertion you wish.</p>996997<p>Wildcard matches can also be made, simplifying our example above for <em>"an image"</em>, by asserting the <em>subtype</em> only:</p>998999<pre><code>req.is('image/*');1000</code></pre>10011002<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>10031004<pre><code>req.is('*/json');1005</code></pre>10061007<h3 id="req-param-name-">req.param(name)</h3>10081009<p>Return the value of param <em>name</em> when present.</p>10101011<ul>1012<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>1013<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1014<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1015</ul>101610171018<p>To utilize urlencoded request bodies, <em>req.body</em>1019should be an object. This can be done by using1020the <em>express.bodyDecoder</em> middleware.</p>10211022<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>10231024<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>10251026<pre><code>req.flash('info', 'email sent');1027req.flash('error', 'email delivery failed');1028req.flash('info', 'email re-sent');1029// => 210301031req.flash('info');1032// => ['email sent', 'email re-sent']10331034req.flash('info');1035// => []10361037req.flash();1038// => { error: ['email delivery failed'], info: [] }1039</code></pre>10401041<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>10421043<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1044</code></pre>10451046<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>10471048<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1049to see if it was issued by an <em>XMLHttpRequest</em>:</p>10501051<pre><code>req.xhr1052req.isXMLHttpRequest1053</code></pre>10541055<h3 id="res-header-key-val-">res.header(key[, val])</h3>10561057<p>Get or set the response header <em>key</em>.</p>10581059<pre><code>res.header('Content-Length');1060// => undefined10611062res.header('Content-Length', 123);1063// => 12310641065res.header('Content-Length');1066// => 1231067</code></pre>10681069<h3 id="res-contentType-type-">res.contentType(type)</h3>10701071<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>10721073<pre><code> var filename = 'path/to/image.png';1074 res.contentType(filename);1075 // res.headers['Content-Type'] is now "image/png"1076</code></pre>10771078<h3 id="res-attachment-filename-">res.attachment([filename])</h3>10791080<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>10811082<pre><code> res.attachment('path/to/my/image.png');1083</code></pre>10841085<h3 id="res-sendfile-path-">res.sendfile(path)</h3>10861087<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>10881089<pre><code>res.sendfile('path/to/my.file');1090</code></pre>10911092<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>10931094<pre><code>res.sendfile(path, function(err, path){1095 if (err) {1096 // handle the error1097 } else {1098 console.log('transferred %s', path);1099 }1100});1101</code></pre>11021103<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>11041105<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>11061107<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>11081109<pre><code>res.download('path/to/image.png');1110res.download('path/to/image.png', 'foo.png');1111</code></pre>11121113<p>This is equivalent to:</p>11141115<pre><code>res.attachment(file);1116res.sendfile(file);1117</code></pre>11181119<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>11201121<p>The <code>res.send()</code> method is a high level response utility allowing you to pass1122objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status1123code based responses. The following are all valid uses:</p>11241125<pre><code> res.send(); // 2041126 res.send(new Buffer('wahoo'));1127 res.send({ some: 'json' });1128 res.send('<p>some html</p>');1129 res.send('Sorry, cant find that', 404);1130 res.send('text', { 'Content-Type': 'text/plain' }, 201);1131 res.send(404);1132</code></pre>11331134<p>By default the <em>Content-Type</em> response header is set, however if explicitly1135assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1136it will not be set again.</p>Added screencasts pageTj Holowaychukbefore adoption4144af3
lines 1137–1138why, one step back11371138<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>Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 1139–1202why, one step back11391140<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>11411142<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>11431144<pre><code>res.redirect('/', 301);1145res.redirect('/account');1146res.redirect('http://google.com');1147res.redirect('home');1148res.redirect('back');1149</code></pre>11501151<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1152The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1153the "home" setting and defaults to "/".</p>11541155<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>11561157<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>11581159<pre><code>// "Remember me" for 15 minutes 1160res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1161</code></pre>11621163<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>11641165<pre><code>app.use(express.cookieDecoder());11661167app.get('/', function(req, res){1168 // use req.cookies.rememberme1169});1170</code></pre>11711172<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>11731174<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>11751176<pre><code>res.clearCookie('rememberme');1177</code></pre>11781179<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>11801181<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1182When a callback function is given a response will <em>not</em> be made1183automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>11841185<p> Most engines accept one or more of the following options,1186 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>11871188<ul>1189<li><em>scope</em> Template evaluation context (value of <em>this</em>)</li>1190<li><em>locals</em> Object containing local variables</li>1191<li><em>debug</em> Output debugging information</li>1192<li><em>status</em> Response status code, defaults to 200</li>1193<li><em>headers</em> Response headers object</li>1194</ul>119511961197<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>11981199<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1200to the view as a local variable.</p>12011202<ul>Rebuilt docsTj Holowaychukbefore adoptiond017c3e
lines 1203–1204why, one step back1203<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1204<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 1205–1243why, one step back12051206<ul>1207<li>as: 'something' will add the <em>something</em> local variable</li>1208<li>as: this will use the collection value as the template context</li>1209<li>as: global will merge the collection value's properties with <em>locals</em></li>1210</ul>1211</li>1212<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1213For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1214</ul>121512161217<p>The following are equivalent, and the name of collection value when passed1218to the partial will be <em>movie</em> as derived from the name.</p>12191220<pre><code>partial('theatre/movie.jade', { collection: movies });1221partial('theatre/movie.jade', movies);1222partial('movie.jade', { collection: movies });1223partial('movie.jade', movies);1224partial('movie', movies);1225// In view: movie.director1226</code></pre>12271228<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>12291230<pre><code>partial('movie', { collection: movies, as: 'video' });1231// In view: video.director1232</code></pre>12331234<p>Also we can make our movie the value of <em>this</em> within our view so that instead1235of <em>movie.director</em> we could use <em>this.director</em>.</p>12361237<pre><code>partial('movie', { collection: movies, as: this });1238// In view: this.director1239</code></pre>12401241<p>Another alternative is to "explode" the properties of the collection item into1242pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>1243Rebuilt docsTj Holowaychukbefore adoptiond017c3e
line 1244why, one step back1244<pre><code>partial('movie', { collection: movies, as: global });Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 1245–1247why, one step back1245// In view: director1246</code></pre>1247Rebuilt docsTj Holowaychukbefore adoptiond017c3e
lines 1248–1268why, one step back1248<p>This same logic applies to a single partial object usage:</p>12491250<pre><code>partial('movie', { object: movie, as: this });1251// In view: this.director12521253partial('movie', { object: movie, as: global });1254// In view: director12551256partial('movie', { object: movie, as: 'video' });1257// In view: video.director12581259partial('movie', { object: movie });1260// In view: movie.director1261</code></pre>12621263<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>12641265<pre><code>partial('movie', movie);1266// => In view: movie.director1267</code></pre>1268Re-built docsTj Holowaychukbefore adoption8e63d04
lines 1269–1286why, one step back1269<h3 id="res-local-name-val-">res.local(name[, val])</h3>12701271<p>Get or set the given local variable <em>name</em>. The locals built up for a response are applied to those given to the view rendering methods such as <code>res.render()</code>.</p>12721273<pre><code> app.all('/movie/:id', function(req, res, next){1274 Movie.get(req.params.id, function(err, movie){1275 // Assigns res.locals.movie = movie1276 res.local('movie', movie);1277 });1278 });12791280 app.get('/movie/:id', function(req, res){1281 // movie is already a local, however we1282 // can pass more if we wish1283 res.render('movie', { displayReviews: true });1284 });1285</code></pre>1286Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 1287–1293why, one step back1287<h3 id="app-set-name-val-">app.set(name[, val])</h3>12881289<p>Apply an application level setting <em>name</em> to <em>val</em>, or1290get the value of <em>name</em> when <em>val</em> is not present:</p>12911292<pre><code>app.set('views', __dirname + '/views');1293app.set('views');Rebuilt docsTj Holowaychukbefore adoptiond017c3e
lines 1294–1299why, one step back1294// => ...path...1295</code></pre>12961297<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>12981299<pre><code>app.settings.viewsUpdated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 1300–1309why, one step back1300// => ...path...1301</code></pre>13021303<h3 id="app-enable-name-">app.enable(name)</h3>13041305<p>Enable the given setting <em>name</em>:</p>13061307<pre><code>app.enable('some arbitrary setting');1308app.set('some arbitrary setting');1309// => trueRe-built docsTj Holowaychukbefore adoption8e63d04
lines 1310–1312why, one step back13101311app.enabled('some arbitrary setting');1312// => trueUpdated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 1313–1320why, one step back1313</code></pre>13141315<h3 id="app-disable-name-">app.disable(name)</h3>13161317<p>Disable the given setting <em>name</em>:</p>13181319<pre><code>app.disable('some setting');1320app.set('some setting');Re-built docsTj Holowaychukbefore adoption8e63d04
lines 1321–1323why, one step back1321// => false13221323app.disabled('some setting');Updated jade submoduleTj Holowaychukbefore adoptionc4ba1b0
lines 1324–1488why, one step back1324// => false1325</code></pre>13261327<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>13281329<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>13301331<pre><code>app.configure(function(){1332 // executed for each env1333});13341335app.configure('development', function(){1336 // executed for 'development' only1337});1338</code></pre>13391340<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>13411342<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>13431344<pre><code>app.redirect('google', 'http://google.com');1345</code></pre>13461347<p>Now in a route we may call:</p>13481349<p> res.redirect('google');</p>13501351<p>We may also map dynamic redirects:</p>13521353<pre><code>app.redirect('comments', function(req, res){1354 return '/post/' + req.params.id + '/comments';1355});1356</code></pre>13571358<p>So now we may do the following, and the redirect will dynamically adjust to1359the context of the request. If we called this route with <em>GET /post/12</em> our1360redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>13611362<pre><code>app.get('/post/:id', function(req, res){1363 res.redirect('comments');1364});1365</code></pre>13661367<h3 id="app-error-function-">app.error(function)</h3>13681369<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1370Note that we may set several error handlers by making several calls to this method, however the handler1371should call <em>next(err)</em> if it does not wish to deal with the exception:</p>13721373<pre><code>app.error(function(err, req, res, next){1374 res.send(err.message, 500);1375});1376</code></pre>13771378<h3 id="app-helpers-obj-">app.helpers(obj)</h3>13791380<p>Registers static view helpers.</p>13811382<pre><code>app.helpers({1383 name: function(first, last){ return first + ', ' + last },1384 firstName: 'tj',1385 lastName: 'holowaychuk'1386});1387</code></pre>13881389<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1390as well as the <em>name()</em> function exposed.</p>13911392<pre><code><%= name(firstName, lastName) %>1393</code></pre>13941395<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>13961397<p>Registers dynamic view helpers. Dynamic view helpers1398are simply functions which accept <em>req</em>, <em>res</em>, and are1399evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1400becomes the local variable it is associated with.</p>14011402<pre><code>app.dynamicHelpers({1403 session: function(req, res){1404 return req.session;1405 }1406});1407</code></pre>14081409<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>14101411<pre><code><%= session.name %>1412</code></pre>14131414<h3 id="app-mounted-fn-">app.mounted(fn)</h3>14151416<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>14171418<pre><code>var app = express.createServer(),1419 blog = express.createServer();14201421blog.mounted(function(parent){1422 // parent is app1423 // "this" is blog1424});14251426app.use(blog);1427</code></pre>14281429<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>14301431<p>Register the given template engine <em>exports</em>1432as <em>ext</em>. For example we may wish to map ".html"1433files to jade:</p>14341435<pre><code> app.register('.html', require('jade'));1436</code></pre>14371438<p>This is also useful for libraries that may not1439match extensions correctly. For example my haml.js1440library is installed from npm as "hamljs" so instead1441of layout.hamljs, we can register the engine as ".haml":</p>14421443<pre><code> app.register('.haml', require('haml-js'));1444</code></pre>14451446<p>For engines that do not comply with the Express1447specification, we can also wrap their api this way.</p>14481449<pre><code> app.register('.foo', {1450 render: function(str, options) {1451 // perhaps their api is1452 // return foo.toHTML(str, options);1453 }1454 });1455</code></pre>14561457<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>14581459<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1460connections will be accepted via <em>INADDR_ANY</em>.</p>14611462<pre><code>app.listen();1463app.listen(3000);1464app.listen(3000, 'n.n.n.n');1465</code></pre>14661467<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>14681469<pre><code>app.listen('/tmp/express.sock');1470</code></pre>14711472<p>Then try it out:</p>14731474<pre><code>$ telnet /tmp/express.sock1475GET / HTTP/1.114761477HTTP/1.1 200 OK1478Content-Type: text/plain1479Content-Length: 1114801481Hello World1482</code></pre>14831484</div>1485 </div>1486 </div>1487 </body>1488</html>