guide.html
This file
Path
docs/guide.html
1,487 lines · 51.2 KiB · HTML
Last changed by
docsTj Holowaychukbefore adoption9d1b3f5
History of this fileTake it
The walk stopped after 200 commits: lines older than f5af66a point at it.
fixed github exampleTj Holowaychukbefore adoptionf5af66a
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;fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 137–182why, 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>docsTj Holowaychukbefore adoption14bd50e
lines 183–184why, one step back183<li><a href="#Creating-A-Server">Creating A Server</a></li>184<li><a href="#Creating-An-HTTPS-Server">Creating An HTTPS Server</a></li>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 185–192why, one step back185<li><a href="#Configuration">Configuration</a></li>186<li><a href="#Settings">Settings</a></li>187<li><a href="#Routing">Routing</a></li>188<li><a href="#Passing-Route-Control">Passing Route Control</a></li>189<li><a href="#Middleware">Middleware</a></li>190<li><a href="#Route-Middleware">Route Middleware</a></li>191<li><a href="#HTTP-Methods">HTTP Methods</a></li>192<li><a href="#Error-Handling">Error Handling</a></li>docsTj Holowaychukbefore adoption9d1b3f5
line 193why, one step back193<li><a href="#Route-Param-Pre-conditions">Route Param Pre-conditions</a></li>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 194–202why, one step back194<li><a href="#View-Rendering">View Rendering</a></li>195<li><a href="#View-Partials">View Partials</a></li>196<li><a href="#Template-Engines">Template Engines</a></li>197<li><a href="#Session-Support">Session Support</a></li>198<li><a href="#Migration-Guide">Migration Guide</a></li>199<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">200<li><a href="#req-header-key-defaultValue-">header()</a></li>201<li><a href="#req-accepts-type-">accepts()</a></li>202<li><a href="#req-is-type-">is()</a></li>docsTj Holowaychukbefore adoption50006f7
line 203why, one step back203<li><a href="#req-param-name-default-">param()</a></li>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 204–218why, one step back204<li><a href="#req-flash-type-msg-">flash()</a></li>205<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>206</ul></li>207<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">208<li><a href="#res-header-key-val-">header()</a></li>209<li><a href="#res-contentType-type-">contentType()</a></li>210<li><a href="#res-attachment-filename-">attachment()</a></li>211<li><a href="#res-sendfile-path-">sendfile()</a></li>212<li><a href="#res-download-file-filename-">download()</a></li>213<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>214<li><a href="#res-redirect-url-status-">redirect()</a></li>215<li><a href="#res-cookie-name-val-options-">cookie()</a></li>216<li><a href="#res-clearCookie-name-">clearCookie()</a></li>217<li><a href="#res-render-view-options-fn-">render()</a></li>218<li><a href="#res-partial-view-options-">partial()</a></li>Re-built docsTj Holowaychukbefore adoption8e63d04
line 219why, one step back219<li><a href="#res-local-name-val-">local()</a></li>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 220–242why, one step back220</ul></li>221<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">222<li><a href="#app-set-name-val-">set()</a></li>223<li><a href="#app-enable-name-">enable()</a></li>224<li><a href="#app-disable-name-">disable()</a></li>225<li><a href="#app-configure-env-function-function-">configure()</a></li>226<li><a href="#app-redirect-name-val-">redirect()</a></li>227<li><a href="#app-error-function-">error()</a></li>228<li><a href="#app-helpers-obj-">helpers()</a></li>229<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>230<li><a href="#app-mounted-fn-">mounted()</a></li>231<li><a href="#app-register-ext-exports-">register()</a></li>232<li><a href="#app-listen-port-host-">listen()</a></li>233</ul></li>234</ul>235 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 236 <p id="tagline">237 High performance, high class web development for238 <a href="http://nodejs.org">Node.js</a>239 </p>240 <ul id="menu">241 <li><a href="index.html">Home</a></li>242 <li><a href="guide.html">Guide</a></li>Added screencasts pageTj Holowaychukbefore adoption4144af3
line 243why, one step back243 <li><a href="screencasts.html">Screencasts</a></li>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 244–255why, one step back244 <li><a href="applications.html">Applications</a></li>245 </ul>246<div class='mp'>247<h2 id="Express">Express</h2>248<p class="man-name">249 <code>guide</code>250</p>251<h3 id="Installation">Installation</h3>252253<pre><code>$ npm install express254</code></pre>255docsTj Holowaychukbefore adoption14bd50e
line 256why, one step back256<h3 id="Creating-A-Server">Creating A Server</h3>fixed github exampleTj Holowaychukbefore adoptionf5af66a
line 257why, one step back257docsTj Holowaychukbefore adoption14bd50e
line 258why, one step back258<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>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 259–262why, one step back259260<pre><code>var app = require('express').createServer();261262app.get('/', function(req, res){docsTj Holowaychukbefore adoption50006f7
line 263why, one step back263 res.send('hello world');fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 264–268why, one step back264});265266app.listen(3000);267</code></pre>268docsTj Holowaychukbefore adoption14bd50e
lines 269–276why, one step back269<h3 id="Creating-An-HTTPS-Server">Creating An HTTPS Server</h3>270271<p> To initialize a <em>express.HTTPSServer</em> we do the same as above, however we272 pass an options object, accepting <em>key</em>, <em>cert</em> and the others mentioned in node's <a href="http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer">https documentation</a>.</p>273274<pre><code> var app = require('express').createServer({ key: ... });275</code></pre>276fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 277–284why, one step back277<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 tracesdocsTj Holowaychukbefore adoption14bd50e
line 285why, one step back285in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.fixed github exampleTj Holowaychukbefore adoptionf5af66a
line 286why, one step back286Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,docsTj Holowaychukbefore adoption14bd50e
line 287why, one step back287otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 288–290why, one step back288289<pre><code>app.configure(function(){290 app.use(express.methodOverride());docsTj Holowaychukbefore adoption14bd50e
line 291why, one step back291 app.use(express.bodyParser());fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 292–295why, one step back292 app.use(app.router);293});294295app.configure('development', function(){docsTj Holowaychukbefore adoption14bd50e
line 296why, one step back296 app.use(express.static(__dirname + '/public'));fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 297–300why, one step back297 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));298});299300app.configure('production', function(){docsTj Holowaychukbefore adoption50006f7
line 301why, one step back301 var oneYear = 31557600000;docsTj Holowaychukbefore adoption14bd50e
lines 302–303why, one step back302 app.use(express.static({ root: __dirname + '/public', maxAge: oneYear }));303 app.use(express.errorHandler());fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 304–308why, one step back304});305</code></pre>306307<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>308docsTj Holowaychukbefore adoption14bd50e
line 309why, one step back309<pre><code> app.configure(function(){fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 310–311why, one step back310 app.set('views', __dirname + '/views');311 app.set('views');docsTj Holowaychukbefore adoption14bd50e
line 312why, one step back312 // => "/absolute/path/to/views"fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 313–318why, one step back313314 app.enable('some feature');315 // same as app.set('some feature', true);316317 app.disable('some feature');318 // same as app.set('some feature', false);docsTj Holowaychukbefore adoption14bd50e
lines 319–322why, one step back319320 app.enabled('some feature')321 // => false322 });fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 323–362why, one step back323</code></pre>324325<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>326327<pre><code>$ NODE_ENV=production node app.js328</code></pre>329330<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>331332<h3 id="Settings">Settings</h3>333334<p>Express supports the following settings out of the box:</p>335336<ul>337<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>338<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>339<li><em>view engine</em> Default view engine name for views rendered without extensions</li>340<li><em>view options</em> An object specifying global view options</li>341</ul>342343344<h3 id="Routing">Routing</h3>345346<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.347For example we may want to render a user's account for the path <em>/user/12</em>, this348can be done by defining the route below. The values associated to the named placeholders349are available as <code>req.params</code>.</p>350351<pre><code>app.get('/user/:id', function(req, res){352 res.send('user ' + req.params.id);353});354</code></pre>355356<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example357when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>358359<pre><code>\/user\/([^\/]+)\/?360</code></pre>361362<p>Regular expression literals may also be passed for complex uses. Since captureRegenerated docsTj Holowaychukbefore adoptiond3abcaf
line 363why, one step back363groups 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>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 364–411why, one step back364365<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){366 res.send(req.params);367});368</code></pre>369370<p>Curl requests against the previously defined route:</p>371372<pre><code> $ curl http://dev:3000/user373 [null,null]374 $ curl http://dev:3000/users375 [null,null]376 $ curl http://dev:3000/users/1377 ["1",null]378 $ curl http://dev:3000/users/1..15379 ["1","15"]380</code></pre>381382<p>Below are some route examples, and the associated paths that they383may consume:</p>384385<pre><code> "/user/:id"386 /user/12387388 "/users/:id?"389 /users/5390 /users391392 "/files/*"393 /files/jquery.js394 /files/javascripts/jquery.js395396 "/file/*.*"397 /files/jquery.js398 /files/javascripts/jquery.js399400 "/user/:id/:operation?"401 /user/1402 /user/1/edit403404 "/products.:format"405 /products.json406 /products.xml407408 "/products.:format?"409 /products.json410 /products.xml411 /productsRegenerated docsTj Holowaychukbefore adoptiond3abcaf
lines 412–415why, one step back412413 "/user/:id.:format?"414 /user/12415 /user/12.jsonfixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 416–417why, one step back416</code></pre>417docsTj Holowaychukbefore adoption14bd50e
line 418why, one step back418<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>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 419–422why, one step back419420<pre><code>var express = require('express')421 , app = express.createServer();422docsTj Holowaychukbefore adoption14bd50e
line 423why, one step back423app.use(express.bodyParser());fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 424–430why, one step back424425app.post('/', function(req, res){426 res.send(req.body);427});428429app.listen(3000);430</code></pre>Regenerated docsTj Holowaychukbefore adoptiond3abcaf
line 431why, one step back431docsTj Holowaychukbefore adoption14bd50e
line 432why, one step back432<p>Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use <em>'/user/:id(\d+)'</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 433–437why, one step back433434<h3 id="Passing-Route-Control">Passing Route Control</h3>435436<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,437the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,docsTj Holowaychukbefore adoption14bd50e
line 438why, one step back438and 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>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 439–453why, one step back439440<pre><code>app.get('/users/:id?', function(req, res, next){441 var id = req.params.id;442 if (id) {443 // do something444 } else {445 next();446 }447});448449app.get('/users', function(req, res){450 // do something else451});452</code></pre>453docsTj Holowaychukbefore adoption14bd50e
line 454why, one step back454<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>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 455–496why, one step back455456<pre><code>var express = require('express')457 , app = express.createServer();458459var users = [{ name: 'tj' }];460461app.all('/user/:id/:op?', function(req, res, next){462 req.user = users[req.params.id];463 if (req.user) {464 next();465 } else {466 next(new Error('cannot find user ' + req.params.id));467 }468});469470app.get('/user/:id', function(req, res){471 res.send('viewing ' + req.user.name);472});473474app.get('/user/:id/edit', function(req, res){475 res.send('editing ' + req.user.name);476});477478app.put('/user/:id', function(req, res){479 res.send('updating ' + req.user.name);480});481482app.get('*', function(req, res){483 res.send('what???', 404);484});485486app.listen(3000); 487</code></pre>488489<h3 id="Middleware">Middleware</h3>490491<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be492passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>493494<pre><code> var express = require('express');495496var app = express.createServer(docsTj Holowaychukbefore adoption14bd50e
lines 497–498why, one step back497 express.logger()498 , express.bodyParser()fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 499–501why, one step back499 );500</code></pre>501docsTj Holowaychukbefore adoption14bd50e
line 502why, one step back502<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 503–510why, one step back503504<pre><code>app.use(express.logger({ format: ':method :uri' }));505</code></pre>506507<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>508509<pre><code>var connect = require('connect');510app.use(connect.logger());docsTj Holowaychukbefore adoption9d1b3f5
line 511why, one step back511app.use(connect.bodyParser());fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 512–516why, one step back512</code></pre>513514<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>515516<pre><code>app.use(express.logger());docsTj Holowaychukbefore adoption9d1b3f5
line 517why, one step back517app.use(express.bodyParser());fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 518–526why, one step back518</code></pre>519520<h3 id="Route-Middleware">Route Middleware</h3>521522<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>523524<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>525526<pre><code>app.get('/user/:id', function(req, res, next){docsTj Holowaychukbefore adoption9d1b3f5
lines 527–530why, one step back527 loadUser(req.params.id, function(err, user){528 if (err) return next(err);529 res.send('Viewing user ' + user.name);530 });fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 531–536why, one step back531});532</code></pre>533534<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>535536<pre><code>function loadUser(req, res, next) {docsTj Holowaychukbefore adoption9d1b3f5
lines 537–544why, one step back537 // You would fetch your user from the db538 var user = users[req.params.id];539 if (user) {540 req.user = user;541 next();542 } else {543 next(new Error('Failed to load user ' + req.params.id));544 }fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 545–547why, one step back545}546547app.get('/user/:id', loadUser, function(req, res){docsTj Holowaychukbefore adoption9d1b3f5
line 548why, one step back548 res.send('Viewing user ' + req.user.name);fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 549–554why, one step back549});550</code></pre>551552<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>553554<pre><code>function andRestrictToSelf(req, res, next) {docsTj Holowaychukbefore adoption9d1b3f5
lines 555–557why, one step back555 req.authenticatedUser.id == req.user.id556 ? next()557 : next(new Error('Unauthorized'));fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 558–560why, one step back558}559560app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){docsTj Holowaychukbefore adoption9d1b3f5
line 561why, one step back561 res.send('Editing user ' + req.user.name);fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 562–567why, one step back562});563</code></pre>564565<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>566567<pre><code>function andRestrictTo(role) {docsTj Holowaychukbefore adoption9d1b3f5
lines 568–572why, one step back568 return function(req, res, next) {569 req.authenticatedUser.role == role570 ? next()571 : next(new Error('Unauthorized'));572 }fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 573–575why, one step back573}574575app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){docsTj Holowaychukbefore adoption9d1b3f5
line 576why, one step back576 res.send('Deleted user ' + req.user.name);fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 577–608why, one step back577});578</code></pre>579580<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>581582<pre><code>var a = [middleware1, middleware2]583 , b = [middleware3, middleware4]584 , all = [a, b];585586app.get('/foo', a, function(){});587app.get('/bar', a, function(){});588589app.get('/', a, middleware3, middleware4, function(){});590app.get('/', a, b, function(){});591app.get('/', all, function(){});592</code></pre>593594<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>595596<h3 id="HTTP-Methods">HTTP Methods</h3>597598<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>599600<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>601602<pre><code> <form method="post" action="/">603 <input type="text" name="user[name]" />604 <input type="text" name="user[email]" />605 <input type="submit" value="Submit" />606 </form>607</code></pre>608docsTj Holowaychukbefore adoption9d1b3f5
line 609why, one step back609<p>By default Express does not know what to do with this request body, so we should add the <em>bodyParser</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> and <em>application/json</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
line 610why, one step back610docsTj Holowaychukbefore adoption9d1b3f5
line 611why, one step back611<pre><code>app.use(express.bodyParser());fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 612–616why, one step back612</code></pre>613614<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>615616<pre><code>app.post('/', function(req, res){docsTj Holowaychukbefore adoption9d1b3f5
lines 617–618why, one step back617 console.log(req.body.user);618 res.redirect('back');fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 619–621why, one step back619});620</code></pre>621docsTj Holowaychukbefore adoption9d1b3f5
line 622why, one step back622<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyParser</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
line 623why, one step back623docsTj Holowaychukbefore adoption9d1b3f5
line 624why, one step back624<pre><code>app.use(express.bodyParser());fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 625–649why, one step back625app.use(express.methodOverride());626</code></pre>627628<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>629630<pre><code><form method="post" action="/">631 <input type="hidden" name="_method" value="put" />632 <input type="text" name="user[name]" />633 <input type="text" name="user[email]" />634 <input type="submit" value="Submit" /> 635</form>636637app.put('/', function(){638 console.log(req.body.user);639 res.redirect('back');640});641</code></pre>642643<h3 id="Error-Handling">Error Handling</h3>644645<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,646or passed to <em>next(err)</em>. Below is an example which serves different pages based on our647ad-hoc <em>NotFound</em> exception:</p>648649<pre><code>function NotFound(msg){docsTj Holowaychukbefore adoption9d1b3f5
lines 650–652why, one step back650 this.name = 'NotFound';651 Error.call(this, msg);652 Error.captureStackTrace(this, arguments.callee);fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 653–654why, one step back653}654docsTj Holowaychukbefore adoption9d1b3f5
line 655why, one step back655NotFound.protoype.__proto__ = Error.prototype;fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 656–657why, one step back656657app.get('/404', function(req, res){docsTj Holowaychukbefore adoption9d1b3f5
line 658why, one step back658 throw new NotFound;fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 659–661why, one step back659});660661app.get('/500', function(req, res){docsTj Holowaychukbefore adoption9d1b3f5
line 662why, one step back662 throw new Error('keyboard cat!');fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 663–684why, one step back663});664</code></pre>665666<p>We can call <em>app.error()</em> several times as shown below.667Here we check for an instanceof <em>NotFound</em> and show the668404 page, or we pass on to the next error handler.</p>669670<p>Note that these handlers can be defined anywhere, as they671will be placed below the route handlers on <em>listen()</em>. This672allows for definition within <em>configure()</em> blocks so we can673handle exceptions in different ways based on the environment.</p>674675<pre><code>app.error(function(err, req, res, next){676 if (err instanceof NotFound) {677 res.render('404.jade');678 } else {679 next(err);680 }681});682</code></pre>683684<p>Here we assume all errors as 500 for the simplicity ofdocsTj Holowaychukbefore adoption9d1b3f5
line 685why, one step back685this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the <em>error.code</em> of <em>ENOENT</em>, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 686–687why, one step back686687<pre><code>app.error(function(err, req, res){docsTj Holowaychukbefore adoption9d1b3f5
lines 688–690why, one step back688 res.render('500.jade', {689 error: err690 });fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 691–708why, one step back691});692</code></pre>693694<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware695to report on exceptions. For example if we wish to output exceptions696in "development" mode to <em>stderr</em> we can use:</p>697698<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));699</code></pre>700701<p>Also during development we may want fancy html pages to show exceptions702that are passed or thrown, so we can set <em>showStack</em> to true:</p>703704<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));705</code></pre>706707<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>708is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
line 709why, one step back709docsTj Holowaychukbefore adoption9d1b3f5
line 710why, one step back710<h3 id="Route-Param-Pre-conditions">Route Param Pre-conditions</h3>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
line 711why, one step back711docsTj Holowaychukbefore adoption9d1b3f5
line 712why, one step back712<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>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
lines 713–721why, one step back713714<pre><code>app.get('/user/:userId', function(req, res, next){715 User.get(req.params.userId, function(err, user){716 if (err) return next(err);717 res.send('user ' + user.name);718 });719}); 720</code></pre>721docsTj Holowaychukbefore adoption9d1b3f5
line 722why, one step back722<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>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
lines 723–749why, one step back723724<pre><code>app.param('userId', function(req, res, next, id){725 User.get(id, function(err, user){726 if (err) return next(err);727 if (!user) return next(new Error('failed to find user'));728 req.user = user;729 next();730 });731});732</code></pre>733734<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>735736<pre><code>app.get('/user/:userId', function(req, res){737 res.send('user ' + req.user.name);738});739</code></pre>740741<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>742743<pre><code>app.param('number', function(n){ return parseInt(n, 10); });744</code></pre>745746<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>747748<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });749</code></pre>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 750–752why, one step back750751<h3 id="View-Rendering">View Rendering</h3>752docsTj Holowaychukbefore adoption9d1b3f5
line 753why, one step back753<p>View filenames take the form "<name>.<engine>", where <engine> is the namefixed github exampleTj Holowaychukbefore adoptionf5af66a
line 754why, one step back754of the module that will be required. For example the view <em>layout.ejs</em> willdocsTj Holowaychukbefore adoption9d1b3f5
lines 755–756why, one step back755tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.compile(str, options)</em>, and return a <em>Function</em> to comply with Express. To alter this behaviour756<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
line 757why, one step back757docsTj Holowaychukbefore adoption9d1b3f5
lines 758–760why, one step back758<p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,759and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as760the <em>body</em> local variable in <em>layout.jade</em>.</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 761–762why, one step back761762<pre><code>app.get('/', function(req, res){docsTj Holowaychukbefore adoption9d1b3f5
line 763why, one step back763 res.render('index.jade', { title: 'My Site' });fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 764–767why, one step back764});765</code></pre>766767<p>The new <em>view engine</em> setting allows us to specify our default template engine,docsTj Holowaychukbefore adoption9d1b3f5
line 768why, one step back768so for example when using jade we could set:</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 769–791why, one step back769770<pre><code>app.set('view engine', 'jade');771</code></pre>772773<p>Allowing us to render with:</p>774775<pre><code>res.render('index');776</code></pre>777778<p>vs:</p>779780<pre><code>res.render('index.jade');781</code></pre>782783<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still784mix and match template engines:</p>785786<pre><code>res.render('another-page.ejs');787</code></pre>788789<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>790791<pre><code>app.set('view options', {docsTj Holowaychukbefore adoption9d1b3f5
line 792why, one step back792 layout: falsefixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 793–795why, one step back793});794</code></pre>795docsTj Holowaychukbefore adoption9d1b3f5
line 796why, one step back796<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 797–857why, one step back797798<pre><code>res.render('myview.ejs', { layout: true });799</code></pre>800801<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>802803<pre><code>res.render('page', { layout: 'mylayout' });804</code></pre>805806<p>Otherwise we must specify the extension:</p>807808<pre><code>res.render('page', { layout: 'mylayout.jade' });809</code></pre>810811<p>These paths may also be absolute:</p>812813<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });814</code></pre>815816<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>817818<pre><code>app.set('view options', {819 open: '{{',820 close: '}}'821});822</code></pre>823824<h3 id="View-Partials">View Partials</h3>825826<p>The Express view system has built-in support for partials and collections, which are827sort of "mini" views representing a document fragment. For example rather than iterating828in a view to display comments, we would use a partial with collection support:</p>829830<pre><code>partial('comment.haml', { collection: comments });831</code></pre>832833<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,834however if we wished we could use an ejs partial, within a haml view for example.</p>835836<pre><code>partial('comment', { collection: comments });837</code></pre>838839<p>And once again even further, when rendering a collection we can simply pass840an array, if no other options are desired:</p>841842<pre><code>partial('comment', comments);843</code></pre>844845<p>When using the partial collection support a few "magic" variables are provided846for free:</p>847848<ul>849<li><em>firstInCollection</em> True if this is the first object</li>850<li><em>indexInCollection</em> Index of the object in the collection</li>851<li><em>lastInCollection</em> True if this is the last object</li>852<li><em>collectionLength</em> Length of the collection</li>853</ul>854855856<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>857Added screencasts pageTj Holowaychukbefore adoption4144af3
lines 858–859why, one step back858<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>859fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 860–1007why, one step back860<h3 id="Template-Engines">Template Engines</h3>861862<p>Below are a few template engines commonly used with Express:</p>863864<ul>865<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>866<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>867<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>868<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>869<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>870</ul>871872873<h3 id="Session-Support">Session Support</h3>874875<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>876877<pre><code>app.use(express.cookieDecoder());878app.use(express.session());879</code></pre>880881<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>882883<pre><code>var RedisStore = require('connect-redis');884app.use(express.cookieDecoder());885app.use(express.session({ store: new RedisStore }));886</code></pre>887888<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>889890<pre><code>var RedisStore = require('connect-redis');891app.use(express.bodyDecoder());892app.use(express.cookieDecoder());893app.use(express.session({ store: new RedisStore }));894895app.post('/add-to-cart', function(req, res){896 // Perhaps we posted several items with a form897 // (use the bodyDecoder() middleware for this)898 var items = req.body.items;899 req.session.items = items;900 res.redirect('back');901});902903app.get('/add-to-cart', function(req, res){904 // When redirected back to GET /add-to-cart905 // we could check req.session.items && req.session.items.length906 // to print out a message907 if (req.session.items && req.session.items.length) {908 req.flash('info', 'You have %s items in your cart', req.session.items.length);909 }910 res.render('shopping-cart');911});912</code></pre>913914<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>915916<h3 id="Migration-Guide">Migration Guide</h3>917918<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>919920<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>921922<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>923924<pre><code>req.header('Host');925req.header('host');926req.header('Accept', '*/*');927</code></pre>928929<h3 id="req-accepts-type-">req.accepts(type)</h3>930931<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>932933<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise934the given <em>type</em> is matched by an exact match, and then subtypes. You935may pass the subtype such as "html" which is then converted internally936to "text/html" using the mime lookup table.</p>937938<pre><code>// Accept: text/html939req.accepts('html');940// => true941942// Accept: text/*; application/json943req.accepts('html');944req.accepts('text/html');945req.accepts('text/plain');946req.accepts('application/json');947// => true948949req.accepts('image/png');950req.accepts('png');951// => false952</code></pre>953954<h3 id="req-is-type-">req.is(type)</h3>955956<p>Check if the incoming request contains the <em>Content-Type</em>957header field, and it contains the give mime <em>type</em>.</p>958959<pre><code> // With Content-Type: text/html; charset=utf-8960 req.is('html');961 req.is('text/html');962 // => true963964 // When Content-Type is application/json965 req.is('json');966 req.is('application/json');967 // => true968969 req.is('html');970 // => false971</code></pre>972973<p>Ad-hoc callbacks can also be registered with Express, to perform974assertions again the request, for example if we need an expressive975way to check if our incoming request is an image, we can register <em>"an image"</em>976callback:</p>977978<pre><code> app.is('an image', function(req){979 return 0 == req.headers['content-type'].indexOf('image');980 });981</code></pre>982983<p>Now within our route callbacks, we can use to to assert content types984such as <em>"image/jpeg"</em>, <em>"image/png"</em>, etc.</p>985986<pre><code> app.post('/image/upload', function(req, res, next){987 if (req.is('an image')) {988 // do something989 } else {990 next();991 }992 });993</code></pre>994995<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you996can perform any request assertion you wish.</p>997998<p>Wildcard matches can also be made, simplifying our example above for <em>"an image"</em>, by asserting the <em>subtype</em> only:</p>9991000<pre><code>req.is('image/*');1001</code></pre>10021003<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>10041005<pre><code>req.is('*/json');1006</code></pre>1007docsTj Holowaychukbefore adoption50006f7
line 1008why, one step back1008<h3 id="req-param-name-default-">req.param(name[, default])</h3>fixed github exampleTj Holowaychukbefore adoptionf5af66a
line 1009why, one step back1009docsTj Holowaychukbefore adoption50006f7
line 1010why, one step back1010<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 1011–1135why, one step back10111012<ul>1013<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>1014<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1015<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1016</ul>101710181019<p>To utilize urlencoded request bodies, <em>req.body</em>1020should be an object. This can be done by using1021the <em>express.bodyDecoder</em> middleware.</p>10221023<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>10241025<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>10261027<pre><code>req.flash('info', 'email sent');1028req.flash('error', 'email delivery failed');1029req.flash('info', 'email re-sent');1030// => 210311032req.flash('info');1033// => ['email sent', 'email re-sent']10341035req.flash('info');1036// => []10371038req.flash();1039// => { error: ['email delivery failed'], info: [] }1040</code></pre>10411042<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>10431044<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1045</code></pre>10461047<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>10481049<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1050to see if it was issued by an <em>XMLHttpRequest</em>:</p>10511052<pre><code>req.xhr1053req.isXMLHttpRequest1054</code></pre>10551056<h3 id="res-header-key-val-">res.header(key[, val])</h3>10571058<p>Get or set the response header <em>key</em>.</p>10591060<pre><code>res.header('Content-Length');1061// => undefined10621063res.header('Content-Length', 123);1064// => 12310651066res.header('Content-Length');1067// => 1231068</code></pre>10691070<h3 id="res-contentType-type-">res.contentType(type)</h3>10711072<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>10731074<pre><code> var filename = 'path/to/image.png';1075 res.contentType(filename);1076 // res.headers['Content-Type'] is now "image/png"1077</code></pre>10781079<h3 id="res-attachment-filename-">res.attachment([filename])</h3>10801081<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>10821083<pre><code> res.attachment('path/to/my/image.png');1084</code></pre>10851086<h3 id="res-sendfile-path-">res.sendfile(path)</h3>10871088<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>10891090<pre><code>res.sendfile('path/to/my.file');1091</code></pre>10921093<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>10941095<pre><code>res.sendfile(path, function(err, path){1096 if (err) {1097 // handle the error1098 } else {1099 console.log('transferred %s', path);1100 }1101});1102</code></pre>11031104<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>11051106<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>11071108<pre><code>res.download('path/to/image.png');1109res.download('path/to/image.png', 'foo.png');1110</code></pre>11111112<p>This is equivalent to:</p>11131114<pre><code>res.attachment(file);1115res.sendfile(file);1116</code></pre>11171118<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>11191120<p>The <code>res.send()</code> method is a high level response utility allowing you to pass1121objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status1122code based responses. The following are all valid uses:</p>11231124<pre><code> res.send(); // 2041125 res.send(new Buffer('wahoo'));1126 res.send({ some: 'json' });1127 res.send('<p>some html</p>');1128 res.send('Sorry, cant find that', 404);1129 res.send('text', { 'Content-Type': 'text/plain' }, 201);1130 res.send(404);1131</code></pre>11321133<p>By default the <em>Content-Type</em> response header is set, however if explicitly1134assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1135it will not be set again.</p>Added screencasts pageTj Holowaychukbefore adoption4144af3
lines 1136–1137why, one step back11361137<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>fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 1138–1267why, one step back11381139<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>11401141<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>11421143<pre><code>res.redirect('/', 301);1144res.redirect('/account');1145res.redirect('http://google.com');1146res.redirect('home');1147res.redirect('back');1148</code></pre>11491150<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1151The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1152the "home" setting and defaults to "/".</p>11531154<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>11551156<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>11571158<pre><code>// "Remember me" for 15 minutes 1159res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1160</code></pre>11611162<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>11631164<pre><code>app.use(express.cookieDecoder());11651166app.get('/', function(req, res){1167 // use req.cookies.rememberme1168});1169</code></pre>11701171<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>11721173<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>11741175<pre><code>res.clearCookie('rememberme');1176</code></pre>11771178<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>11791180<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1181When a callback function is given a response will <em>not</em> be made1182automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>11831184<p> Most engines accept one or more of the following options,1185 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>11861187<ul>1188<li><em>scope</em> Template evaluation context (value of <em>this</em>)</li>1189<li><em>locals</em> Object containing local variables</li>1190<li><em>debug</em> Output debugging information</li>1191<li><em>status</em> Response status code, defaults to 200</li>1192<li><em>headers</em> Response headers object</li>1193</ul>119411951196<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>11971198<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1199to the view as a local variable.</p>12001201<ul>1202<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1203<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>12041205<ul>1206<li>as: 'something' will add the <em>something</em> local variable</li>1207<li>as: this will use the collection value as the template context</li>1208<li>as: global will merge the collection value's properties with <em>locals</em></li>1209</ul>1210</li>1211<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1212For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1213</ul>121412151216<p>The following are equivalent, and the name of collection value when passed1217to the partial will be <em>movie</em> as derived from the name.</p>12181219<pre><code>partial('theatre/movie.jade', { collection: movies });1220partial('theatre/movie.jade', movies);1221partial('movie.jade', { collection: movies });1222partial('movie.jade', movies);1223partial('movie', movies);1224// In view: movie.director1225</code></pre>12261227<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>12281229<pre><code>partial('movie', { collection: movies, as: 'video' });1230// In view: video.director1231</code></pre>12321233<p>Also we can make our movie the value of <em>this</em> within our view so that instead1234of <em>movie.director</em> we could use <em>this.director</em>.</p>12351236<pre><code>partial('movie', { collection: movies, as: this });1237// In view: this.director1238</code></pre>12391240<p>Another alternative is to "explode" the properties of the collection item into1241pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>12421243<pre><code>partial('movie', { collection: movies, as: global });1244// In view: director1245</code></pre>12461247<p>This same logic applies to a single partial object usage:</p>12481249<pre><code>partial('movie', { object: movie, as: this });1250// In view: this.director12511252partial('movie', { object: movie, as: global });1253// In view: director12541255partial('movie', { object: movie, as: 'video' });1256// In view: video.director12571258partial('movie', { object: movie });1259// In view: movie.director1260</code></pre>12611262<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>12631264<pre><code>partial('movie', movie);1265// => In view: movie.director1266</code></pre>1267Re-built docsTj Holowaychukbefore adoption8e63d04
lines 1268–1285why, one step back1268<h3 id="res-local-name-val-">res.local(name[, val])</h3>12691270<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>12711272<pre><code> app.all('/movie/:id', function(req, res, next){1273 Movie.get(req.params.id, function(err, movie){1274 // Assigns res.locals.movie = movie1275 res.local('movie', movie);1276 });1277 });12781279 app.get('/movie/:id', function(req, res){1280 // movie is already a local, however we1281 // can pass more if we wish1282 res.render('movie', { displayReviews: true });1283 });1284</code></pre>1285fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 1286–1308why, one step back1286<h3 id="app-set-name-val-">app.set(name[, val])</h3>12871288<p>Apply an application level setting <em>name</em> to <em>val</em>, or1289get the value of <em>name</em> when <em>val</em> is not present:</p>12901291<pre><code>app.set('views', __dirname + '/views');1292app.set('views');1293// => ...path...1294</code></pre>12951296<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>12971298<pre><code>app.settings.views1299// => ...path...1300</code></pre>13011302<h3 id="app-enable-name-">app.enable(name)</h3>13031304<p>Enable the given setting <em>name</em>:</p>13051306<pre><code>app.enable('some arbitrary setting');1307app.set('some arbitrary setting');1308// => trueRe-built docsTj Holowaychukbefore adoption8e63d04
lines 1309–1311why, one step back13091310app.enabled('some arbitrary setting');1311// => truefixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 1312–1319why, one step back1312</code></pre>13131314<h3 id="app-disable-name-">app.disable(name)</h3>13151316<p>Disable the given setting <em>name</em>:</p>13171318<pre><code>app.disable('some setting');1319app.set('some setting');Re-built docsTj Holowaychukbefore adoption8e63d04
lines 1320–1322why, one step back1320// => false13211322app.disabled('some setting');fixed github exampleTj Holowaychukbefore adoptionf5af66a
lines 1323–1487why, one step back1323// => false1324</code></pre>13251326<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>13271328<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>13291330<pre><code>app.configure(function(){1331 // executed for each env1332});13331334app.configure('development', function(){1335 // executed for 'development' only1336});1337</code></pre>13381339<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>13401341<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>13421343<pre><code>app.redirect('google', 'http://google.com');1344</code></pre>13451346<p>Now in a route we may call:</p>13471348<p> res.redirect('google');</p>13491350<p>We may also map dynamic redirects:</p>13511352<pre><code>app.redirect('comments', function(req, res){1353 return '/post/' + req.params.id + '/comments';1354});1355</code></pre>13561357<p>So now we may do the following, and the redirect will dynamically adjust to1358the context of the request. If we called this route with <em>GET /post/12</em> our1359redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>13601361<pre><code>app.get('/post/:id', function(req, res){1362 res.redirect('comments');1363});1364</code></pre>13651366<h3 id="app-error-function-">app.error(function)</h3>13671368<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1369Note that we may set several error handlers by making several calls to this method, however the handler1370should call <em>next(err)</em> if it does not wish to deal with the exception:</p>13711372<pre><code>app.error(function(err, req, res, next){1373 res.send(err.message, 500);1374});1375</code></pre>13761377<h3 id="app-helpers-obj-">app.helpers(obj)</h3>13781379<p>Registers static view helpers.</p>13801381<pre><code>app.helpers({1382 name: function(first, last){ return first + ', ' + last },1383 firstName: 'tj',1384 lastName: 'holowaychuk'1385});1386</code></pre>13871388<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1389as well as the <em>name()</em> function exposed.</p>13901391<pre><code><%= name(firstName, lastName) %>1392</code></pre>13931394<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>13951396<p>Registers dynamic view helpers. Dynamic view helpers1397are simply functions which accept <em>req</em>, <em>res</em>, and are1398evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1399becomes the local variable it is associated with.</p>14001401<pre><code>app.dynamicHelpers({1402 session: function(req, res){1403 return req.session;1404 }1405});1406</code></pre>14071408<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>14091410<pre><code><%= session.name %>1411</code></pre>14121413<h3 id="app-mounted-fn-">app.mounted(fn)</h3>14141415<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>14161417<pre><code>var app = express.createServer(),1418 blog = express.createServer();14191420blog.mounted(function(parent){1421 // parent is app1422 // "this" is blog1423});14241425app.use(blog);1426</code></pre>14271428<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>14291430<p>Register the given template engine <em>exports</em>1431as <em>ext</em>. For example we may wish to map ".html"1432files to jade:</p>14331434<pre><code> app.register('.html', require('jade'));1435</code></pre>14361437<p>This is also useful for libraries that may not1438match extensions correctly. For example my haml.js1439library is installed from npm as "hamljs" so instead1440of layout.hamljs, we can register the engine as ".haml":</p>14411442<pre><code> app.register('.haml', require('haml-js'));1443</code></pre>14441445<p>For engines that do not comply with the Express1446specification, we can also wrap their api this way.</p>14471448<pre><code> app.register('.foo', {1449 render: function(str, options) {1450 // perhaps their api is1451 // return foo.toHTML(str, options);1452 }1453 });1454</code></pre>14551456<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>14571458<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1459connections will be accepted via <em>INADDR_ANY</em>.</p>14601461<pre><code>app.listen();1462app.listen(3000);1463app.listen(3000, 'n.n.n.n');1464</code></pre>14651466<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>14671468<pre><code>app.listen('/tmp/express.sock');1469</code></pre>14701471<p>Then try it out:</p>14721473<pre><code>$ telnet /tmp/express.sock1474GET / HTTP/1.114751476HTTP/1.1 200 OK1477Content-Type: text/plain1478Content-Length: 1114791480Hello World1481</code></pre>14821483</div>1484 </div>1485 </div>1486 </body>1487</html>