guide.html
This file
Path
docs/guide.html
1,562 lines · 53.5 KiB · HTML
Last changed by
view lookup docsTj Holowaychukbefore adoption8a62f8c
History of this fileTake it
The walk stopped after 200 commits: lines older than 136f920 point at it.
route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
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;route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
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>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
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>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 193why, one step back193<li><a href="#Route-Param-Pre-conditions">Route Param Pre-conditions</a></li>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 194–195why, one step back194<li><a href="#View-Rendering">View Rendering</a></li>195<li><a href="#View-Partials">View Partials</a></li>view lookup docsTj Holowaychukbefore adoption8a62f8c
line 196why, one step back196<li><a href="#View-Lookup">View Lookup</a></li>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 197–203why, one step back197<li><a href="#Template-Engines">Template Engines</a></li>198<li><a href="#Session-Support">Session Support</a></li>199<li><a href="#Migration-Guide">Migration Guide</a></li>200<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">201<li><a href="#req-header-key-defaultValue-">header()</a></li>202<li><a href="#req-accepts-type-">accepts()</a></li>203<li><a href="#req-is-type-">is()</a></li>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 204why, one step back204<li><a href="#req-param-name-default-">param()</a></li>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 205–211why, one step back205<li><a href="#req-flash-type-msg-">flash()</a></li>206<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>207</ul></li>208<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">209<li><a href="#res-header-key-val-">header()</a></li>210<li><a href="#res-contentType-type-">contentType()</a></li>211<li><a href="#res-attachment-filename-">attachment()</a></li>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 212–213why, one step back212<li><a href="#res-sendfile-path-options-callback-">sendfile()</a></li>213<li><a href="#res-download-file-filename-callback-">download()</a></li>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 214–219why, one step back214<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>215<li><a href="#res-redirect-url-status-">redirect()</a></li>216<li><a href="#res-cookie-name-val-options-">cookie()</a></li>217<li><a href="#res-clearCookie-name-">clearCookie()</a></li>218<li><a href="#res-render-view-options-fn-">render()</a></li>219<li><a href="#res-partial-view-options-">partial()</a></li>Re-built docsTj Holowaychukbefore adoption8e63d04
line 220why, one step back220<li><a href="#res-local-name-val-">local()</a></li>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 221–224why, one step back221</ul></li>222<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">223<li><a href="#app-set-name-val-">set()</a></li>224<li><a href="#app-enable-name-">enable()</a></li>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 225why, one step back225<li><a href="#app-enabled-name-">enabled()</a></li>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 226why, one step back226<li><a href="#app-disable-name-">disable()</a></li>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 227why, one step back227<li><a href="#app-disabled-name-">disabled()</a></li>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 228–245why, one step back228<li><a href="#app-configure-env-function-function-">configure()</a></li>229<li><a href="#app-redirect-name-val-">redirect()</a></li>230<li><a href="#app-error-function-">error()</a></li>231<li><a href="#app-helpers-obj-">helpers()</a></li>232<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>233<li><a href="#app-mounted-fn-">mounted()</a></li>234<li><a href="#app-register-ext-exports-">register()</a></li>235<li><a href="#app-listen-port-host-">listen()</a></li>236</ul></li>237</ul>238 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 239 <p id="tagline">240 High performance, high class web development for241 <a href="http://nodejs.org">Node.js</a>242 </p>243 <ul id="menu">244 <li><a href="index.html">Home</a></li>245 <li><a href="guide.html">Guide</a></li>Added screencasts pageTj Holowaychukbefore adoption4144af3
line 246why, one step back246 <li><a href="screencasts.html">Screencasts</a></li>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 247–258why, one step back247 <li><a href="applications.html">Applications</a></li>248 </ul>249<div class='mp'>250<h2 id="Express">Express</h2>251<p class="man-name">252 <code>guide</code>253</p>254<h3 id="Installation">Installation</h3>255256<pre><code>$ npm install express257</code></pre>258Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 259why, one step back259<h3 id="Creating-A-Server">Creating A Server</h3>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 260why, one step back260Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 261why, one step back261<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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 262–265why, one step back262263<pre><code>var app = require('express').createServer();264265app.get('/', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 266why, one step back266 res.send('hello world');route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 267–271why, one step back267});268269app.listen(3000);270</code></pre>271Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 272–279why, one step back272<h3 id="Creating-An-HTTPS-Server">Creating An HTTPS Server</h3>273274<p> To initialize a <em>express.HTTPSServer</em> we do the same as above, however we275 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>276277<pre><code> var app = require('express').createServer({ key: ... });278</code></pre>279route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 280–287why, one step back280<h3 id="Configuration">Configuration</h3>281282<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers283can use the <em>configure()</em> method to setup needs required by the current environment. When284<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment285prior to the environment specific callback.</p>286287<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack tracesMerge branch 'docs'Tj Holowaychukbefore adoption64da262
line 288why, one step back288in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 289why, one step back289Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 290why, one step back290otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 291–293why, one step back291292<pre><code>app.configure(function(){293 app.use(express.methodOverride());Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 294why, one step back294 app.use(express.bodyParser());route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 295–298why, one step back295 app.use(app.router);296});297298app.configure('development', function(){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 299why, one step back299 app.use(express.static(__dirname + '/public'));route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 300–303why, one step back300 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));301});302303app.configure('production', function(){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 304–306why, one step back304 var oneYear = 31557600000;305 app.use(express.static({ root: __dirname + '/public', maxAge: oneYear }));306 app.use(express.errorHandler());route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 307–311why, one step back307});308</code></pre>309310<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>311Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 312why, one step back312<pre><code> app.configure(function(){route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 313–314why, one step back313 app.set('views', __dirname + '/views');314 app.set('views');Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 315why, one step back315 // => "/absolute/path/to/views"route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 316–321why, one step back316317 app.enable('some feature');318 // same as app.set('some feature', true);319320 app.disable('some feature');321 // same as app.set('some feature', false);Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 322–325why, one step back322323 app.enabled('some feature')324 // => false325 });route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 326–365why, one step back326</code></pre>327328<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>329330<pre><code>$ NODE_ENV=production node app.js331</code></pre>332333<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>334335<h3 id="Settings">Settings</h3>336337<p>Express supports the following settings out of the box:</p>338339<ul>340<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>341<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>342<li><em>view engine</em> Default view engine name for views rendered without extensions</li>343<li><em>view options</em> An object specifying global view options</li>344</ul>345346347<h3 id="Routing">Routing</h3>348349<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.350For example we may want to render a user's account for the path <em>/user/12</em>, this351can be done by defining the route below. The values associated to the named placeholders352are available as <code>req.params</code>.</p>353354<pre><code>app.get('/user/:id', function(req, res){355 res.send('user ' + req.params.id);356});357</code></pre>358359<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example360when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>361362<pre><code>\/user\/([^\/]+)\/?363</code></pre>364365<p>Regular expression literals may also be passed for complex uses. Since captureRegenerated docsTj Holowaychukbefore adoptiond3abcaf
line 366why, one step back366groups 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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 367–414why, one step back367368<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){369 res.send(req.params);370});371</code></pre>372373<p>Curl requests against the previously defined route:</p>374375<pre><code> $ curl http://dev:3000/user376 [null,null]377 $ curl http://dev:3000/users378 [null,null]379 $ curl http://dev:3000/users/1380 ["1",null]381 $ curl http://dev:3000/users/1..15382 ["1","15"]383</code></pre>384385<p>Below are some route examples, and the associated paths that they386may consume:</p>387388<pre><code> "/user/:id"389 /user/12390391 "/users/:id?"392 /users/5393 /users394395 "/files/*"396 /files/jquery.js397 /files/javascripts/jquery.js398399 "/file/*.*"400 /files/jquery.js401 /files/javascripts/jquery.js402403 "/user/:id/:operation?"404 /user/1405 /user/1/edit406407 "/products.:format"408 /products.json409 /products.xml410411 "/products.:format?"412 /products.json413 /products.xml414 /productsRegenerated docsTj Holowaychukbefore adoptiond3abcaf
lines 415–418why, one step back415416 "/user/:id.:format?"417 /user/12418 /user/12.jsonroute-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 419–420why, one step back419</code></pre>420Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 421why, one step back421<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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 422–425why, one step back422423<pre><code>var express = require('express')424 , app = express.createServer();425Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 426why, one step back426app.use(express.bodyParser());route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 427–433why, one step back427428app.post('/', function(req, res){429 res.send(req.body);430});431432app.listen(3000);433</code></pre>Regenerated docsTj Holowaychukbefore adoptiond3abcaf
line 434why, one step back434Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 435why, one step back435<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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 436–440why, one step back436437<h3 id="Passing-Route-Control">Passing Route Control</h3>438439<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,440the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 441why, one step back441and 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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 442–456why, one step back442443<pre><code>app.get('/users/:id?', function(req, res, next){444 var id = req.params.id;445 if (id) {446 // do something447 } else {448 next();449 }450});451452app.get('/users', function(req, res){453 // do something else454});455</code></pre>456Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 457why, one step back457<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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 458–499why, one step back458459<pre><code>var express = require('express')460 , app = express.createServer();461462var users = [{ name: 'tj' }];463464app.all('/user/:id/:op?', function(req, res, next){465 req.user = users[req.params.id];466 if (req.user) {467 next();468 } else {469 next(new Error('cannot find user ' + req.params.id));470 }471});472473app.get('/user/:id', function(req, res){474 res.send('viewing ' + req.user.name);475});476477app.get('/user/:id/edit', function(req, res){478 res.send('editing ' + req.user.name);479});480481app.put('/user/:id', function(req, res){482 res.send('updating ' + req.user.name);483});484485app.get('*', function(req, res){486 res.send('what???', 404);487});488489app.listen(3000); 490</code></pre>491492<h3 id="Middleware">Middleware</h3>493494<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be495passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>496497<pre><code> var express = require('express');498499var app = express.createServer(Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 500–501why, one step back500 express.logger()501 , express.bodyParser()route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 502–504why, one step back502 );503</code></pre>504Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 505why, one step back505<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 506–513why, one step back506507<pre><code>app.use(express.logger({ format: ':method :uri' }));508</code></pre>509510<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>511512<pre><code>var connect = require('connect');513app.use(connect.logger());Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 514why, one step back514app.use(connect.bodyParser());route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 515–519why, one step back515</code></pre>516517<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>518519<pre><code>app.use(express.logger());Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 520why, one step back520app.use(express.bodyParser());route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 521–529why, one step back521</code></pre>522523<h3 id="Route-Middleware">Route Middleware</h3>524525<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>526527<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>528529<pre><code>app.get('/user/:id', function(req, res, next){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 530–533why, one step back530 loadUser(req.params.id, function(err, user){531 if (err) return next(err);532 res.send('Viewing user ' + user.name);533 });route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 534–539why, one step back534});535</code></pre>536537<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>538539<pre><code>function loadUser(req, res, next) {Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 540–547why, one step back540 // You would fetch your user from the db541 var user = users[req.params.id];542 if (user) {543 req.user = user;544 next();545 } else {546 next(new Error('Failed to load user ' + req.params.id));547 }route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 548–550why, one step back548}549550app.get('/user/:id', loadUser, function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 551why, one step back551 res.send('Viewing user ' + req.user.name);route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 552–557why, one step back552});553</code></pre>554555<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>556557<pre><code>function andRestrictToSelf(req, res, next) {Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 558–560why, one step back558 req.authenticatedUser.id == req.user.id559 ? next()560 : next(new Error('Unauthorized'));route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 561–563why, one step back561}562563app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 564why, one step back564 res.send('Editing user ' + req.user.name);route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 565–570why, one step back565});566</code></pre>567568<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>569570<pre><code>function andRestrictTo(role) {Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 571–575why, one step back571 return function(req, res, next) {572 req.authenticatedUser.role == role573 ? next()574 : next(new Error('Unauthorized'));575 }route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 576–578why, one step back576}577578app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 579why, one step back579 res.send('Deleted user ' + req.user.name);route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 580–611why, one step back580});581</code></pre>582583<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>584585<pre><code>var a = [middleware1, middleware2]586 , b = [middleware3, middleware4]587 , all = [a, b];588589app.get('/foo', a, function(){});590app.get('/bar', a, function(){});591592app.get('/', a, middleware3, middleware4, function(){});593app.get('/', a, b, function(){});594app.get('/', all, function(){});595</code></pre>596597<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>598599<h3 id="HTTP-Methods">HTTP Methods</h3>600601<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>602603<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>604605<pre><code> <form method="post" action="/">606 <input type="text" name="user[name]" />607 <input type="text" name="user[email]" />608 <input type="submit" value="Submit" />609 </form>610</code></pre>611Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 612why, one step back612<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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 613why, one step back613Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 614why, one step back614<pre><code>app.use(express.bodyParser());route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 615–619why, one step back615</code></pre>616617<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>618619<pre><code>app.post('/', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 620–621why, one step back620 console.log(req.body.user);621 res.redirect('back');route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 622–624why, one step back622});623</code></pre>624Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 625why, one step back625<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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 626why, one step back626Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 627why, one step back627<pre><code>app.use(express.bodyParser());route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 628–652why, one step back628app.use(express.methodOverride());629</code></pre>630631<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>632633<pre><code><form method="post" action="/">634 <input type="hidden" name="_method" value="put" />635 <input type="text" name="user[name]" />636 <input type="text" name="user[email]" />637 <input type="submit" value="Submit" /> 638</form>639640app.put('/', function(){641 console.log(req.body.user);642 res.redirect('back');643});644</code></pre>645646<h3 id="Error-Handling">Error Handling</h3>647648<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,649or passed to <em>next(err)</em>. Below is an example which serves different pages based on our650ad-hoc <em>NotFound</em> exception:</p>651652<pre><code>function NotFound(msg){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 653–655why, one step back653 this.name = 'NotFound';654 Error.call(this, msg);655 Error.captureStackTrace(this, arguments.callee);route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 656–657why, one step back656}657Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 658why, one step back658NotFound.protoype.__proto__ = Error.prototype;route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 659–660why, one step back659660app.get('/404', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 661why, one step back661 throw new NotFound;route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 662–664why, one step back662});663664app.get('/500', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 665why, one step back665 throw new Error('keyboard cat!');route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 666–687why, one step back666});667</code></pre>668669<p>We can call <em>app.error()</em> several times as shown below.670Here we check for an instanceof <em>NotFound</em> and show the671404 page, or we pass on to the next error handler.</p>672673<p>Note that these handlers can be defined anywhere, as they674will be placed below the route handlers on <em>listen()</em>. This675allows for definition within <em>configure()</em> blocks so we can676handle exceptions in different ways based on the environment.</p>677678<pre><code>app.error(function(err, req, res, next){679 if (err instanceof NotFound) {680 res.render('404.jade');681 } else {682 next(err);683 }684});685</code></pre>686687<p>Here we assume all errors as 500 for the simplicity ofMerge branch 'docs'Tj Holowaychukbefore adoption64da262
line 688why, one step back688this 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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 689–690why, one step back689690<pre><code>app.error(function(err, req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 691–693why, one step back691 res.render('500.jade', {692 error: err693 });route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 694–711why, one step back694});695</code></pre>696697<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware698to report on exceptions. For example if we wish to output exceptions699in "development" mode to <em>stderr</em> we can use:</p>700701<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));702</code></pre>703704<p>Also during development we may want fancy html pages to show exceptions705that are passed or thrown, so we can set <em>showStack</em> to true:</p>706707<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));708</code></pre>709710<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>711is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
line 712why, one step back712Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 713why, one step back713<h3 id="Route-Param-Pre-conditions">Route Param Pre-conditions</h3>Route precondition docsTj Holowaychukbefore adoptionfd2f67b
line 714why, one step back714Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 715why, one step back715<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 716–724why, one step back716717<pre><code>app.get('/user/:userId', function(req, res, next){718 User.get(req.params.userId, function(err, user){719 if (err) return next(err);720 res.send('user ' + user.name);721 });722}); 723</code></pre>724Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 725why, one step back725<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 726–752why, one step back726727<pre><code>app.param('userId', function(req, res, next, id){728 User.get(id, function(err, user){729 if (err) return next(err);730 if (!user) return next(new Error('failed to find user'));731 req.user = user;732 next();733 });734});735</code></pre>736737<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>738739<pre><code>app.get('/user/:userId', function(req, res){740 res.send('user ' + req.user.name);741});742</code></pre>743744<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>745746<pre><code>app.param('number', function(n){ return parseInt(n, 10); });747</code></pre>748749<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>750751<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });752</code></pre>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 753–755why, one step back753754<h3 id="View-Rendering">View Rendering</h3>755Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 756why, one step back756<p>View filenames take the form "<name>.<engine>", where <engine> is the nameroute-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 757why, one step back757of the module that will be required. For example the view <em>layout.ejs</em> willMerge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 758–759why, one step back758tell 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 behaviour759<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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 760why, one step back760Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 761–763why, one step back761<p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,762and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as763the <em>body</em> local variable in <em>layout.jade</em>.</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 764–765why, one step back764765<pre><code>app.get('/', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 766why, one step back766 res.render('index.jade', { title: 'My Site' });route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 767–770why, one step back767});768</code></pre>769770<p>The new <em>view engine</em> setting allows us to specify our default template engine,Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 771why, one step back771so for example when using jade we could set:</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 772–794why, one step back772773<pre><code>app.set('view engine', 'jade');774</code></pre>775776<p>Allowing us to render with:</p>777778<pre><code>res.render('index');779</code></pre>780781<p>vs:</p>782783<pre><code>res.render('index.jade');784</code></pre>785786<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still787mix and match template engines:</p>788789<pre><code>res.render('another-page.ejs');790</code></pre>791792<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>793794<pre><code>app.set('view options', {Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 795why, one step back795 layout: falseroute-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 796–798why, one step back796});797</code></pre>798Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 799why, one step back799<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 800–828why, one step back800801<pre><code>res.render('myview.ejs', { layout: true });802</code></pre>803804<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>805806<pre><code>res.render('page', { layout: 'mylayout' });807</code></pre>808809<p>Otherwise we must specify the extension:</p>810811<pre><code>res.render('page', { layout: 'mylayout.jade' });812</code></pre>813814<p>These paths may also be absolute:</p>815816<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });817</code></pre>818819<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>820821<pre><code>app.set('view options', {822 open: '{{',823 close: '}}'824});825</code></pre>826827<h3 id="View-Partials">View Partials</h3>828Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 829why, one step back829<p>The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iteratingroute-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 830–834why, one step back830in a view to display comments, we would use a partial with collection support:</p>831832<pre><code>partial('comment', { collection: comments });833</code></pre>834Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 835why, one step back835<p>If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 836–843why, one step back836837<pre><code>partial('comment', comments);838</code></pre>839840<p>When using the partial collection support a few "magic" variables are provided841for free:</p>842843<ul>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 844–847why, one step back844<li><em>firstInCollection</em> true if this is the first object</li>845<li><em>indexInCollection</em> index of the object in the collection</li>846<li><em>lastInCollection</em> true if this is the last object</li>847<li><em>collectionLength</em> length of the collection</li>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 848–852why, one step back848</ul>849850851<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>852view lookup docsTj Holowaychukbefore adoption8a62f8c
lines 853–859why, one step back853<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>854855<h3 id="View-Lookup">View Lookup</h3>856857<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('edit')</em> it would attempt to load <em>views/user/edit.jade</em>, whereas <em>partial('../messages')</em> would load <em>views/messages.jade</em>.</p>858859<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('users')</em> either <em>views/users.jade</em>, or <em>views/users/index.jade</em>.</p>Added screencasts pageTj Holowaychukbefore adoption4144af3
line 860why, one step back860route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 861–874why, one step back861<h3 id="Template-Engines">Template Engines</h3>862863<p>Below are a few template engines commonly used with Express:</p>864865<ul>866<li><a href="http://jade-lang.com">Jade</a> haml.js successor</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>874Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 875why, one step back875<p>Sessions support can be added by using Connect'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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 876why, one step back876Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 877–878why, one step back877<pre><code>app.use(express.cookieParser());878app.use(express.session({ secret: "keyboard cat" }));route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 879–883why, one step back879</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');Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 884–885why, one step back884app.use(express.cookieParser());885app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 886–890why, one step back886</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');Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 891–893why, one step back891app.use(express.bodyParser());892app.use(express.cookieParser());893app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 894–896why, one step back894895app.post('/add-to-cart', function(req, res){896 // Perhaps we posted several items with a formMerge branch 'docs'Tj Holowaychukbefore adoption64da262
line 897why, one step back897 // (use the bodyParser() middleware for this)route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 898–913why, one step back898 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>913Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 914why, one step back914<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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 915–917why, one step back915916<h3 id="Migration-Guide">Migration Guide</h3>917Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 918why, one step back918<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.</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 919–928why, one step back919920<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>928Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 929–939why, one step back929<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>930931<pre><code>// sent Referrer: http://google.com932933req.header('Referer');934// => "http://google.com"935936req.header('Referrer');937// => "http://google.com"938</code></pre>939route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 940–1018why, one step back940<h3 id="req-accepts-type-">req.accepts(type)</h3>941942<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>943944<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise945the given <em>type</em> is matched by an exact match, and then subtypes. You946may pass the subtype such as "html" which is then converted internally947to "text/html" using the mime lookup table.</p>948949<pre><code>// Accept: text/html950req.accepts('html');951// => true952953// Accept: text/*; application/json954req.accepts('html');955req.accepts('text/html');956req.accepts('text/plain');957req.accepts('application/json');958// => true959960req.accepts('image/png');961req.accepts('png');962// => false963</code></pre>964965<h3 id="req-is-type-">req.is(type)</h3>966967<p>Check if the incoming request contains the <em>Content-Type</em>968header field, and it contains the give mime <em>type</em>.</p>969970<pre><code> // With Content-Type: text/html; charset=utf-8971 req.is('html');972 req.is('text/html');973 // => true974975 // When Content-Type is application/json976 req.is('json');977 req.is('application/json');978 // => true979980 req.is('html');981 // => false982</code></pre>983984<p>Ad-hoc callbacks can also be registered with Express, to perform985assertions again the request, for example if we need an expressive986way to check if our incoming request is an image, we can register <em>"an image"</em>987callback:</p>988989<pre><code> app.is('an image', function(req){990 return 0 == req.headers['content-type'].indexOf('image');991 });992</code></pre>993994<p>Now within our route callbacks, we can use to to assert content types995such as <em>"image/jpeg"</em>, <em>"image/png"</em>, etc.</p>996997<pre><code> app.post('/image/upload', function(req, res, next){998 if (req.is('an image')) {999 // do something1000 } else {1001 next();1002 }1003 });1004</code></pre>10051006<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you1007can perform any request assertion you wish.</p>10081009<p>Wildcard matches can also be made, simplifying our example above for <em>"an image"</em>, by asserting the <em>subtype</em> only:</p>10101011<pre><code>req.is('image/*');1012</code></pre>10131014<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>10151016<pre><code>req.is('*/json');1017</code></pre>1018Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1019why, one step back1019<h3 id="req-param-name-default-">req.param(name[, default])</h3>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 1020why, one step back1020Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1021why, one step back1021<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1022–1023why, one step back10221023<ul>Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1024why, one step back1024<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1025–1031why, one step back1025<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1026<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1027</ul>102810291030<p>To utilize urlencoded request bodies, <em>req.body</em>1031should be an object. This can be done by usingMerge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1032why, one step back1032the _express.bodyParser middleware.</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1033–1086why, one step back10331034<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>10351036<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>10371038<pre><code>req.flash('info', 'email sent');1039req.flash('error', 'email delivery failed');1040req.flash('info', 'email re-sent');1041// => 210421043req.flash('info');1044// => ['email sent', 'email re-sent']10451046req.flash('info');1047// => []10481049req.flash();1050// => { error: ['email delivery failed'], info: [] }1051</code></pre>10521053<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>10541055<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1056</code></pre>10571058<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>10591060<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header1061to see if it was issued by an <em>XMLHttpRequest</em>:</p>10621063<pre><code>req.xhr1064req.isXMLHttpRequest1065</code></pre>10661067<h3 id="res-header-key-val-">res.header(key[, val])</h3>10681069<p>Get or set the response header <em>key</em>.</p>10701071<pre><code>res.header('Content-Length');1072// => undefined10731074res.header('Content-Length', 123);1075// => 12310761077res.header('Content-Length');1078// => 1231079</code></pre>10801081<h3 id="res-contentType-type-">res.contentType(type)</h3>10821083<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>10841085<pre><code> var filename = 'path/to/image.png';1086 res.contentType(filename);Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1087why, one step back1087 // Content-Type is now "image/png"route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1088–1096why, one step back1088</code></pre>10891090<h3 id="res-attachment-filename-">res.attachment([filename])</h3>10911092<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>10931094<pre><code> res.attachment('path/to/my/image.png');1095</code></pre>1096Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1097why, one step back1097<h3 id="res-sendfile-path-options-callback-">res.sendfile(path[, options[, callback]])</h3>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1098–1103why, one step back10981099<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>11001101<pre><code>res.sendfile('path/to/my.file');1102</code></pre>1103Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1104–1105why, one step back1104<p>This method accepts an optional callback which is called when1105an 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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 1106why, one step back1106Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1107why, one step back1107<pre><code>res.sendfile(path, function(err){route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 1108why, one step back1108 if (err) {Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1109why, one step back1109 next(err);route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1110–1115why, one step back1110 } else {1111 console.log('transferred %s', path);1112 }1113});1114</code></pre>1115Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1116why, one step back1116<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 1117why, one step back1117Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1118–1121why, one step back1118<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1119 // handle1120});1121</code></pre>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 1122why, one step back1122Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1123–1124why, one step back1123<h3 id="res-download-file-filename-callback-">res.download(file[, filename[, callback]])</h3>1124route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1125–1136why, one step back1125<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>11261127<pre><code>res.download('path/to/image.png');1128res.download('path/to/image.png', 'foo.png');1129</code></pre>11301131<p>This is equivalent to:</p>11321133<pre><code>res.attachment(file);1134res.sendfile(file);1135</code></pre>1136Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1137–1143why, one step back1137<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>:</p>11381139<pre><code>res.download(path, 'expenses.doc', function(err){1140 // handle1141});1142</code></pre>1143route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1144–1145why, one step back1144<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>1145Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1146–1147why, one step back1146<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1147objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1148–1160why, one step back11481149<pre><code> res.send(); // 2041150 res.send(new Buffer('wahoo'));1151 res.send({ some: 'json' });1152 res.send('<p>some html</p>');1153 res.send('Sorry, cant find that', 404);1154 res.send('text', { 'Content-Type': 'text/plain' }, 201);1155 res.send(404);1156</code></pre>11571158<p>By default the <em>Content-Type</em> response header is set, however if explicitly1159assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1160it will not be set again.</p>Added screencasts pageTj Holowaychukbefore adoption4144af3
line 1161why, one step back1161Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1162why, one step back1162<p>Note that this method <em>end()</em>s the response, so you will want to use node's <em>res.write()</em> for multiple writes or streaming.</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1163–1180why, one step back11631164<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>11651166<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>11671168<pre><code>res.redirect('/', 301);1169res.redirect('/account');1170res.redirect('http://google.com');1171res.redirect('home');1172res.redirect('back');1173</code></pre>11741175<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1176The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1177the "home" setting and defaults to "/".</p>11781179<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>1180Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1181why, one step back1181<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>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1182–1188why, one step back11821183<pre><code>// "Remember me" for 15 minutes 1184res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1185</code></pre>11861187<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>1188Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1189why, one step back1189<pre><code>app.use(express.cookieParser());route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1190–1191why, one step back11901191app.get('/', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1192why, one step back1192 // use req.cookies.remembermeroute-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1193–1208why, one step back1193});1194</code></pre>11951196<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>11971198<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>11991200<pre><code>res.clearCookie('rememberme');1201</code></pre>12021203<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>12041205<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1206When a callback function is given a response will <em>not</em> be made1207automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>1208Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1209why, one step back1209<p>The <em>options</em> passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 1210why, one step back1210Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1211–1213why, one step back1211<pre><code>var user = { name: 'tj' };1212res.render('index', { layout: false, user: user });1213</code></pre>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1214–1286why, one step back12141215<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>12161217<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1218to the view as a local variable.</p>12191220<ul>1221<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1222<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>12231224<ul>1225<li>as: 'something' will add the <em>something</em> local variable</li>1226<li>as: this will use the collection value as the template context</li>1227<li>as: global will merge the collection value's properties with <em>locals</em></li>1228</ul>1229</li>1230<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1231For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1232</ul>123312341235<p>The following are equivalent, and the name of collection value when passed1236to the partial will be <em>movie</em> as derived from the name.</p>12371238<pre><code>partial('theatre/movie.jade', { collection: movies });1239partial('theatre/movie.jade', movies);1240partial('movie.jade', { collection: movies });1241partial('movie.jade', movies);1242partial('movie', movies);1243// In view: movie.director1244</code></pre>12451246<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>12471248<pre><code>partial('movie', { collection: movies, as: 'video' });1249// In view: video.director1250</code></pre>12511252<p>Also we can make our movie the value of <em>this</em> within our view so that instead1253of <em>movie.director</em> we could use <em>this.director</em>.</p>12541255<pre><code>partial('movie', { collection: movies, as: this });1256// In view: this.director1257</code></pre>12581259<p>Another alternative is to "explode" the properties of the collection item into1260pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>12611262<pre><code>partial('movie', { collection: movies, as: global });1263// In view: director1264</code></pre>12651266<p>This same logic applies to a single partial object usage:</p>12671268<pre><code>partial('movie', { object: movie, as: this });1269// In view: this.director12701271partial('movie', { object: movie, as: global });1272// In view: director12731274partial('movie', { object: movie, as: 'video' });1275// In view: video.director12761277partial('movie', { object: movie });1278// In view: movie.director1279</code></pre>12801281<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>12821283<pre><code>partial('movie', movie);1284// => In view: movie.director1285</code></pre>1286Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1287–1302why, one step back1287<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>12881289<pre><code>app.get('/users', function(req, res){1290 if (req.xhr) {1291 // respond with the each user in the collection1292 // passed to the "user" view1293 res.partial('user', users);1294 } else {1295 // respond with layout, and users page1296 // which internally does partial('user', users)1297 // along with other UI1298 res.render('users', { users: users });1299 }1300});1301</code></pre>1302Re-built docsTj Holowaychukbefore adoption8e63d04
lines 1303–1320why, one step back1303<h3 id="res-local-name-val-">res.local(name[, val])</h3>13041305<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>13061307<pre><code> app.all('/movie/:id', function(req, res, next){1308 Movie.get(req.params.id, function(err, movie){1309 // Assigns res.locals.movie = movie1310 res.local('movie', movie);1311 });1312 });13131314 app.get('/movie/:id', function(req, res){1315 // movie is already a local, however we1316 // can pass more if we wish1317 res.render('movie', { displayReviews: true });1318 });1319</code></pre>1320route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1321–1343why, one step back1321<h3 id="app-set-name-val-">app.set(name[, val])</h3>13221323<p>Apply an application level setting <em>name</em> to <em>val</em>, or1324get the value of <em>name</em> when <em>val</em> is not present:</p>13251326<pre><code>app.set('views', __dirname + '/views');1327app.set('views');1328// => ...path...1329</code></pre>13301331<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>13321333<pre><code>app.settings.views1334// => ...path...1335</code></pre>13361337<h3 id="app-enable-name-">app.enable(name)</h3>13381339<p>Enable the given setting <em>name</em>:</p>13401341<pre><code>app.enable('some arbitrary setting');1342app.set('some arbitrary setting');1343// => trueRe-built docsTj Holowaychukbefore adoption8e63d04
lines 1344–1346why, one step back13441345app.enabled('some arbitrary setting');1346// => trueroute-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1347–1348why, one step back1347</code></pre>1348Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1349–1360why, one step back1349<h3 id="app-enabled-name-">app.enabled(name)</h3>13501351<p>Check if setting <em>name</em> is enabled:</p>13521353<pre><code>app.enabled('view cache');1354// => false13551356app.enable('view cache');1357app.enabled('view cache');1358// => true1359</code></pre>1360route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1361–1366why, one step back1361<h3 id="app-disable-name-">app.disable(name)</h3>13621363<p>Disable the given setting <em>name</em>:</p>13641365<pre><code>app.disable('some setting');1366app.set('some setting');Re-built docsTj Holowaychukbefore adoption8e63d04
lines 1367–1369why, one step back1367// => false13681369app.disabled('some setting');route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1370–1372why, one step back1370// => false1371</code></pre>1372Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1373–1386why, one step back1373<h3 id="app-disabled-name-">app.disabled(name)</h3>13741375<p>Check if setting <em>name</em> is disabled:</p>13761377<pre><code>app.enable('view cache');13781379app.disabled('view cache');1380// => false13811382app.disable('view cache');1383app.disabled('view cache');1384// => true1385</code></pre>1386route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1387–1401why, one step back1387<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>13881389<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>13901391<pre><code>app.configure(function(){1392 // executed for each env1393});13941395app.configure('development', function(){1396 // executed for 'development' only1397});1398</code></pre>13991400<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>1401Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1402why, one step back1402<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1403–1413why, one step back14031404<pre><code>app.redirect('google', 'http://google.com');1405</code></pre>14061407<p>Now in a route we may call:</p>14081409<p> res.redirect('google');</p>14101411<p>We may also map dynamic redirects:</p>14121413<pre><code>app.redirect('comments', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1414why, one step back1414 return '/post/' + req.params.id + '/comments';route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1415–1422why, one step back1415});1416</code></pre>14171418<p>So now we may do the following, and the redirect will dynamically adjust to1419the context of the request. If we called this route with <em>GET /post/12</em> our1420redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>14211422<pre><code>app.get('/post/:id', function(req, res){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1423why, one step back1423 res.redirect('comments');route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1424–1426why, one step back1424});1425</code></pre>1426Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1427–1431why, one step back1427<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>14281429<pre><code>res.redirect('/posts');1430</code></pre>1431route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1432–1438why, one step back1432<h3 id="app-error-function-">app.error(function)</h3>14331434<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1435Note that we may set several error handlers by making several calls to this method, however the handler1436should call <em>next(err)</em> if it does not wish to deal with the exception:</p>14371438<pre><code>app.error(function(err, req, res, next){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
line 1439why, one step back1439 res.send(err.message, 500);route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1440–1446why, one step back1440});1441</code></pre>14421443<h3 id="app-helpers-obj-">app.helpers(obj)</h3>14441445<p>Registers static view helpers.</p>1446Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1447–1451why, one step back1447<p> app.helpers({</p>14481449<pre><code> name: function(first, last){ return first + ', ' + last }1450, firstName: 'tj'1451, lastName: 'holowaychuk'route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1452–1453why, one step back1452</code></pre>1453Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1454–1455why, one step back1454<p> });</p>1455route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1456–1469why, one step back1456<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1457as well as the <em>name()</em> function exposed.</p>14581459<pre><code><%= name(firstName, lastName) %>1460</code></pre>14611462<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>14631464<p>Registers dynamic view helpers. Dynamic view helpers1465are simply functions which accept <em>req</em>, <em>res</em>, and are1466evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1467becomes the local variable it is associated with.</p>14681469<pre><code>app.dynamicHelpers({Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1470–1472why, one step back1470 session: function(req, res){1471 return req.session;1472 }route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1473–1488why, one step back1473});1474</code></pre>14751476<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>14771478<pre><code><%= session.name %>1479</code></pre>14801481<h3 id="app-mounted-fn-">app.mounted(fn)</h3>14821483<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>14841485<pre><code>var app = express.createServer(),1486 blog = express.createServer();14871488blog.mounted(function(parent){Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1489–1490why, one step back1489 // parent is app1490 // "this" is blogroute-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1491–1513why, one step back1491});14921493app.use(blog);1494</code></pre>14951496<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>14971498<p>Register the given template engine <em>exports</em>1499as <em>ext</em>. For example we may wish to map ".html"1500files to jade:</p>15011502<pre><code> app.register('.html', require('jade'));1503</code></pre>15041505<p>This is also useful for libraries that may not1506match extensions correctly. For example my haml.js1507library is installed from npm as "hamljs" so instead1508of layout.hamljs, we can register the engine as ".haml":</p>15091510<pre><code> app.register('.haml', require('haml-js'));1511</code></pre>15121513<p>For engines that do not comply with the ExpressMerge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1514–1517why, one step back1514specification, we can also wrap their api this way. Below1515we map <em>.md</em> to render markdown files, rendering the html once1516since it will not change on subsequent calls, and support local substitution1517in the form of "{name}".</p>route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
line 1518why, one step back1518Merge branch 'docs'Tj Holowaychukbefore adoption64da262
lines 1519–1528why, one step back1519<pre><code> app.register('.md', {1520 compile: function(str, options){1521 var html = md.toHTML(str);1522 return function(locals){1523 return html.replace(/\{([^}]+)\}/g, function(_, name){1524 return locals[name];1525 });1526 };1527 }1528 });route-separation example using new view resolutionTj Holowaychukbefore adoption136f920
lines 1529–1562why, one step back1529</code></pre>15301531<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>15321533<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1534connections will be accepted via <em>INADDR_ANY</em>.</p>15351536<pre><code>app.listen();1537app.listen(3000);1538app.listen(3000, 'n.n.n.n');1539</code></pre>15401541<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>15421543<pre><code>app.listen('/tmp/express.sock');1544</code></pre>15451546<p>Then try it out:</p>15471548<pre><code>$ telnet /tmp/express.sock1549GET / HTTP/1.115501551HTTP/1.1 200 OK1552Content-Type: text/plain1553Content-Length: 1115541555Hello World1556</code></pre>15571558</div>1559 </div>1560 </div>1561 </body>1562</html>