Skip to content
Myr

guide.html

This file

Path

docs/guide.html

1,807 lines · 63.4 KiB · HTML

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 05b76a1 point at it.

prepping blog example for new expressTj Holowaychukbefore adoption05b76a1

lines 1–1807why, one step back
1<html>
2 <head>3 <title>Express - node web framework</title>4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">5 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>6 <style>7 #tagline {8 margin-left: 75px;9 margin-bottom: 30px;10 color: rgba(255,255,255,0.7); }11 html {12 background: #1c1c1c url(images/bg.tile.jpg); }1314 body {15 margin: 0;16 padding-bottom: 30px;17 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";18 font-size: 14px;19 line-height: 1.5;20 -webkit-font-smoothing: antialiased;21 background: url(images/bg.jpg) 50% 0 no-repeat;22 color: #8b8b8b; }2324 * {25 outline: none; }2627 em {28 color: white; }2930 a img {31 border: none !important; }3233 a {34 font-weight: bold;35 text-decoration: none;36 color: white;37 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;38 -webkit-transition-duration: 0.15s;39 -webkit-transition-timing-function: ease-out; }40 a:hover {41 opacity: 0.8; }4243 h1, h2, h3, h4 {44 margin: 45px 0 0 0;45 color: white;46 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4748 h3 {49 font-size: 18px; }50 h4 {51 margin-left: 10px;52 font-size: 14px;53 }5455 pre {56 margin: 20px 10px;57 padding: 25px 20px;58 background: rgba(0,0,0,0.5);59 border: 1px solid #323232;60 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);62 -webkit-border-radius: 5px;63 -moz-border-radius: 5px; }6465 code {66 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6768 ul {69 margin: 15px 0;70 padding: 0 0 0 35px; }71 ul li {72 margin: 0;73 padding: 2px 0;74 list-style: square; }75 ul li ul {76 margin: 0;77 padding-left: 12px;78 }7980 .man-name, #Express { display:none; }8182 .sect {83 margin-left: 40px; }84 img {85 margin-left: 20px;86 margin-bottom: 15px;87 }8889 #logo {90 display: block;91 margin-left: 30%;92 margin-bottom: 30px;93 width: 194px;94 height: 51px;95 background: url(images/logo.png) 0 0 no-repeat;96 text-indent: -99999px; }97 #logo:hover {98 opacity: 0.7; }99 #logo:active {100 opacity: 0.3; }101102 #ribbon {103 position: fixed;104 top: 0;105 right: 0;106 z-index: 2; }107108 #wrapper {109 width: 100%;110 min-height: 800px;111 background: url(images/top.png) 0 0 repeat-x; }112113 #container {114 margin: 0 auto;115 padding-top: 80px;116 width: 550px; }117118 #toc {119 position: fixed;120 top: 0;121 left: 0;122 margin: 0 0 0 15px;123 padding: 15px;124 height: 100%;125 background: rgba(0,0,0,0.2);126 overflow: auto;127 border-right: 1px solid rgba(255,255,255,0.05);128 }129 #toc li {130 padding: 0;131 list-style: none;132 }133 #toc li a {134 font-size: 11px;135 }136 #menu {137 margin-left: 75px;138 padding: 0;139 padding-bottom: 30px; }140 #menu li {141 display: inline;142 list-style: none; }143 #menu li a {144 display: block;145 float: left;146 margin: 0 2px;147 padding: 3px 15px;148 background: rgba(0,0,0,0.2);149 -webkit-border-radius: 8px;150 -moz-border-radius: 8px;151 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);152 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);153 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;154 -webkit-transition-duration: 0.15s;155 -webkit-transition-timing-function: ease-out; }156 #menu li a:hover,157 #menu li a.active {158 background: rgba(0,0,0,0.5); }159 #menu li a:active {160 background: rgba(0,0,0,0.1);161 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);162 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }163 </style>164 <script>165 $(function(){166 $('.section').hide();167 $('.toggle, a.section-title').toggle(function(){168 $(this).siblings('ul').fadeIn(300);169 return false;170 }, function(){171 $(this).siblings('ul').fadeOut(300);172 return false;173 });174 });175 </script>176 </head>177 <body>178 <a href='http://github.com/visionmedia/express'> 179 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 180 </a>181 <div id="wrapper">182 <div id="container"><ul id="toc">183184</ul><ul id="toc">185<li><a href="#installation">Installation</a></li>186<li><a href="#creating-a server">Creating A Server</a></li>187<li><a href="#creating-an https server">Creating An HTTPS Server</a></li>188<li><a href="#configuration">Configuration</a></li>189<li><a href="#settings">Settings</a></li>190<li><a href="#routing">Routing</a></li>191<li><a href="#passing-route control">Passing Route Control</a></li>192<li><a href="#middleware">Middleware</a></li>193<li><a href="#route-middleware">Route Middleware</a></li>194<li><a href="#http-methods">HTTP Methods</a></li>195<li><a href="#error-handling">Error Handling</a></li>196<li><a href="#route-param pre-conditions">Route Param Pre-conditions</a></li>197<li><a href="#view-rendering">View Rendering</a></li>198<li><a href="#view-partials">View Partials</a></li>199<li><a href="#view-lookup">View Lookup</a></li>200<li><a href="#template-engines">Template Engines</a></li>201<li><a href="#session-support">Session Support</a></li>202<li><a href="#migration-guide">Migration Guide</a></li>203<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">204<li><a href="#req.header()">header()</a></li>205<li><a href="#req.accepts()">accepts()</a></li>206<li><a href="#req.is()">is()</a></li>207<li><a href="#req.param()">param()</a></li>208<li><a href="#req.get()">get()</a></li>209<li><a href="#req.flash()">flash()</a></li>210<li><a href="#req.isxmlhttprequest">isXMLHttpRequest</a></li>211</ul></li>212<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">213<li><a href="#res.header()">header()</a></li>214<li><a href="#res.charset">charset</a></li>215<li><a href="#res.contenttype()">contentType()</a></li>216<li><a href="#res.attachment()">attachment()</a></li>217<li><a href="#res.sendfile()">sendfile()</a></li>218<li><a href="#res.download()">download()</a></li>219<li><a href="#res.send()">send()</a></li>220<li><a href="#res.redirect()">redirect()</a></li>221<li><a href="#res.cookie()">cookie()</a></li>222<li><a href="#res.clearcookie()">clearCookie()</a></li>223<li><a href="#res.render()">render()</a></li>224<li><a href="#res.partial()">partial()</a></li>225<li><a href="#res.local()">local()</a></li>226<li><a href="#res.locals()">locals()</a></li>227</ul></li>228<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">229<li><a href="#app.set()">set()</a></li>230<li><a href="#app.enable()">enable()</a></li>231<li><a href="#app.enabled()">enabled()</a></li>232<li><a href="#app.disable()">disable()</a></li>233<li><a href="#app.disabled()">disabled()</a></li>234<li><a href="#app.configure()">configure()</a></li>235<li><a href="#app.redirect()">redirect()</a></li>236<li><a href="#app.error()">error()</a></li>237<li><a href="#app.helpers()">helpers()</a></li>238<li><a href="#app.dynamichelpers()">dynamicHelpers()</a></li>239<li><a href="#app.lookup">lookup</a></li>240<li><a href="#app.match">match</a></li>241<li><a href="#app.mounted()">mounted()</a></li>242<li><a href="#app.register()">register()</a></li>243<li><a href="#app.listen()">listen()</a></li>244</ul></li>245</ul>246 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 247 <p id="tagline">248 High performance, high class web development for249 <a href="http://nodejs.org">Node.js</a>250 </p>251 <ul id="menu">252 <li><a href="index.html">Home</a></li>253 <li><a href="guide.html">Guide</a></li>254 <li><a href="screencasts.html">Screencasts</a></li>255 <li><a href="applications.html">Applications</a></li>256 </ul>257<h3 id="installation">Installation</h3>258259<pre><code>$ npm install express260</code></pre>261262<p>or to access the <code>express(1)</code> executable install globally:</p>263264<pre><code>$ npm install -g express265</code></pre>266267<h2>Quick Start</h2>268269<p> The quickest way to get started with express is to utilize the executable <code>express(1)</code> to generate an application as shown below:</p>270271<p> Create the app:</p>272273<pre><code>$ npm install -g express274$ express /tmp/foo &amp;&amp; cd /tmp/foo275</code></pre>276277<p> Install dependencies:</p>278279<pre><code>$ npm install -d280</code></pre>281282<p> Start the server:</p>283284<pre><code>$ node app.js285</code></pre>286287<h3 id="creating-a server">Creating A Server</h3>288289<p> To create an instance of the <em>express.HTTPServer</em>, simply invoke the <em>createServer()</em> method. With our instance <em>app</em> we can then define routes based on the HTTP verbs, in this example <em>app.get()</em>.</p>290291<pre><code>var app = require('express').createServer();292293app.get('/', function(req, res){294 res.send('hello world');295});296297app.listen(3000);298</code></pre>299300<h3 id="creating-an https server">Creating An HTTPS Server</h3>301302<p> To initialize a <em>express.HTTPSServer</em> we do the same as above, however we303 pass an options object, accepting <em>key</em>, <em>cert</em> and the others mentioned in node&rsquo;s <a href="http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer">https documentation</a>.</p>304305<pre><code> var app = require('express').createServer({ key: ... });306</code></pre>307308<h3 id="configuration">Configuration</h3>309310<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers311can use the <em>configure()</em> method to setup needs required by the current environment. When312<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment313prior to the environment specific callback.</p>314315<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces316in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.317Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,318otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>319320<pre><code>app.configure(function(){321 app.use(express.methodOverride());322 app.use(express.bodyParser());323 app.use(app.router);324});325326app.configure('development', function(){327 app.use(express.static(__dirname + '/public'));328 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));329});330331app.configure('production', function(){332 var oneYear = 31557600000;333 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));334 app.use(express.errorHandler());335});336</code></pre>337338<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>339340<pre><code> app.configure(function(){341 app.set('views', __dirname + '/views');342 app.set('views');343 // =&gt; "/absolute/path/to/views"344345 app.enable('some feature');346 // same as app.set('some feature', true);347348 app.disable('some feature');349 // same as app.set('some feature', false);350351 app.enabled('some feature')352 // =&gt; false353 });354</code></pre>355356<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>357358<pre><code>$ NODE_ENV=production node app.js359</code></pre>360361<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>362363<h3 id="settings">Settings</h3>364365<p>Express supports the following settings out of the box:</p>366367<ul>368<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>369<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>370<li><em>view engine</em> Default view engine name for views rendered without extensions</li>371<li><em>view options</em> An object specifying global view options</li>372<li><em>view cache</em> Enable view caching (enabled in production)</li>373<li><em>case sensitive routes</em> Enable case-sensitive routing</li>374</ul>375376377<h3 id="routing">Routing</h3>378379<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.380For example we may want to render a user&rsquo;s account for the path <em>/user/12</em>, this381can be done by defining the route below. The values associated to the named placeholders382are available as <code>req.params</code>.</p>383384<pre><code>app.get('/user/:id', function(req, res){385 res.send('user ' + req.params.id);386});387</code></pre>388389<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example390when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>391392<pre><code>\/user\/([^\/]+)\/?393</code></pre>394395<p>Regular expression literals may also be passed for complex uses. Since capture396groups with literal <em>RegExp</em>&rsquo;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>397398<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){399 res.send(req.params);400});401</code></pre>402403<p>Curl requests against the previously defined route:</p>404405<pre><code> $ curl http://dev:3000/user406 [null,null]407 $ curl http://dev:3000/users408 [null,null]409 $ curl http://dev:3000/users/1410 ["1",null]411 $ curl http://dev:3000/users/1..15412 ["1","15"]413</code></pre>414415<p>Below are some route examples, and the associated paths that they416may consume:</p>417418<pre><code> "/user/:id"419 /user/12420421 "/users/:id?"422 /users/5423 /users424425 "/files/*"426 /files/jquery.js427 /files/javascripts/jquery.js428429 "/file/*.*"430 /files/jquery.js431 /files/javascripts/jquery.js432433 "/user/:id/:operation?"434 /user/1435 /user/1/edit436437 "/products.:format"438 /products.json439 /products.xml440441 "/products.:format?"442 /products.json443 /products.xml444 /products445446 "/user/:id.:format?"447 /user/12448 /user/12.json449</code></pre>450451<p>For example we can <strong>POST</strong> some json, and echo the json back using the <em>bodyParser</em> middleware which will parse json request bodies (as well as others), and place the result in <em>req.body</em>:</p>452453<pre><code>var express = require('express')454 , app = express.createServer();455456app.use(express.bodyParser());457458app.post('/', function(req, res){459 res.send(req.body);460});461462app.listen(3000);463</code></pre>464465<p>Typically we may use a &ldquo;dumb&rdquo; placeholder such as &ldquo;/user/:id&rdquo; which has no restrictions, however say for example we are limiting a user id to digits, we may use <em>&lsquo;/user/:id([0-9]+)&rsquo;</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>466467<h3 id="passing-route control">Passing Route Control</h3>468469<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,470the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,471and middleware continue to be invoked in the order that they are added via <em>use()</em>. The same is true for several routes which have the same path defined, they will simply be executed in order until one does <em>not</em> call <em>next()</em> and decides to respond.</p>472473<pre><code>app.get('/users/:id?', function(req, res, next){474 var id = req.params.id;475 if (id) {476 // do something477 } else {478 next();479 }480});481482app.get('/users', function(req, res){483 // do something else484});485</code></pre>486487<p>The <em>app.all()</em> method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to <em>req.user</em>.</p>488489<pre><code>var express = require('express')490 , app = express.createServer();491492var users = [{ name: 'tj' }];493494app.all('/user/:id/:op?', function(req, res, next){495 req.user = users[req.params.id];496 if (req.user) {497 next();498 } else {499 next(new Error('cannot find user ' + req.params.id));500 }501});502503app.get('/user/:id', function(req, res){504 res.send('viewing ' + req.user.name);505});506507app.get('/user/:id/edit', function(req, res){508 res.send('editing ' + req.user.name);509});510511app.put('/user/:id', function(req, res){512 res.send('updating ' + req.user.name);513});514515app.get('*', function(req, res){516 res.send('what???', 404);517});518519app.listen(3000); 520</code></pre>521522<h3 id="middleware">Middleware</h3>523524<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be525passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>526527<pre><code> var express = require('express');528529var app = express.createServer(530 express.logger()531 , express.bodyParser()532 );533</code></pre>534535<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manner.</p>536537<pre><code>app.use(express.logger({ format: ':method :url' }));538</code></pre>539540<p>Typically with connect middleware you would <em>require(&lsquo;connect&rsquo;)</em> like so:</p>541542<pre><code>var connect = require('connect');543app.use(connect.logger());544app.use(connect.bodyParser());545</code></pre>546547<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>548549<pre><code>app.use(express.logger());550app.use(express.bodyParser());551</code></pre>552553<p>Middleware ordering is important, when Connect receives a request the <em>first</em> middleware we pass to <em>createServer()</em> or <em>use()</em> is executed with three parameters, <em>request</em>, <em>response</em>, and a callback function usually named <em>next</em>. When <em>next()</em> is invoked the second middleware will then have it&rsquo;s turn and so on. This is important to note because many middleware depend on each other, for example <em>methodOverride()</em> checks <em>req.body.</em>method<em> for the HTTP method override, however </em>bodyParser()<em> parses the request body and populates </em>req.body<em>. Another example of this is cookie parsing and session support, we must first </em>use()<em> </em>cookieParser()<em> followed by </em>session()_.</p>554555<p>Many Express applications may contain the line <em>app.use(app.router)</em>, while this may appear strange, it&rsquo;s simply the middleware function that contains all defined routes, and performs route lookup based on the current request url and HTTP method. Express allows you to position this middleware, though by default it will be added to the bottom. By positioning the router, we can alter middleware precedence, for example we may want to add error reporting as the <em>last</em> middleware so that any exception passed to <em>next()</em> will be handled by it, or perhaps we want static file serving to have low precedence, allowing our routes to intercept requests to a static file to count downloads etc. This may look a little like below</p>556557<pre><code>app.use(express.logger(...));558app.use(express.bodyParser(...));559app.use(express.cookieParser(...));560app.use(express.session(...));561app.use(app.router);562app.use(express.static(...));563app.use(express.errorHandler(...));564</code></pre>565566<p>First we add <em>logger()</em> so that it may wrap node&rsquo;s <em>req.end()</em> method, providing us with response-time data. Next the request&rsquo;s body will be parsed (if any), followed by cookie parsing and session support, meaning <em>req.session</em> will be defined by the time we hit our routes in <em>app.router</em>. If a request such as <em>GET /javascripts/jquery.js</em> is handled by our routes, and we do not call <em>next()</em> then the <em>static()</em> middleware will never see this request, however if were to define a route as shown below, we can record stats, refuse downloads, consume download credits etc.</p>567568<pre><code>var downloads = {};569570app.use(app.router);571app.use(express.static(__dirname + '/public'));572573app.get('/*', function(req, res, next){574 var file = req.params[0];575 downloads[file] = downloads[file] || 0;576 downloads[file]++;577 next();578});579</code></pre>580581<h3 id="route-middleware">Route Middleware</h3>582583<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>584585<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>586587<pre><code>app.get('/user/:id', function(req, res, next){588 loadUser(req.params.id, function(err, user){589 if (err) return next(err);590 res.send('Viewing user ' + user.name);591 });592});593</code></pre>594595<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>596597<pre><code>function loadUser(req, res, next) {598 // You would fetch your user from the db599 var user = users[req.params.id];600 if (user) {601 req.user = user;602 next();603 } else {604 next(new Error('Failed to load user ' + req.params.id));605 }606}607608app.get('/user/:id', loadUser, function(req, res){609 res.send('Viewing user ' + req.user.name);610});611</code></pre>612613<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>614615<pre><code>function andRestrictToSelf(req, res, next) {616 req.authenticatedUser.id == req.user.id617 ? next()618 : next(new Error('Unauthorized'));619}620621app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){622 res.send('Editing user ' + req.user.name);623});624</code></pre>625626<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>627628<pre><code>function andRestrictTo(role) {629 return function(req, res, next) {630 req.authenticatedUser.role == role631 ? next()632 : next(new Error('Unauthorized'));633 }634}635636app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){637 res.send('Deleted user ' + req.user.name);638});639</code></pre>640641<p>Commonly used &ldquo;stacks&rdquo; of middleware can be passed as an array (<em>applied recursively</em>), which can be mixed and matched to any degree.</p>642643<pre><code>var a = [middleware1, middleware2]644 , b = [middleware3, middleware4]645 , all = [a, b];646647app.get('/foo', a, function(){});648app.get('/bar', a, function(){});649650app.get('/', a, middleware3, middleware4, function(){});651app.get('/', a, b, function(){});652app.get('/', all, function(){});653</code></pre>654655<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>656657<p>There are times when we may want to &ldquo;skip&rdquo; passed remaining route middleware, but continue matching subsequent routes. To do this we invoke <code>next()</code> with the string &ldquo;route&rdquo; <code>next('route')</code>. If no remaining routes match the request url then Express will respond with 404 Not Found.</p>658659<h3 id="http-methods">HTTP Methods</h3>660661<p>We have seen <em>app.get()</em> a few times, however Express also exposes other familiar HTTP verbs in the same manner, such as <em>app.post()</em>, <em>app.del()</em>, etc.</p>662663<p> A common example for <em>POST</em> usage, is when &ldquo;submitting&rdquo; a form. Below we simply set our form method to &ldquo;post&rdquo; in our html, and control will be given to the route we have defined below it.</p>664665<pre><code> &lt;form method="post" action="/"&gt;666 &lt;input type="text" name="user[name]" /&gt;667 &lt;input type="text" name="user[email]" /&gt;668 &lt;input type="submit" value="Submit" /&gt;669 &lt;/form&gt;670</code></pre>671672<p>By default Express does not know what to do with this request body, so we should add the <em>bodyParser</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> and <em>application/json</em> request bodies and place the variables in <em>req.body</em>. We can do this by &ldquo;using&rdquo; the middleware as shown below:</p>673674<pre><code>app.use(express.bodyParser());675</code></pre>676677<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>678679<pre><code>app.post('/', function(req, res){680 console.log(req.body.user);681 res.redirect('back');682});683</code></pre>684685<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyParser</em> so that it can utilize it&rsquo;s <em>req.body</em> containing the form values.</p>686687<pre><code>app.use(express.bodyParser());688app.use(express.methodOverride());689</code></pre>690691<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>692693<pre><code>&lt;form method="post" action="/"&gt;694 &lt;input type="hidden" name="_method" value="put" /&gt;695 &lt;input type="text" name="user[name]" /&gt;696 &lt;input type="text" name="user[email]" /&gt;697 &lt;input type="submit" value="Submit" /&gt; 698&lt;/form&gt;699700app.put('/', function(){701 console.log(req.body.user);702 res.redirect('back');703});704</code></pre>705706<h3 id="error-handling">Error Handling</h3>707708<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,709or passed to <em>next(err)</em>. Below is an example which serves different pages based on our710ad-hoc <em>NotFound</em> exception:</p>711712<pre><code>function NotFound(msg){713 this.name = 'NotFound';714 Error.call(this, msg);715 Error.captureStackTrace(this, arguments.callee);716}717718NotFound.prototype.__proto__ = Error.prototype;719720app.get('/404', function(req, res){721 throw new NotFound;722});723724app.get('/500', function(req, res){725 throw new Error('keyboard cat!');726});727</code></pre>728729<p>We can call <em>app.error()</em> several times as shown below.730Here we check for an instanceof <em>NotFound</em> and show the731404 page, or we pass on to the next error handler.</p>732733<p>Note that these handlers can be defined anywhere, as they734will be placed below the route handlers on <em>listen()</em>. This735allows for definition within <em>configure()</em> blocks so we can736handle exceptions in different ways based on the environment.</p>737738<pre><code>app.error(function(err, req, res, next){739 if (err instanceof NotFound) {740 res.render('404.jade');741 } else {742 next(err);743 }744});745</code></pre>746747<p>Here we assume all errors as 500 for the simplicity of748this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the <em>error.code</em> of <em>ENOENT</em>, meaning &ldquo;no such file or directory&rdquo;, we can utilize this in our error handling and display a page specific to this if desired.</p>749750<pre><code>app.error(function(err, req, res){751 res.render('500.jade', {752 error: err753 });754});755</code></pre>756757<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware758to report on exceptions. For example if we wish to output exceptions759in &ldquo;development&rdquo; mode to <em>stderr</em> we can use:</p>760761<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));762</code></pre>763764<p>Also during development we may want fancy html pages to show exceptions765that are passed or thrown, so we can set <em>showStack</em> to true:</p>766767<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));768</code></pre>769770<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>771is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>772773<h3 id="route-param pre-conditions">Route Param Pre-conditions</h3>774775<p>Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for <em>/user/:id</em>, we might typically do something like below:</p>776777<pre><code>app.get('/user/:userId', function(req, res, next){778 User.get(req.params.userId, function(err, user){779 if (err) return next(err);780 res.send('user ' + user.name);781 });782}); 783</code></pre>784785<p>With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>786787<pre><code>app.param('userId', function(req, res, next, id){788 User.get(id, function(err, user){789 if (err) return next(err);790 if (!user) return next(new Error('failed to find user'));791 req.user = user;792 next();793 });794});795</code></pre>796797<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>798799<pre><code>app.get('/user/:userId', function(req, res){800 res.send('user ' + req.user.name);801});802</code></pre>803804<h3 id="view-rendering">View Rendering</h3>805806<p>View filenames take the form &ldquo;&lt;name&gt;.&lt;engine&gt;&rdquo;, where &lt;engine&gt; is the name807of the module that will be required. For example the view <em>layout.ejs</em> will808tell the view system to <em>require(&lsquo;ejs&rsquo;)</em>, the module being loaded must export the method <em>exports.compile(str, options)</em>, and return a <em>Function</em> to comply with Express. To alter this behaviour809<em>app.register()</em> can be used to map engines to file extensions, so that for example &ldquo;foo.html&rdquo; can be rendered by ejs.</p>810811<p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,812and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as813the <em>body</em> local variable in <em>layout.jade</em>.</p>814815<pre><code>app.get('/', function(req, res){816 res.render('index.jade', { title: 'My Site' });817});818</code></pre>819820<p>The new <em>view engine</em> setting allows us to specify our default template engine,821so for example when using jade we could set:</p>822823<pre><code>app.set('view engine', 'jade');824</code></pre>825826<p>Allowing us to render with:</p>827828<pre><code>res.render('index');829</code></pre>830831<p>vs:</p>832833<pre><code>res.render('index.jade');834</code></pre>835836<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still837mix and match template engines:</p>838839<pre><code>res.render('another-page.ejs');840</code></pre>841842<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>843844<pre><code>app.set('view options', {845 layout: false846});847</code></pre>848849<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>850851<pre><code>res.render('myview.ejs', { layout: true });852</code></pre>853854<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>855856<pre><code>res.render('page', { layout: 'mylayout' });857</code></pre>858859<p>Otherwise we must specify the extension:</p>860861<pre><code>res.render('page', { layout: 'mylayout.jade' });862</code></pre>863864<p>These paths may also be absolute:</p>865866<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });867</code></pre>868869<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>870871<pre><code>app.set('view options', {872 open: '{{',873 close: '}}'874});875</code></pre>876877<h3 id="view-partials">View Partials</h3>878879<p>The Express view system has built-in support for partials and collections, which are &ldquo;mini&rdquo; views representing a document fragment. For example rather than iterating880in a view to display comments, we could use partial collection:</p>881882<pre><code>partial('comment', { collection: comments });883</code></pre>884885<p>If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>886887<pre><code>partial('comment', comments);888</code></pre>889890<p>When using the partial collection support a few &ldquo;magic&rdquo; locals are provided891for free:</p>892893<ul>894<li><em>firstInCollection</em> true if this is the first object</li>895<li><em>indexInCollection</em> index of the object in the collection</li>896<li><em>lastInCollection</em> true if this is the last object</li>897<li><em>collectionLength</em> length of the collection</li>898</ul>899900901<p>Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well. So for example if we were to render a blog post with <em>partial(&lsquo;blog/post&rsquo;, post)</em> it would generate the <em>post</em> local, but the view calling this function had the local <em>user</em>, it would be available to the <em>blog/post</em> view as well.</p>902903<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>904905<p><strong>NOTE:</strong> be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead.</p>906907<h3 id="view-lookup">View Lookup</h3>908909<p>View lookup is performed relative to the parent view, for example if we had a page view named <em>views/user/list.jade</em>, and within that view we did <em>partial(&lsquo;edit&rsquo;)</em> it would attempt to load <em>views/user/edit.jade</em>, whereas <em>partial(&lsquo;../messages&rsquo;)</em> would load <em>views/messages.jade</em>.</p>910911<p>The view system also allows for index templates, allowing you to have a directory of the same name. For example within a route we may have <em>res.render(&lsquo;users&rsquo;)</em> either <em>views/users.jade</em>, or <em>views/users/index.jade</em>.</p>912913<p>When utilizing index views as shown above, we may reference <em>views/users/index.jade</em> from a view in the same directory by <em>partial(&lsquo;users&rsquo;)</em>, and the view system will try <em>../users/index</em>, preventing us from needing to call <em>partial(&lsquo;index&rsquo;)</em>.</p>914915<h3 id="template-engines">Template Engines</h3>916917<p>Below are a few template engines commonly used with Express:</p>918919<ul>920<li><a href="http://github.com/visionmedia/haml.js">Haml</a> haml implementation</li>921<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>922<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>923<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>924<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>925</ul>926927928<h3 id="session-support">Session Support</h3>929930<p>Sessions support can be added by using Connect&rsquo;s <em>session</em> middleware. To do so we also need the <em>cookieParser</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>931932<pre><code>app.use(express.cookieParser());933app.use(express.session({ secret: "keyboard cat" }));934</code></pre>935936<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>937938<pre><code>var RedisStore = require('connect-redis')(express);939app.use(express.cookieParser());940app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));941</code></pre>942943<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>944945<pre><code>var RedisStore = require('connect-redis')(express);946app.use(express.bodyParser());947app.use(express.cookieParser());948app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));949950app.post('/add-to-cart', function(req, res){951 // Perhaps we posted several items with a form952 // (use the bodyParser() middleware for this)953 var items = req.body.items;954 req.session.items = items;955 res.redirect('back');956});957958app.get('/add-to-cart', function(req, res){959 // When redirected back to GET /add-to-cart960 // we could check req.session.items &amp;&amp; req.session.items.length961 // to print out a message962 if (req.session.items &amp;&amp; req.session.items.length) {963 req.flash('info', 'You have %s items in your cart', req.session.items.length);964 }965 res.render('shopping-cart');966});967</code></pre>968969<p>The <em>req.session</em> object also has methods such as <em>Session#touch()</em>, <em>Session#destroy()</em>, <em>Session#regenerate()</em> among others to maintain and manipulate sessions. For more information view the <a href="http://senchalabs.github.com/connect/middleware-session.html">Connect Session</a> documentation.</p>970971<h3 id="migration-guide">Migration Guide</h3>972973<p> Express 1.x developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application to work with Express 2.x, Connect 1.x, and Node 0.4.x.</p>974975<h3 id="req.header()">req.header(key[, defaultValue])</h3>976977<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>978979<pre><code>req.header('Host');980req.header('host');981req.header('Accept', '*/*');982</code></pre>983984<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>985986<pre><code>// sent Referrer: http://google.com987988req.header('Referer');989// =&gt; "http://google.com"990991req.header('Referrer');992// =&gt; "http://google.com"993</code></pre>994995<h3 id="req.accepts()">req.accepts(type)</h3>996997<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>998999<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise1000the given <em>type</em> is matched by an exact match, and then subtypes. You1001may pass the subtype such as &ldquo;html&rdquo; which is then converted internally1002to &ldquo;text/html&rdquo; using the mime lookup table.</p>10031004<pre><code>// Accept: text/html1005req.accepts('html');1006// =&gt; true10071008// Accept: text/*; application/json1009req.accepts('html');1010req.accepts('text/html');1011req.accepts('text/plain');1012req.accepts('application/json');1013// =&gt; true10141015req.accepts('image/png');1016req.accepts('png');1017// =&gt; false1018</code></pre>10191020<h3 id="req.is()">req.is(type)</h3>10211022<p>Check if the incoming request contains the <em>Content-Type</em>1023header field, and it contains the give mime <em>type</em>.</p>10241025<pre><code> // With Content-Type: text/html; charset=utf-81026 req.is('html');1027 req.is('text/html');1028 // =&gt; true10291030 // When Content-Type is application/json1031 req.is('json');1032 req.is('application/json');1033 // =&gt; true10341035 req.is('html');1036 // =&gt; false1037</code></pre>10381039<p>Ad-hoc callbacks can also be registered with Express, to perform1040assertions again the request, for example if we need an expressive1041way to check if our incoming request is an image, we can register <em>&ldquo;an image&rdquo;</em>1042callback:</p>10431044<pre><code> app.is('an image', function(req){1045 return 0 == req.headers['content-type'].indexOf('image');1046 });1047</code></pre>10481049<p>Now within our route callbacks, we can use to to assert content types1050such as <em>&ldquo;image/jpeg&rdquo;</em>, <em>&ldquo;image/png&rdquo;</em>, etc.</p>10511052<pre><code> app.post('/image/upload', function(req, res, next){1053 if (req.is('an image')) {1054 // do something1055 } else {1056 next();1057 }1058 });1059</code></pre>10601061<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you1062can perform any request assertion you wish.</p>10631064<p>Wildcard matches can also be made, simplifying our example above for <em>&ldquo;an image&rdquo;</em>, by asserting the <em>subtype</em> only:</p>10651066<pre><code>req.is('image/*');1067</code></pre>10681069<p>We may also assert the <em>type</em> as shown below, which would return true for <em>&ldquo;application/json&rdquo;</em>, and <em>&ldquo;text/json&rdquo;</em>.</p>10701071<pre><code>req.is('*/json');1072</code></pre>10731074<h3 id="req.param()">req.param(name[, default])</h3>10751076<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>10771078<ul>1079<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>1080<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1081<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1082</ul>108310841085<p>To utilize urlencoded request bodies, <em>req.body</em>1086should be an object. This can be done by using1087the _express.bodyParser middleware.</p>10881089<h3 id="req.get()">req.get(field, param)</h3>10901091<p> Get <em>field</em>&rsquo;s <em>param</em> value, defaulting to &lsquo;&rsquo; when the <em>param</em>1092 or <em>field</em> is not present.</p>10931094<pre><code> req.get('content-disposition', 'filename');1095 // =&gt; "something.png"10961097 req.get('Content-Type', 'boundary');1098 // =&gt; "--foo-bar-baz"1099</code></pre>11001101<h3 id="req.flash()">req.flash(type[, msg])</h3>11021103<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>11041105<pre><code>req.flash('info', 'email sent');1106req.flash('error', 'email delivery failed');1107req.flash('info', 'email re-sent');1108// =&gt; 211091110req.flash('info');1111// =&gt; ['email sent', 'email re-sent']11121113req.flash('info');1114// =&gt; []11151116req.flash();1117// =&gt; { error: ['email delivery failed'], info: [] }1118</code></pre>11191120<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>11211122<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1123</code></pre>11241125<h3 id="req.isxmlhttprequest">req.isXMLHttpRequest</h3>11261127<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1128to see if it was issued by an <em>XMLHttpRequest</em>:</p>11291130<pre><code>req.xhr1131req.isXMLHttpRequest1132</code></pre>11331134<h3 id="res.header()">res.header(key[, val])</h3>11351136<p>Get or set the response header <em>key</em>.</p>11371138<pre><code>res.header('Content-Length');1139// =&gt; undefined11401141res.header('Content-Length', 123);1142// =&gt; 12311431144res.header('Content-Length');1145// =&gt; 1231146</code></pre>11471148<h3 id="res.charset">res.charset</h3>11491150<p>Sets the charset for subsequent <code>Content-Type</code> header fields. For example <code>res.send()</code> and <code>res.render()</code> default to &ldquo;utf8&rdquo;, so we may explicitly set the charset before rendering a template:</p>11511152<pre><code>res.charset = 'ISO-8859-1';1153res.render('users');1154</code></pre>11551156<p>or before responding with <code>res.send()</code>:</p>11571158<pre><code>res.charset = 'ISO-8859-1';1159res.send(str);1160</code></pre>11611162<p>or with node&rsquo;s <code>res.end()</code>:</p>11631164<pre><code>res.charset = 'ISO-8859-1';1165res.header('Content-Type', 'text/plain');1166res.end(str);1167</code></pre>11681169<h3 id="res.contenttype()">res.contentType(type)</h3>11701171<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>11721173<pre><code> var filename = 'path/to/image.png';1174 res.contentType(filename);1175 // Content-Type is now "image/png"1176</code></pre>11771178<p>A literal <em>Content-Type</em> works as well:</p>11791180<pre><code> res.contentType('application/json');1181</code></pre>11821183<p>Or simply the extension without leading <code>.</code>:</p>11841185<pre><code> res.contentType('json');1186</code></pre>11871188<h3 id="res.attachment()">res.attachment([filename])</h3>11891190<p>Sets the <em>Content-Disposition</em> response header to &ldquo;attachment&rdquo;, with optional <em>filename</em>.</p>11911192<pre><code> res.attachment('path/to/my/image.png');1193</code></pre>11941195<h3 id="res.sendfile()">res.sendfile(path[, options[, callback]])</h3>11961197<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>11981199<pre><code>res.sendfile('path/to/my.file');1200</code></pre>12011202<p>This method accepts an optional callback which is called when1203an error occurs, or when the transfer is complete. By default failures call <code>next(err)</code>, however when a callback is supplied you must do this explicitly, or act on the error.</p>12041205<pre><code>res.sendfile(path, function(err){1206 if (err) {1207 next(err);1208 } else {1209 console.log('transferred %s', path);1210 }1211});1212</code></pre>12131214<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>12151216<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1217 // handle1218});1219</code></pre>12201221<h3 id="res.download()">res.download(file[, filename[, callback[, callback2]]])</h3>12221223<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>12241225<pre><code>res.download('path/to/image.png');1226res.download('path/to/image.png', 'foo.png');1227</code></pre>12281229<p>This is equivalent to:</p>12301231<pre><code>res.attachment(file);1232res.sendfile(file);1233</code></pre>12341235<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>. Within this callback you may still respond, as the header has not been sent.</p>12361237<pre><code>res.download(path, 'expenses.doc', function(err){1238 // handle1239});1240</code></pre>12411242<p>An optional second callback, <em>callback2</em> may be given to allow you to act on connection related errors, however you should not attempt to respond.</p>12431244<pre><code>res.download(path, function(err){1245 // error or finished1246}, function(err){1247 // connection related error1248});1249</code></pre>12501251<h3 id="res.send()">res.send(body|status[, headers|status[, status]])</h3>12521253<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1254objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>12551256<pre><code> res.send(); // 2041257 res.send(new Buffer('wahoo'));1258 res.send({ some: 'json' });1259 res.send('&lt;p&gt;some html&lt;/p&gt;');1260 res.send('Sorry, cant find that', 404);1261 res.send('text', { 'Content-Type': 'text/plain' }, 201);1262 res.send(404);1263</code></pre>12641265<p>By default the <em>Content-Type</em> response header is set, however if explicitly1266assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1267it will not be set again.</p>12681269<p>Note that this method <em>end()</em>s the response, so you will want to use node&rsquo;s <em>res.write()</em> for multiple writes or streaming.</p>12701271<h3 id="res.redirect()">res.redirect(url[, status])</h3>12721273<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>12741275<pre><code>res.redirect('/', 301);1276res.redirect('/account');1277res.redirect('http://google.com');1278res.redirect('home');1279res.redirect('back');1280</code></pre>12811282<p>Express supports &ldquo;redirect mapping&rdquo;, which by default provides <em>home</em>, and <em>back</em>.1283The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1284the &ldquo;home&rdquo; setting and defaults to &ldquo;/&rdquo;.</p>12851286<h3 id="res.cookie()">res.cookie(name, val[, options])</h3>12871288<p>Sets the given cookie <em>name</em> to <em>val</em>, with options <em>httpOnly</em>, <em>secure</em>, <em>expires</em> etc.</p>12891290<pre><code>// "Remember me" for 15 minutes 1291res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1292</code></pre>12931294<p>The <em>maxAge</em> property may be used to set <em>expires</em> relative to <em>Date.now()</em> in milliseconds, so our example above can now become:</p>12951296<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });1297</code></pre>12981299<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieParser</em> middleware, which provides the <em>req.cookies</em> object:</p>13001301<pre><code>app.use(express.cookieParser());13021303app.get('/', function(req, res){1304 // use req.cookies.rememberme1305});1306</code></pre>13071308<h3 id="res.clearcookie()">res.clearCookie(name[, options])</h3>13091310<p>Clear cookie <em>name</em> by setting &ldquo;expires&rdquo; far in the past.</p>13111312<pre><code>res.clearCookie('rememberme');1313</code></pre>13141315<h3 id="res.render()">res.render(view[, options[, fn]])</h3>13161317<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1318When a callback function is given a response will <em>not</em> be made1319automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>13201321<p>The <em>options</em> passed are the local variables as well, for example if we want to expose &ldquo;user&rdquo; to the view, and prevent a local we do so within the same object:</p>13221323<pre><code>var user = { name: 'tj' };1324res.render('index', { layout: false, user: user });1325</code></pre>13261327<h3 id="res.partial()">res.partial(view[, options])</h3>13281329<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1330to the view as a local variable.</p>13311332<ul>1333<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1334<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>13351336<ul>1337<li>as: &lsquo;something&rsquo; will add the <em>something</em> local variable</li>1338<li>as: this will use the collection value as the template context</li>1339<li>as: global will merge the collection value&rsquo;s properties with <em>locals</em></li>1340</ul>1341</li>1342<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1343For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1344</ul>134513461347<p>The following are equivalent, and the name of collection value when passed1348to the partial will be <em>movie</em> as derived from the name.</p>13491350<pre><code>partial('theatre/movie.jade', { collection: movies });1351partial('theatre/movie.jade', movies);1352partial('movie.jade', { collection: movies });1353partial('movie.jade', movies);1354partial('movie', movies);1355// In view: movie.director1356</code></pre>13571358<p>To change the local from <em>movie</em> to <em>video</em> we can use the &ldquo;as&rdquo; option:</p>13591360<pre><code>partial('movie', { collection: movies, as: 'video' });1361// In view: video.director1362</code></pre>13631364<p>Also we can make our movie the value of <em>this</em> within our view so that instead1365of <em>movie.director</em> we could use <em>this.director</em>.</p>13661367<pre><code>partial('movie', { collection: movies, as: this });1368// In view: this.director1369</code></pre>13701371<p>Another alternative is to &ldquo;expand&rdquo; the properties of the collection item into1372pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>13731374<pre><code>partial('movie', { collection: movies, as: global });1375// In view: director1376</code></pre>13771378<p>This same logic applies to a single partial object usage:</p>13791380<pre><code>partial('movie', { object: movie, as: this });1381// In view: this.director13821383partial('movie', { object: movie, as: global });1384// In view: director13851386partial('movie', { object: movie, as: 'video' });1387// In view: video.director13881389partial('movie', { object: movie });1390// In view: movie.director1391</code></pre>13921393<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&rsquo;s local variable name is derived from the view name:</p>13941395<pre><code>var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1396partial('movie', movie)1397// =&gt; In view: movie.director1398</code></pre>13991400<p>The exception of this, is when a &ldquo;plain&rdquo; object, aka &ldquo;{}&rdquo; or &ldquo;new Object&rdquo; is passed, which is considered an object with local variable. For example some may expect a &ldquo;movie&rdquo; local with the following, however since it is a plain object &ldquo;director&rdquo; and &ldquo;title&rdquo; are simply locals:</p>14011402<pre><code>var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1403partial('movie', movie)1404</code></pre>14051406<p>For cases like this where passing a plain object is desired, simply assign it to a key, or use the <code>object</code> key which will use the filename-derived variable name. The examples below are equivalent:</p>14071408<pre><code> partial('movie', { locals: { movie: movie }})1409 partial('movie', { movie: movie })1410 partial('movie', { object: movie })1411</code></pre>14121413<p>This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:</p>14141415<pre><code>app.get('/users', function(req, res){1416 if (req.xhr) {1417 // respond with the each user in the collection1418 // passed to the "user" view1419 res.partial('user', users);1420 } else {1421 // respond with layout, and users page1422 // which internally does partial('user', users)1423 // along with other UI1424 res.render('users', { users: users });1425 }1426});1427</code></pre>14281429<h3 id="res.local()">res.local(name[, val])</h3>14301431<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>14321433<pre><code> app.all('/movie/:id', function(req, res, next){1434 Movie.get(req.params.id, function(err, movie){1435 // Assigns res.locals.movie = movie1436 res.local('movie', movie);1437 });1438 });14391440 app.get('/movie/:id', function(req, res){1441 // movie is already a local, however we1442 // can pass more if we wish1443 res.render('movie', { displayReviews: true });1444 });1445</code></pre>14461447<h3 id="res.locals()">res.locals(obj)</h3>14481449<p> Assign several locals with the given <em>obj</em>. The following are equivalent:</p>14501451<pre><code> res.local('foo', bar);1452 res.local('bar', baz);14531454 res.locals({ foo: bar, bar, baz });1455</code></pre>14561457<h3 id="app.set()">app.set(name[, val])</h3>14581459<p>Apply an application level setting <em>name</em> to <em>val</em>, or1460get the value of <em>name</em> when <em>val</em> is not present:</p>14611462<pre><code>app.set('views', __dirname + '/views');1463app.set('views');1464// =&gt; ...path...1465</code></pre>14661467<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>14681469<pre><code>app.settings.views1470// =&gt; ...path...1471</code></pre>14721473<h3 id="app.enable()">app.enable(name)</h3>14741475<p>Enable the given setting <em>name</em>:</p>14761477<pre><code>app.enable('some arbitrary setting');1478app.set('some arbitrary setting');1479// =&gt; true14801481app.enabled('some arbitrary setting');1482// =&gt; true1483</code></pre>14841485<h3 id="app.enabled()">app.enabled(name)</h3>14861487<p>Check if setting <em>name</em> is enabled:</p>14881489<pre><code>app.enabled('view cache');1490// =&gt; false14911492app.enable('view cache');1493app.enabled('view cache');1494// =&gt; true1495</code></pre>14961497<h3 id="app.disable()">app.disable(name)</h3>14981499<p>Disable the given setting <em>name</em>:</p>15001501<pre><code>app.disable('some setting');1502app.set('some setting');1503// =&gt; false15041505app.disabled('some setting');1506// =&gt; false1507</code></pre>15081509<h3 id="app.disabled()">app.disabled(name)</h3>15101511<p>Check if setting <em>name</em> is disabled:</p>15121513<pre><code>app.enable('view cache');15141515app.disabled('view cache');1516// =&gt; false15171518app.disable('view cache');1519app.disabled('view cache');1520// =&gt; true1521</code></pre>15221523<h3 id="app.configure()">app.configure(env|function[, function])</h3>15241525<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>15261527<pre><code>app.configure(function(){1528 // executed for each env1529});15301531app.configure('development', function(){1532 // executed for 'development' only1533});1534</code></pre>15351536<h3 id="app.redirect()">app.redirect(name, val)</h3>15371538<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>15391540<pre><code>app.redirect('google', 'http://google.com');1541</code></pre>15421543<p>Now in a route we may call:</p>15441545<p> res.redirect(&lsquo;google&rsquo;);</p>15461547<p>We may also map dynamic redirects:</p>15481549<pre><code>app.redirect('comments', function(req, res){1550 return '/post/' + req.params.id + '/comments';1551});1552</code></pre>15531554<p>So now we may do the following, and the redirect will dynamically adjust to1555the context of the request. If we called this route with <em>GET /post/12</em> our1556redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>15571558<pre><code>app.get('/post/:id', function(req, res){1559 res.redirect('comments');1560});1561</code></pre>15621563<p>When mounted, <em>res.redirect()</em> will respect the mount-point. For example if a blog app is mounted at <em>/blog</em>, the following will redirect to <em>/blog/posts</em>:</p>15641565<pre><code>res.redirect('/posts');1566</code></pre>15671568<h3 id="app.error()">app.error(function)</h3>15691570<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1571Note that we may set several error handlers by making several calls to this method, however the handler1572should call <em>next(err)</em> if it does not wish to deal with the exception:</p>15731574<pre><code>app.error(function(err, req, res, next){1575 res.send(err.message, 500);1576});1577</code></pre>15781579<h3 id="app.helpers()">app.helpers(obj)</h3>15801581<p>Registers static view helpers.</p>15821583<pre><code>app.helpers({1584 name: function(first, last){ return first + ', ' + last }1585 , firstName: 'tj'1586 , lastName: 'holowaychuk'1587});1588</code></pre>15891590<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1591as well as the <em>name()</em> function exposed.</p>15921593<pre><code>&lt;%= name(firstName, lastName) %&gt;1594</code></pre>15951596<p>Express also provides a few locals by default:</p>15971598<pre><code>- `settings` the app's settings object1599- `filename` the view's filename1600- `layout(path)` specify the layout from within a view1601</code></pre>16021603<p>This method is aliased as <em>app.locals()</em>.</p>16041605<h3 id="app.dynamichelpers()">app.dynamicHelpers(obj)</h3>16061607<p>Registers dynamic view helpers. Dynamic view helpers1608are simply functions which accept <em>req</em>, <em>res</em>, and are1609evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1610becomes the local variable it is associated with.</p>16111612<pre><code>app.dynamicHelpers({1613 session: function(req, res){1614 return req.session;1615 }1616});1617</code></pre>16181619<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>16201621<pre><code>&lt;%= session.name %&gt;1622</code></pre>16231624<h3 id="app.lookup">app.lookup</h3>16251626<p> The <em>app.lookup</em> http methods returns an array of callback functions1627 associated with the given <em>path</em>.</p>16281629<p> Suppose we define the following routes:</p>16301631<pre><code> app.get('/user/:id', function(){});1632 app.put('/user/:id', function(){});1633 app.get('/user/:id/:op?', function(){});1634</code></pre>16351636<p> We can utilize this lookup functionality to check which routes1637 have been defined, which can be extremely useful for higher level1638 frameworks built on Express.</p>16391640<pre><code> app.lookup.get('/user/:id');1641 // =&gt; [Function]16421643 app.lookup.get('/user/:id/:op?');1644 // =&gt; [Function]16451646 app.lookup.put('/user/:id');1647 // =&gt; [Function]16481649 app.lookup.all('/user/:id');1650 // =&gt; [Function, Function]16511652 app.lookup.all('/hey');1653 // =&gt; []1654</code></pre>16551656<p> To alias <em>app.lookup.VERB()</em>, we can simply invoke <em>app.VERB()</em>1657 without a callback, as a shortcut, for example the following are1658 equivalent:</p>16591660<pre><code> app.lookup.get('/user');1661 app.get('/user');1662</code></pre>16631664<p> Each function returned has the following properties:</p>16651666<pre><code> var fn = app.get('/user/:id/:op?')[0];16671668 fn.regexp1669 // =&gt; /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i16701671 fn.keys1672 // =&gt; ['id', 'op']16731674 fn.path1675 // =&gt; '/user/:id/:op?'16761677 fn.method1678 // =&gt; 'GET'1679</code></pre>16801681<h3 id="app.match">app.match</h3>16821683<p> The <em>app.match</em> http methods return an array of callback functions1684 which match the given <em>url</em>, which may include a query string etc. This1685 is useful when you want reflect on which routes have the opportunity to1686 respond.</p>16871688<p> Suppose we define the following routes:</p>16891690<pre><code> app.get('/user/:id', function(){});1691 app.put('/user/:id', function(){});1692 app.get('/user/:id/:op?', function(){});1693</code></pre>16941695<p> Our match against <strong>GET</strong> will return two functions, since the <em>:op</em>1696 in our second route is optional.</p>16971698<pre><code> app.match.get('/user/1');1699 // =&gt; [Function, Function]1700</code></pre>17011702<p> This second call returns only the callback for <em>/user/:id/:op?</em>.</p>17031704<pre><code> app.match.get('/user/23/edit');1705 // =&gt; [Function]1706</code></pre>17071708<p> We can also use <em>all()</em> to disregard the http method:</p>17091710<pre><code> app.match.all('/user/20');1711 // =&gt; [Function, Function, Function]1712</code></pre>17131714<p> Each function matched has the following properties:</p>17151716<pre><code> var fn = app.match.get('/user/23/edit')[0];17171718 fn.keys1719 // =&gt; ['id', 'op']17201721 fn.params1722 // =&gt; { id: '23', op: 'edit' }17231724 fn.method1725 // =&gt; 'GET'1726</code></pre>17271728<h3 id="app.mounted()">app.mounted(fn)</h3>17291730<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>17311732<pre><code>var app = express.createServer(),1733 blog = express.createServer();17341735blog.mounted(function(parent){1736 // parent is app1737 // "this" is blog1738});17391740app.use(blog);1741</code></pre>17421743<h3 id="app.register()">app.register(ext, exports)</h3>17441745<p>Register the given template engine <em>exports</em>1746as <em>ext</em>. For example we may wish to map &ldquo;.html&rdquo;1747files to jade:</p>17481749<pre><code> app.register('.html', require('jade'));1750</code></pre>17511752<p>This is also useful for libraries that may not1753match extensions correctly. For example my haml.js1754library is installed from npm as &ldquo;hamljs&rdquo; so instead1755of layout.hamljs, we can register the engine as &ldquo;.haml&rdquo;:</p>17561757<pre><code> app.register('.haml', require('haml-js'));1758</code></pre>17591760<p>For engines that do not comply with the Express1761specification, we can also wrap their api this way. Below1762we map <em>.md</em> to render markdown files, rendering the html once1763since it will not change on subsequent calls, and support local substitution1764in the form of &ldquo;{name}&rdquo;.</p>17651766<pre><code> app.register('.md', {1767 compile: function(str, options){1768 var html = md.toHTML(str);1769 return function(locals){1770 return html.replace(/\{([^}]+)\}/g, function(_, name){1771 return locals[name];1772 });1773 };1774 }1775 });1776</code></pre>17771778<h3 id="app.listen()">app.listen([port[, host]])</h3>17791780<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1781connections will be accepted via <em>INADDR_ANY</em>.</p>17821783<pre><code>app.listen();1784app.listen(3000);1785app.listen(3000, 'n.n.n.n');1786</code></pre>17871788<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>17891790<pre><code>app.listen('/tmp/express.sock');1791</code></pre>17921793<p>Then try it out:</p>17941795<pre><code>$ telnet /tmp/express.sock1796GET / HTTP/1.117971798HTTP/1.1 200 OK1799Content-Type: text/plain1800Content-Length: 1118011802Hello World1803</code></pre>1804 </div>1805 </div>1806 </body>1807</html>