guide.html
This file
Path
docs/guide.html
1,010 lines · 31.4 KiB · HTML
Last changed by
Regenerated docs againTj Holowaychukbefore adoption8ead901
History of this fileTake it
The walk stopped after 200 commits: lines older than 9fbb9fa point at it.
Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 1–99why, one step back1<html>2 <head>3 <title>Express - node web framework</title>4 <style>5 #tagline {6 margin-left: 75px;7 margin-bottom: 30px;8 color: rgba(255,255,255,0.7); }9 html {10 background: #1c1c1c url(images/bg.tile.jpg); }1112 body {13 margin: 0;14 padding-bottom: 30px;15 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";16 font-size: 14px;17 line-height: 1.5;18 -webkit-text-stroke: 1px rgba(0, 0, 0, 0.1);19 -moz-text-stroke: 1px rgba(0, 0, 0, 0.1);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 {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; }4950 pre {51 margin: 20px 10px;52 padding: 25px 20px;53 background: rgba(0,0,0,0.5);54 border: 1px solid #323232;55 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);56 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);57 -webkit-border-radius: 5px;58 -moz-border-radius: 5px; }5960 code {61 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6263 ul {64 margin: 15px 0;65 padding: 0 0 0 35px; }66 ul li {67 margin: 0;68 padding: 2px 0;69 list-style: square; }7071 .sect {72 margin-left: 40px; }7374 #logo {75 display: block;76 margin-left: 30%;77 margin-bottom: 30px;78 width: 194px;79 height: 51px;80 background: url(images/logo.png) 0 0 no-repeat;81 text-indent: -99999px; }82 #logo:hover {83 opacity: 0.7; }84 #logo:active {85 opacity: 0.3; }8687 #ribbon {88 position: fixed;89 top: 0;90 right: 0;91 z-index: 2; }9293 #wrapper {94 width: 100%;95 min-height: 800px;96 background: url(images/top.png) 0 0 repeat-x; }9798 #container {99 margin: 0 auto;Regenerated docs againTj Holowaychukbefore adoption8ead901
line 100why, one step back100 padding-top: 80px;Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 101–104why, one step back101 width: 550px; }102103 #toc {104 position: fixed;Regenerated docs againTj Holowaychukbefore adoption8ead901
line 105why, one step back105 top: 0;Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 106–113why, one step back106 left: 0;107 margin: 0 0 0 15px;108 padding: 15px;109 height: 100%;110 background: rgba(0,0,0,0.2);111 border-right: 1px solid rgba(255,255,255,0.05);112 }113 #toc li {More view docsTj Holowaychukbefore adoption1c8ff48
line 114why, one step back114 padding: 0;Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 115–162why, one step back115 list-style: none;116 }117 #toc li a {118 font-size: 11px;119 }120 #menu {121 margin-left: 65px;122 padding: 0;123 padding-bottom: 30px; }124 #menu li {125 display: inline;126 list-style: none; }127 #menu li a {128 display: block;129 float: left;130 margin: 0 2px;131 padding: 3px 15px;132 background: rgba(0,0,0,0.2);133 -webkit-border-radius: 8px;134 -moz-border-radius: 8px;135 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);136 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);137 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;138 -webkit-transition-duration: 0.15s;139 -webkit-transition-timing-function: ease-out; }140 #menu li a:hover,141 #menu li a.active {142 background: rgba(0,0,0,0.5); }143 #menu li a:active {144 background: rgba(0,0,0,0.1);145 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);146 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }147 </style>148 </head>149 <body>150 <a href='http://github.com/visionmedia/express'> 151 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 152 </a>153 <div id="wrapper">154 <div id="container"><ul id="toc">155<li><a href="#Installation">Installation</a></li>156<li><a href="#Creating-An-Application">Creating An Application</a></li>157<li><a href="#Configuration">Configuration</a></li>158<li><a href="#Settings">Settings</a></li>159<li><a href="#Routing">Routing</a></li>160<li><a href="#Passing-Route-Control">Passing Route Control</a></li>161<li><a href="#Middleware">Middleware</a></li>162<li><a href="#Error-Handling">Error Handling</a></li>Added more view docsTj Holowaychukbefore adoption2f96506
lines 163–165why, one step back163<li><a href="#View-Rendering">View Rendering</a></li>164<li><a href="#View-Partials">View Partials</a></li>165<li><a href="#Template-Engines">Template Engines</a></li>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 166–177why, one step back166<li><a href="#req-header-key-defaultValue-">req.header()</a></li>167<li><a href="#req-accepts-type-">req.accepts()</a></li>168<li><a href="#req-param-name-">req.param()</a></li>169<li><a href="#req-flash-type-msg-">req.flash()</a></li>170<li><a href="#req-isXMLHttpRequest">req.isXMLHttpRequest</a></li>171<li><a href="#res-header-key-val-">res.header()</a></li>172<li><a href="#res-contentType-type-">res.contentType()</a></li>173<li><a href="#res-attachment-filename-">res.attachment()</a></li>174<li><a href="#res-sendfile-path-">res.sendfile()</a></li>175<li><a href="#res-download-file-filename-">res.download()</a></li>176<li><a href="#res-send-body-status-headers-status-status-">res.send()</a></li>177<li><a href="#res-redirect-url-status-">res.redirect()</a></li>More view docsTj Holowaychukbefore adoption1c8ff48
line 178why, one step back178<li><a href="#res-render-view-options-fn-">res.render()</a></li>In depth partial docsTj Holowaychukbefore adoption793943f
line 179why, one step back179<li><a href="#res-partial-view-options-">res.partial()</a></li>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 180–185why, one step back180<li><a href="#app-set-name-val-">app.set()</a></li>181<li><a href="#app-enable-name-">app.enable()</a></li>182<li><a href="#app-disable-name-">app.disable()</a></li>183<li><a href="#app-configure-env-function-function-">app.configure()</a></li>184<li><a href="#app-redirect-name-val-">app.redirect()</a></li>185<li><a href="#app-error-function-">app.error()</a></li>Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
line 186why, one step back186<li><a href="#app-helpers-obj-">app.helpers()</a></li>Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 187why, one step back187<li><a href="#app-dynamicHelpers-obj-">app.dynamicHelpers()</a></li>Rebuilt docsTj Holowaychukbefore adoptionba88e48
line 188why, one step back188<li><a href="#app-mounted-fn-">app.mounted()</a></li>Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 189why, one step back189<li><a href="#app-register-ext-exports-">app.register()</a></li>Server#listen() docsTj Holowaychukbefore adoptionf3803c4
line 190why, one step back190<li><a href="#app-listen-port-host-">app.listen()</a></li>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 191–205why, one step back191</ul>192 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 193 <p id="tagline">194 High performance, high class web development for195 <a href="http://nodejs.org">Node.js</a>196 </p>197 <ul id="menu">198 <li><a href="index.html">Home</a></li>199 <li><a href="guide.html">Guide</a></li>200 <li><a href="contrib.html">Contributing</a></li>201 <li><a href="migrate.html">1.x Migration</a></li>202 </ul>203<div class='mp'>204<h3 id="Installation">Installation</h3>205No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9
line 206why, one step back206<p>curl:</p>Error handling docsTj Holowaychukbefore adoption9fbb9fa
line 207why, one step back207Updated curl install docsTj Holowaychukbefore adoption3ceb0de
line 208why, one step back208<pre><code>$ curl -# http://expressjs.com/install.sh | shError handling docsTj Holowaychukbefore adoption9fbb9fa
lines 209–210why, one step back209</code></pre>210Updated curl install docsTj Holowaychukbefore adoption3ceb0de
line 211why, one step back211<p>npm:</p>Error handling docsTj Holowaychukbefore adoption9fbb9fa
line 212why, one step back212Added "Apps using express" section, PM me to add to the listTj Holowaychukbefore adoption7328842
line 213why, one step back213<pre><code>$ npm install expressError handling docsTj Holowaychukbefore adoption9fbb9fa
lines 214–215why, one step back214</code></pre>215Updated install docsTj Holowaychukbefore adoption193c4a9
line 216why, one step back216<p>git clone, first update the submodules:</p>Error handling docsTj Holowaychukbefore adoption9fbb9fa
line 217why, one step back217Updated install docsTj Holowaychukbefore adoption193c4a9
lines 218–220why, one step back218<pre><code>$ git submodule update --init219$ make install220$ make install-supportError handling docsTj Holowaychukbefore adoption9fbb9fa
lines 221–245why, one step back221</code></pre>222223<h3 id="Creating-An-Application">Creating An Application</h3>224225<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however226follows the same idiom by providing <em>express.createServer()</em> as shown below. This means227that you can utilize Express server's transparently with other libraries.</p>228229<pre><code>var app = require('express').createServer();230231app.get('/', function(req, res){232 res.send('hello world');233});234235app.listen(3000);236</code></pre>237238<h3 id="Configuration">Configuration</h3>239240<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers241can use the <em>configure()</em> method to setup needs required by the current environment. When242<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment243prior to the environment specific callback.</p>244245<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack tracesUpdated configuration docsTj Holowaychukbefore adoptionf8ccaa3
lines 246–248why, one step back246in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.247Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,248otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 249–250why, one step back249250<pre><code>app.configure(function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 251–252why, one step back251 app.use(express.methodOverride());252 app.use(express.bodyDecoder());Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
line 253why, one step back253 app.use(app.router);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 254why, one step back254 app.use(express.staticProvider(__dirname + '/public'));Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 255–257why, one step back255});256257app.configure('development', function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 258why, one step back258 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 259–261why, one step back259});260261app.configure('production', function(){Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 262why, one step back262 app.use(express.errorHandler());Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 263–291why, one step back263});264</code></pre>265266<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>267268<pre><code>app.configure(function(){269 app.set('views', __dirname + '/views');270 app.set('views');271 // => "... views directory ..."272273 app.enable('some feature');274 // same as app.set('some feature', true);275276 app.disable('some feature');277 // same as app.set('some feature', false);278});279</code></pre>280281<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,282or more specifically <em>EXPRESS_ENV</em>, for example:</p>283284<pre><code>$ EXPRESS_ENV=production node app.js285</code></pre>286287<h3 id="Settings">Settings</h3>288289<p>Express supports the following settings out of the box:</p>290291<ul>Updated docsTj Holowaychukbefore adoption4d32762
line 292why, one step back292<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>New "home" docsTj Holowaychukbefore adoption1e7a12f
line 293why, one step back293<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 294–295why, one step back294<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>295<li><em>view engine</em> Default view engine name for views rendered without extensions</li>Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 296–297why, one step back296<li><em>view options</em> An object specifying global view options</li>297<li><em>partials</em> Root view partials directory defaulting to <em>views</em>/partials.</li>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 298–304why, one step back298</ul>299300301<h3 id="Routing">Routing</h3>302303<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.304For example we may want to render a user's account for the path <em>/user/12</em>, thisUpdated docsTj Holowaychukbefore adoptiond691ecb
lines 305–306why, one step back305can be done by defining the route below. The values associated to the named placeholders306are available as <code>req.params</code>.</p>Error handling docsTj Holowaychukbefore adoption9fbb9fa
line 307why, one step back307Updated docsTj Holowaychukbefore adoptiond691ecb
lines 308–309why, one step back308<pre><code>app.get('/user/:id', function(req, res){309 res.send('user ' + req.params.id);Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 310–318why, one step back310});311</code></pre>312313<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example314when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>315316<pre><code>\/user\/([^\/]+)\/?317</code></pre>318Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
line 319why, one step back319<p>Regular expression literals may also be passed for complex uses. Since captureUpdated docsTj Holowaychukbefore adoptiond691ecb
line 320why, one step back320groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>.</p>Error handling docsTj Holowaychukbefore adoption9fbb9fa
line 321why, one step back321Updated docsTj Holowaychukbefore adoptiond691ecb
lines 322–323why, one step back322<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){323 res.send(req.params);Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
lines 324–336why, one step back324});325</code></pre>326327<p>Curl requests against the previously defined route:</p>328329<pre><code> $ curl http://dev:3000/user330 [null,null]331 $ curl http://dev:3000/users332 [null,null]333 $ curl http://dev:3000/users/1334 ["1",null]335 $ curl http://dev:3000/users/1..15336 ["1","15"]Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 337–372why, one step back337</code></pre>338339<p>Below are some route examples, and the associated paths that they340may consume:</p>341342<pre><code> "/user/:id"343 /user/12344345 "/users/:id?"346 /users/5347 /users348349 "/files/*"350 /files/jquery.js351 /files/javascripts/jquery.js352353 "/file/*.*"354 /files/jquery.js355 /files/javascripts/jquery.js356357 "/user/:id/:operation?"358 /user/1359 /user/1/edit360361 "/products.:format"362 /products.json363 /products.xml364365 "/products.:format?"366 /products.json367 /products.xml368 /products369</code></pre>370371<h3 id="Passing-Route-Control">Passing Route Control</h3>372Updated docsTj Holowaychukbefore adoptiond691ecb
lines 373–375why, one step back373<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,374the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,375and middleware continue to be invoked.</p>Error handling docsTj Holowaychukbefore adoption9fbb9fa
line 376why, one step back376Updated docsTj Holowaychukbefore adoptionb819366
line 377why, one step back377<pre><code>app.get('/users/:id?', function(req, res, next){Updated docsTj Holowaychukbefore adoptiond691ecb
lines 378–379why, one step back378 var id = req.params.id;379 if (id) {Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 380–385why, one step back380 // do something381 } else {382 next();383 }384});385Updated docsTj Holowaychukbefore adoptiond691ecb
line 386why, one step back386app.get('/users', function(req, res){Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 387–395why, one step back387 // do something else388});389</code></pre>390391<h3 id="Middleware">Middleware</h3>392393<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/extjs/Connect">Connect</a> can be394passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>395Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 396why, one step back396<pre><code>var express = require('express');Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 397–398why, one step back397398var app = express.createServer(Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 399–400why, one step back399 express.logger(),400 express.bodyDecoder()Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 401–405why, one step back401);402</code></pre>403404<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>405Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 406why, one step back406<pre><code>app.use(express.logger({ format: ':method :uri' }));Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 407–408why, one step back407</code></pre>408Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 409–419why, one step back409<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>410411<pre><code>var connect = require('connect');412app.use(connect.logger());413</code></pre>414415<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>416417<pre><code>app.use(express.logger());418</code></pre>419Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 420–446why, one step back420<h3 id="Error-Handling">Error Handling</h3>421422<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,423or passed to <em>next(err)</em>. Below is an example which serves different pages based on our424ad-hoc <em>NotFound</em> exception:</p>425426<pre><code>function NotFound(msg){427 this.name = 'NotFound';428 Error.call(this, msg);429 Error.captureStackTrace(this, arguments.callee);430}431432sys.inherits(NotFound, Error);433434app.get('/404', function(req, res){435 throw new NotFound;436});437438app.get('/500', function(req, res){439 throw new Error('keyboard cat!');440});441</code></pre>442443<p>We can call <em>app.error()</em> several times as shown below.444Here we check for an instanceof <em>NotFound</em> and show the445404 page, or we pass on to the next error handler.</p>446Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 447–451why, one step back447<p>Note that these handlers can be defined anywhere, as they448will be placed below the route handlers on <em>listen()</em>. This449allows for definition within <em>configure()</em> blocks so we can450handle exceptions in different ways based on the environment.</p>451Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 452–471why, one step back452<pre><code>app.error(function(err, req, res, next){453 if (err instanceof NotFound) {454 res.render('404.jade');455 } else {456 next(err);457 }458});459</code></pre>460461<p>Here we assume all errors as 500 for the simplicity of462this demo, however you can choose whatever you like</p>463464<pre><code>app.error(function(err, req, res){465 res.render('500.jade', {466 locals: {467 error: err468 } 469 });470});471</code></pre>Added more view docsTj Holowaychukbefore adoption2f96506
line 472why, one step back472More error handling docsTj Holowaychukbefore adoptioncea401c
lines 473–476why, one step back473<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware474to report on exceptions. For example if we wish to output exceptions475in "development" mode to <em>stderr</em> we can use:</p>476Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 477why, one step back477<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 478–482why, one step back478</code></pre>479480<p>Also during development we may want fancy html pages to show exceptions481that are passed or thrown, so we can set <em>showStack</em> to true:</p>482Added app.register() docsTj Holowaychukbefore adoption77e5d8e
line 483why, one step back483<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 484–488why, one step back484</code></pre>485486<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>487is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>488Added more view docsTj Holowaychukbefore adoption2f96506
lines 489–492why, one step back489<h3 id="View-Rendering">View Rendering</h3>490491<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name492of the module that will be required. For example the view <em>layout.ejs</em> willAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 493–494why, one step back493tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.render(str, options)</em> to comply with Express, however494<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.</p>Added more view docsTj Holowaychukbefore adoption2f96506
lines 495–506why, one step back495496<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,497and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as498the <em>body</em> local variable in <em>layout.haml</em>.</p>499500<pre><code>app.get('/', function(req, res){501 res.render('index.haml', {502 locals: { title: 'My Site' }503 });504});505</code></pre>506Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
lines 507–528why, one step back507<p>The new <em>view engine</em> setting allows us to specify our default template engine,508so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>509510<pre><code>app.set('view engine', 'jade');511</code></pre>512513<p>Allowing us to render with:</p>514515<pre><code>res.render('index');516</code></pre>517518<p>vs:</p>519520<pre><code>res.render('index.jade');521</code></pre>522523<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still524mix and match template engines:</p>525526<pre><code>res.render('another-page.ejs');527</code></pre>528Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 529–548why, one step back529<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>530531<pre><code>app.set('view options', {532 layout: false533});534</code></pre>535536<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>537538<pre><code>res.render('myview.ejs', { layout: true });539</code></pre>540541<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>542543<pre><code>app.set('view options', {544 open: '{{',545 close: '}}'546});547</code></pre>548Added more view docsTj Holowaychukbefore adoption2f96506
lines 549–569why, one step back549<h3 id="View-Partials">View Partials</h3>550551<p>The Express view system has built-in support for partials and collections, which are552sort of "mini" views representing a document fragment. For example rather than iterating553in a view to display comments, we would use a partial with collection support:</p>554555<pre><code>partial('comment.haml', { collection: comments });556</code></pre>557558<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,559however if we wished we could use an ejs partial, within a haml view for example.</p>560561<pre><code>partial('comment', { collection: comments });562</code></pre>563564<p>And once again even further, when rendering a collection we can simply pass565an array, if no other options are desired:</p>566567<pre><code>partial('comments', comments);568</code></pre>569Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701
lines 570–578why, one step back570<p>When using the partial collection support a few "magic" variables are provided571for free:</p>572573<ul>574<li><em>firstInCollection</em> True if this is the first object</li>575<li><em>indexInCollection</em> Index of the object in the collection</li>576<li>_lastInCollection _ True if this is the last object</li>577</ul>578Added view helper docs. Closes #344Tj Holowaychukbefore adoptionc4b5208
line 579why, one step back579Added more view docsTj Holowaychukbefore adoption2f96506
lines 580–589why, one step back580<h3 id="Template-Engines">Template Engines</h3>581582<p>Below are a few template engines commonly used with Express:</p>583584<ul>585<li><a href="http://github.com/visionmedia/jade">Jade</a> haml.js successor</li>586<li><a href="http://github.com/visionmedia/haml.js">Haml</a> indented templates</li>587<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>588</ul>589Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 590–629why, one step back590591<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>592593<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>594595<pre><code>req.header('Host');596req.header('host');597req.header('Accept', '*/*');598</code></pre>599600<h3 id="req-accepts-type-">req.accepts(type)</h3>601602<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>603604<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise605the given <em>type</em> is matched by an exact match, and then subtypes. You606may pass the subtype such as "html" which is then converted internally607to "text/html" using the mime lookup table.</p>608609<pre><code>// Accept: text/html610req.accepts('html');611// => true612613// Accept: text/*; application/json614req.accepts('html');615req.accepts('text/html');616req.accepts('text/plain');617req.accepts('application/json');618// => true619620req.accepts('image/png');621req.accepts('png');622// => false623</code></pre>624625<h3 id="req-param-name-">req.param(name)</h3>626627<p>Return the value of param <em>name</em> when present.</p>628629<ul>Updated docsTj Holowaychukbefore adoptiond691ecb
lines 630–632why, one step back630<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>631<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>632<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 633–637why, one step back633</ul>634635636<p>To utilize urlencoded request bodies, <em>req.body</em>637should be an object. This can be done by usingAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
line 638why, one step back638the <em>express.bodyDecoder</em> middleware.</p>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 639–704why, one step back639640<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>641642<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>643644<pre><code>req.flash('info', 'email sent');645req.flash('error', 'email delivery failed');646req.flash('info', 'email re-sent');647// => 2648649req.flash('info');650// => ['email sent', 'email re-sent']651652req.flash('info');653// => []654655req.flash();656// => { error: ['email delivery failed'], info: [] }657</code></pre>658659<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>660661<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header662to see if it was issued by an <em>XMLHttpRequest</em>:</p>663664<pre><code>req.xhr665req.isXMLHttpRequest666</code></pre>667668<h3 id="res-header-key-val-">res.header(key[, val])</h3>669670<p>Get or set the response header <em>key</em>.</p>671672<pre><code>res.header('Content-Length');673// => undefined674675res.header('Content-Length', 123);676// => 123677678res.header('Content-Length');679// => 123680</code></pre>681682<h3 id="res-contentType-type-">res.contentType(type)</h3>683684<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>685686<pre><code> var filename = 'path/to/image.png';687 res.contentType(filename);688 // res.headers['Content-Type'] is now "image/png"689</code></pre>690691<h3 id="res-attachment-filename-">res.attachment([filename])</h3>692693<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>694695<pre><code> res.attachment('path/to/my/image.png');696</code></pre>697698<h3 id="res-sendfile-path-">res.sendfile(path)</h3>699700<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>701702<pre><code>res.sendfile('path/to/my.file');703</code></pre>704Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1
lines 705–708why, one step back705<p>This is <em>not</em> a substitution for Connect's <em>staticProvider</em> middleware, it does not706support HTTP caching, and does not perform any security checks. This method is utilized707by <em>res.download()</em> to transfer static files, and allows you do to so from outside of708the public directory, so suitable security checks should be applied.</p>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 709–755why, one step back709710<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>711712<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>713714<pre><code>res.download('path/to/image.png');715res.download('path/to/image.png', 'foo.png');716</code></pre>717718<p>This is equivalent to:</p>719720<pre><code>res.attachment(file);721res.sendfile(file);722</code></pre>723724<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>725726<p>The <code>res.send()</code> method is a high level response utility allowing you to pass727objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status728code based responses. The following are all valid uses:</p>729730<pre><code> res.send(new Buffer('wahoo'));731 res.send({ some: 'json' });732 res.send('<p>some html</p>');733 res.send('Sorry, cant find that', 404);734 res.send('text', { 'Content-Type': 'text/plain' }, 201);735 res.send(404);736</code></pre>737738<p>By default the <em>Content-Type</em> response header is set, however if explicitly739assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>740it will not be set again.</p>741742<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>743744<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>745746<pre><code>res.redirect('/', 301);747res.redirect('/account');748res.redirect('http://google.com');749res.redirect('home');750res.redirect('back');751</code></pre>752753<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.754The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes755the "home" setting and defaults to "/".</p>More view docsTj Holowaychukbefore adoption1c8ff48
lines 756–771why, one step back756757<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>758759<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.760When a callback function is given a response will <em>not</em> be made761automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>762763<p> Most engines accept one or more of the following options,764 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>765766<ul>767<li><em>context|scope</em> Template evaluation context (<em>this</em>)</li>768<li><em>locals</em> Object containing local variables</li>769<li><em>debug</em> Output debugging information</li>770</ul>771In depth partial docsTj Holowaychukbefore adoption793943f
lines 772–819why, one step back772773<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>774775<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available776to the view as a local variable.</p>777778<ul>779<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>780781<ul>782<li>as: 'something' will add the <em>something</em> local variable</li>783<li>as: this will use the collection value as the template context</li>784<li>as: global will merge the collection value's properties with <em>locals</em></li>785</ul>786</li>787<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.788For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>789</ul>790791792<p>The following are equivalent, and the name of collection value when passed793to the partial will be <em>movie</em> as derived from the name.</p>794795<pre><code>partial('movie.jade', { collection: movies });796partial('movie.jade', movies);797partial('movie', movies);798// In view: movie.director799</code></pre>800801<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>802803<pre><code>partial('movie', { collection: movies, as: 'video' });804// In view: video.director805</code></pre>806807<p>Also we can make our movie the value of <em>this</em> within our view so that instead808of <em>movie.director</em> we could use <em>this.director</em>.</p>809810<pre><code>partial('movie', { collection: movies, as: this });811// In view: this.director812</code></pre>813814<p>Another alternative is to "explode" the properties of the collection item into815pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>816817<pre><code>partials('movie', { collection: movies, as: global });818// In view: director819</code></pre>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 820–825why, one step back820821<h3 id="app-set-name-val-">app.set(name[, val])</h3>822823<p>Apply an application level setting <em>name</em> to <em>val</em>, or824get the value of <em>name</em> when <em>val</em> is not present:</p>825Updated docsTj Holowaychukbefore adoption3234329
lines 826–828why, one step back826<pre><code>app.set('views', __dirname + '/views');827app.set('views');828// => ...path...Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 829–874why, one step back829</code></pre>830831<h3 id="app-enable-name-">app.enable(name)</h3>832833<p>Enable the given setting <em>name</em>:</p>834835<pre><code>app.enable('some arbitrary setting');836app.set('some arbitrary setting');837// => true838</code></pre>839840<h3 id="app-disable-name-">app.disable(name)</h3>841842<p>Disable the given setting <em>name</em>:</p>843844<pre><code>app.disable('some setting');845app.set('some setting');846// => false847</code></pre>848849<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>850851<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>852853<pre><code>app.configure(function(){854 // executed for each env855});856857app.configure('development', function(){858 // executed for 'development' only859});860</code></pre>861862<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>863864<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>865866<pre><code>app.redirect('google', 'http://google.com');867</code></pre>868869<p>Now in a route we may call:</p>870871<p> res.redirect('google');</p>872873<p>We may also map dynamic redirects:</p>874Updated docsTj Holowaychukbefore adoptiond691ecb
lines 875–876why, one step back875<pre><code>app.redirect('comments', function(req, res){876 return '/post/' + req.params.id + '/comments';Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 877–890why, one step back877});878</code></pre>879880<p>So now we may do the following, and the redirect will dynamically adjust to881the context of the request. If we called this route with <em>GET /post/12</em> our882redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>883884<pre><code>app.get('/post/:id', function(req, res){885 res.redirect('comments');886});887</code></pre>888889<h3 id="app-error-function-">app.error(function)</h3>890More error docsTj Holowaychukbefore adoption6227f5c
lines 891–893why, one step back891<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.892Note that we may set several error handlers by making several calls to this method, however the handler893should call <em>next(err)</em> if it does not wish to deal with the exception:</p>Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 894–897why, one step back894895<pre><code>app.error(function(err, req, res, next){896 res.send(err.message, 500);897});Server#listen() docsTj Holowaychukbefore adoptionf3803c4
line 898why, one step back898</code></pre>Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 899–901why, one step back899900<h3 id="app-helpers-obj-">app.helpers(obj)</h3>901Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 902–919why, one step back902<p>Registers static view helpers.</p>903904<pre><code>app.helpers({905 name: function(first, last){ return first + ', ' + last },906 firstName: 'tj',907 lastName: 'holowaychuk'908});909</code></pre>910911<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,912as well as the <em>name()</em> function exposed.</p>913914<pre><code><%= name(firstName, lastName) %>915</code></pre>916917<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>918919<p>Registers dynamic view helpers. Dynamic view helpersUpdated docsTj Holowaychukbefore adoptiond691ecb
line 920why, one step back920are simply functions which accept <em>req</em>, <em>res</em>, and areDocs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 921why, one step back921evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this functionAdded app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 922–923why, one step back922becomes the local variable it is associated with.</p>923Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 924why, one step back924<pre><code>app.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 925why, one step back925 session: function(req, res){Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 926–930why, one step back926 return req.session;927 }928});929</code></pre>930Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 931–933why, one step back931<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>932933<pre><code><%= session.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 934–948why, one step back934</code></pre>935936<h3 id="app-mounted-fn-">app.mounted(fn)</h3>937938<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>939940<pre><code>var app = express.createServer(),941 blog = express.createServer();942943blog.mounted(function(parent){944 // parent is app945 // "this" is blog946});947948app.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 949–976why, one step back949</code></pre>950951<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>952953<p>Register the given template engine <em>exports</em>954as <em>ext</em>. For example we may wish to map ".html"955files to jade:</p>956957<pre><code> app.register('.html', require('jade'));958</code></pre>959960<p>This is also useful for libraries that may not961match extensions correctly. For example my haml.js962library is installed from npm as "hamljs" so instead963of layout.hamljs, we can register the engine as ".haml":</p>964965<pre><code> app.register('.haml', require('haml-js'));966</code></pre>967968<p>For engines that do not comply with the Express969specification, we can also wrap their api this way.</p>970971<pre><code> app.register('.foo', {972 render: function(str, options) {973 // perhaps their api is974 // foo.toHTML(str, options);975 }976 });Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 977why, one step back977</code></pre>Server#listen() docsTj Holowaychukbefore adoptionf3803c4
lines 978–986why, one step back978979<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>980981<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all982connections will be accepted via <em>INADDR_ANY</em>.</p>983984<pre><code>app.listen();985app.listen(3000);986app.listen(3000, 'n.n.n.n');Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 987–988why, one step back987</code></pre>988Unix domain socket docsTj Holowaychukbefore adoption2fa7907
lines 989–1005why, one step back989<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>990991<pre><code>app.listen('/tmp/express.sock');992</code></pre>993994<p>Then try it out:</p>995996<pre><code>$ telnet /tmp/express.sock997GET / HTTP/1.1998999HTTP/1.1 200 OK1000Content-Type: text/plain1001Content-Length: 1110021003Hello World1004</code></pre>1005Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 1006–1010why, one step back1006</div>1007 </div>1008 </div>1009 </body>1010</html>