guide.html
This file
Path
docs/guide.html
974 lines · 30.2 KiB · HTML
Last changed by
Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
History of this fileTake it
1<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 <script>6 $(function(){7 var done;8 $(document).scroll(function(event){9 if (!done) {10 $('#toc').animate({11 top: 012 });13 }14 });15 });16 </script>17 <style>18 #header {19 position: absolute;20 top: 10px;21 left: 0;22 padding: 12px 0;23 text-indent: 40px;24 width: 100%;25 border-top: 1px solid rgba(0,0,0,0.7);26 border-bottom: 1px solid rgba(0,0,0,0.7);27 background: rgba(255,255,255,0.1) url(http://www.sencha.com/favicon.ico) no-repeat 15px 50%;28 text-align: left;29 color: #fff;30 }31 #tagline {32 margin-left: 75px;33 margin-bottom: 30px;34 color: rgba(255,255,255,0.7); }35 html {36 background: #1c1c1c url(images/bg.tile.jpg); }3738 body {39 margin: 0;40 padding-bottom: 30px;41 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";42 font-size: 14px;43 line-height: 1.5;44 -webkit-text-stroke: 1px rgba(0, 0, 0, 0.1);45 -moz-text-stroke: 1px rgba(0, 0, 0, 0.1);46 background: url(images/bg.jpg) 50% 0 no-repeat;47 color: #8b8b8b; }4849 * {50 outline: none; }5152 em {53 color: white; }5455 a img {56 border: none !important; }5758 a {59 font-weight: bold;60 text-decoration: none;61 color: white;62 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;63 -webkit-transition-duration: 0.15s;64 -webkit-transition-timing-function: ease-out; }65 a:hover {66 opacity: 0.8; }6768 h1, h2, h3 {69 margin: 45px 0 0 0;70 color: white;71 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }7273 h3 {74 font-size: 18px; }7576 pre {77 margin: 20px 10px;78 padding: 25px 20px;79 background: rgba(0,0,0,0.5);80 border: 1px solid #323232;81 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);82 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);83 -webkit-border-radius: 5px;84 -moz-border-radius: 5px; }8586 code {87 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }8889 ul {90 margin: 15px 0;91 padding: 0 0 0 35px; }92 ul li {93 margin: 0;94 padding: 2px 0;95 list-style: square; }9697 .sect {98 margin-left: 40px; }99100 #logo {101 display: block;102 margin-left: 30%;103 margin-bottom: 30px;104 width: 194px;105 height: 51px;106 background: url(images/logo.png) 0 0 no-repeat;107 text-indent: -99999px; }108 #logo:hover {109 opacity: 0.7; }110 #logo:active {111 opacity: 0.3; }112113 #ribbon {114 position: fixed;115 top: 0;116 right: 0;117 z-index: 2; }118119 #wrapper {120 width: 100%;121 min-height: 800px;122 background: url(images/top.png) 0 0 repeat-x; }123124 #container {125 margin: 0 auto;126 padding-top: 110px;127 width: 550px; }128129 #toc {130 position: fixed;131 top: 60px;132 left: 0;133 margin: 0 0 0 15px;134 padding: 15px;135 height: 100%;136 background: rgba(0,0,0,0.2);137 border-right: 1px solid rgba(255,255,255,0.05);138 }139 #toc li {140 padding: 0;141 list-style: none;142 }143 #toc li a {144 font-size: 11px;145 }146 #menu {147 margin-left: 65px;148 padding: 0;149 padding-bottom: 30px; }150 #menu li {151 display: inline;152 list-style: none; }153 #menu li a {154 display: block;155 float: left;156 margin: 0 2px;157 padding: 3px 15px;158 background: rgba(0,0,0,0.2);159 -webkit-border-radius: 8px;160 -moz-border-radius: 8px;161 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);162 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);163 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;164 -webkit-transition-duration: 0.15s;165 -webkit-transition-timing-function: ease-out; }166 #menu li a:hover,167 #menu li a.active {168 background: rgba(0,0,0,0.5); }169 #menu li a:active {170 background: rgba(0,0,0,0.1);171 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);172 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }173 </style>174 </head>175 <body>176 <a href='http://github.com/visionmedia/express'> 177 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 178 </a>179 <div id="header"><strong>Sencha</strong> labs</div>180 <div id="wrapper">181 <div id="container"><ul id="toc">182<li><a href="#Installation">Installation</a></li>183<li><a href="#Creating-An-Application">Creating An Application</a></li>184<li><a href="#Configuration">Configuration</a></li>185<li><a href="#Settings">Settings</a></li>186<li><a href="#Routing">Routing</a></li>187<li><a href="#Passing-Route-Control">Passing Route Control</a></li>188<li><a href="#Middleware">Middleware</a></li>189<li><a href="#Error-Handling">Error Handling</a></li>190<li><a href="#View-Rendering">View Rendering</a></li>191<li><a href="#View-Partials">View Partials</a></li>192<li><a href="#Template-Engines">Template Engines</a></li>193<li><a href="#req-header-key-defaultValue-">req.header()</a></li>194<li><a href="#req-accepts-type-">req.accepts()</a></li>195<li><a href="#req-param-name-">req.param()</a></li>196<li><a href="#req-flash-type-msg-">req.flash()</a></li>197<li><a href="#req-isXMLHttpRequest">req.isXMLHttpRequest</a></li>198<li><a href="#res-header-key-val-">res.header()</a></li>199<li><a href="#res-contentType-type-">res.contentType()</a></li>200<li><a href="#res-attachment-filename-">res.attachment()</a></li>201<li><a href="#res-sendfile-path-">res.sendfile()</a></li>202<li><a href="#res-download-file-filename-">res.download()</a></li>203<li><a href="#res-send-body-status-headers-status-status-">res.send()</a></li>204<li><a href="#res-redirect-url-status-">res.redirect()</a></li>205<li><a href="#res-render-view-options-fn-">res.render()</a></li>206<li><a href="#res-partial-view-options-">res.partial()</a></li>207<li><a href="#app-set-name-val-">app.set()</a></li>208<li><a href="#app-enable-name-">app.enable()</a></li>209<li><a href="#app-disable-name-">app.disable()</a></li>210<li><a href="#app-configure-env-function-function-">app.configure()</a></li>211<li><a href="#app-redirect-name-val-">app.redirect()</a></li>212<li><a href="#app-error-function-">app.error()</a></li>213<li><a href="#app-helpers-obj-">app.helpers()</a></li>214<li><a href="#app-dynamicHelpers-obj-">app.dynamicHelpers()</a></li>215<li><a href="#app-mounted-fn-">app.mounted()</a></li>216<li><a href="#app-listen-port-host-">app.listen()</a></li>217</ul>218 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 219 <p id="tagline">220 High performance, high class web development for221 <a href="http://nodejs.org">Node.js</a>222 </p>223 <ul id="menu">224 <li><a href="index.html">Home</a></li>225 <li><a href="guide.html">Guide</a></li>226 <li><a href="contrib.html">Contributing</a></li>227 <li><a href="migrate.html">1.x Migration</a></li>228 </ul>229<div class='mp'>230<h3 id="Installation">Installation</h3>231232<p>curl:</p>233234<pre><code>$ curl -# http://expressjs.com/install.sh | sh235</code></pre>236237<p>npm:</p>238239<pre><code>$ npm install connect240$ npm install express241</code></pre>242243<p>git clone, first update the submodules:</p>244245<pre><code>$ git submodule update --init246$ make install247$ make install-support248</code></pre>249250<h3 id="Creating-An-Application">Creating An Application</h3>251252<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however253follows the same idiom by providing <em>express.createServer()</em> as shown below. This means254that you can utilize Express server's transparently with other libraries.</p>255256<pre><code>var app = require('express').createServer();257258app.get('/', function(req, res){259 res.send('hello world');260});261262app.listen(3000);263</code></pre>264265<h3 id="Configuration">Configuration</h3>266267<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers268can use the <em>configure()</em> method to setup needs required by the current environment. When269<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment270prior to the environment specific callback.</p>271272<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces273in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.274Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,275otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>276277<pre><code>app.configure(function(){278 app.use(connect.methodOverride());279 app.use(connect.bodyDecoder());280 app.use(app.router);281 app.use(connect.staticProvider(__dirname + '/public'));282});283284app.configure('development', function(){285 app.use(connect.errorHandler({ dumpExceptions: true, showStack: true }));286});287288app.configure('production', function(){289 app.use(connect.errorHandler());290});291</code></pre>292293<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>294295<pre><code>app.configure(function(){296 app.set('views', __dirname + '/views');297 app.set('views');298 // => "... views directory ..."299300 app.enable('some feature');301 // same as app.set('some feature', true);302303 app.disable('some feature');304 // same as app.set('some feature', false);305});306</code></pre>307308<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,309or more specifically <em>EXPRESS_ENV</em>, for example:</p>310311<pre><code>$ EXPRESS_ENV=production node app.js312</code></pre>313314<h3 id="Settings">Settings</h3>315316<p>Express supports the following settings out of the box:</p>317318<ul>319<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>320<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>321<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>322<li><em>view engine</em> Default view engine name for views rendered without extensions</li>323<li><em>reload views</em> Reloads altered views, by default watches for <em>mtime</em> changes with324 with a 5 minute interval. Example: <em>app.set('reload views', 60000);</em></li>325</ul>326327328<h3 id="Routing">Routing</h3>329330<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.331For example we may want to render a user's account for the path <em>/user/12</em>, this332can be done by defining the route below. The values associated to the named placeholders,333are passed as the <em>third</em> argument, which here we name <em>params</em>.</p>334335<pre><code>app.get('/user/:id', function(req, res, params){336 res.send('user ' + params.id);337});338</code></pre>339340<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example341when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>342343<pre><code>\/user\/([^\/]+)\/?344</code></pre>345346<p>Regular expression literals may also be passed for complex uses. Since capture347groups with literal <em>RegExp</em>'s are anonymous we can access them directly from the <em>params</em> array.</p>348349<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res, params){350 res.send(params);351});352</code></pre>353354<p>Curl requests against the previously defined route:</p>355356<pre><code> $ curl http://dev:3000/user357 [null,null]358 $ curl http://dev:3000/users359 [null,null]360 $ curl http://dev:3000/users/1361 ["1",null]362 $ curl http://dev:3000/users/1..15363 ["1","15"]364</code></pre>365366<p>Below are some route examples, and the associated paths that they367may consume:</p>368369<pre><code> "/user/:id"370 /user/12371372 "/users/:id?"373 /users/5374 /users375376 "/files/*"377 /files/jquery.js378 /files/javascripts/jquery.js379380 "/file/*.*"381 /files/jquery.js382 /files/javascripts/jquery.js383384 "/user/:id/:operation?"385 /user/1386 /user/1/edit387388 "/products.:format"389 /products.json390 /products.xml391392 "/products.:format?"393 /products.json394 /products.xml395 /products396</code></pre>397398<h3 id="Passing-Route-Control">Passing Route Control</h3>399400<p>We may pass control to the next <em>matching</em> route, by calling the <em>fourth</em> parameter,401the <em>next()</em> function. When a match cannot be made, control is passed back to Connect.</p>402403<pre><code>app.get('/users/:id?', function(req, res, params){404 if (params.id) {405 // do something406 } else {407 next();408 }409});410411app.get('/users', function(req, res, params){412 // do something else413});414</code></pre>415416<h3 id="Middleware">Middleware</h3>417418<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/extjs/Connect">Connect</a> can be419passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>420421<pre><code>var connect = require('connect'),422 express = require('express');423424var app = express.createServer(425 connect.logger(),426 connect.bodyDecoder()427);428</code></pre>429430<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>431432<pre><code>app.use(connect.logger({ format: ':method :uri' }));433</code></pre>434435<h3 id="Error-Handling">Error Handling</h3>436437<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,438or passed to <em>next(err)</em>. Below is an example which serves different pages based on our439ad-hoc <em>NotFound</em> exception:</p>440441<pre><code>function NotFound(msg){442 this.name = 'NotFound';443 Error.call(this, msg);444 Error.captureStackTrace(this, arguments.callee);445}446447sys.inherits(NotFound, Error);448449app.get('/404', function(req, res){450 throw new NotFound;451});452453app.get('/500', function(req, res){454 throw new Error('keyboard cat!');455});456</code></pre>457458<p>We can call <em>app.error()</em> several times as shown below.459Here we check for an instanceof <em>NotFound</em> and show the460404 page, or we pass on to the next error handler.</p>461462<pre><code>app.error(function(err, req, res, next){463 if (err instanceof NotFound) {464 res.render('404.jade');465 } else {466 next(err);467 }468});469</code></pre>470471<p>Here we assume all errors as 500 for the simplicity of472this demo, however you can choose whatever you like</p>473474<pre><code>app.error(function(err, req, res){475 res.render('500.jade', {476 locals: {477 error: err478 } 479 });480});481</code></pre>482483<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware484to report on exceptions. For example if we wish to output exceptions485in "development" mode to <em>stderr</em> we can use:</p>486487<pre><code>app.use(connect.errorHandler({ dumpExceptions: true }));488</code></pre>489490<p>Also during development we may want fancy html pages to show exceptions491that are passed or thrown, so we can set <em>showStack</em> to true:</p>492493<pre><code>app.use(connect.errorHandler({ showStack: true, dumpExceptions: true }));494</code></pre>495496<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>497is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>498499<h3 id="View-Rendering">View Rendering</h3>500501<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name502of the module that will be required. For example the view <em>layout.ejs</em> will503tell the view system to <em>require('ejs')</em>, the module being loaded must (currently)504export the method <em>exports.render(str, options)</em> to comply with Express, however505with will likely be extensible in the future.</p>506507<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,508and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as509the <em>body</em> local variable in <em>layout.haml</em>.</p>510511<pre><code>app.get('/', function(req, res){512 res.render('index.haml', {513 locals: { title: 'My Site' }514 });515});516</code></pre>517518<p>The new <em>view engine</em> setting allows us to specify our default template engine,519so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>520521<pre><code>app.set('view engine', 'jade');522</code></pre>523524<p>Allowing us to render with:</p>525526<pre><code>res.render('index');527</code></pre>528529<p>vs:</p>530531<pre><code>res.render('index.jade');532</code></pre>533534<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still535mix and match template engines:</p>536537<pre><code>res.render('another-page.ejs');538</code></pre>539540<h3 id="View-Partials">View Partials</h3>541542<p>The Express view system has built-in support for partials and collections, which are543sort of "mini" views representing a document fragment. For example rather than iterating544in a view to display comments, we would use a partial with collection support:</p>545546<pre><code>partial('comment.haml', { collection: comments });547</code></pre>548549<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,550however if we wished we could use an ejs partial, within a haml view for example.</p>551552<pre><code>partial('comment', { collection: comments });553</code></pre>554555<p>And once again even further, when rendering a collection we can simply pass556an array, if no other options are desired:</p>557558<pre><code>partial('comments', comments);559</code></pre>560561<p>When using the partial collection support a few "magic" variables are provided562for free:</p>563564<ul>565<li><em>firstInCollection</em> True if this is the first object</li>566<li><em>indexInCollection</em> Index of the object in the collection</li>567<li>_lastInCollection _ True if this is the last object</li>568</ul>569570571<h3 id="Template-Engines">Template Engines</h3>572573<p>Below are a few template engines commonly used with Express:</p>574575<ul>576<li><a href="http://github.com/visionmedia/jade">Jade</a> haml.js successor</li>577<li><a href="http://github.com/visionmedia/haml.js">Haml</a> indented templates</li>578<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>579</ul>580581582<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>583584<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>585586<pre><code>req.header('Host');587req.header('host');588req.header('Accept', '*/*');589</code></pre>590591<h3 id="req-accepts-type-">req.accepts(type)</h3>592593<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>594595<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise596the given <em>type</em> is matched by an exact match, and then subtypes. You597may pass the subtype such as "html" which is then converted internally598to "text/html" using the mime lookup table.</p>599600<pre><code>// Accept: text/html601req.accepts('html');602// => true603604// Accept: text/*; application/json605req.accepts('html');606req.accepts('text/html');607req.accepts('text/plain');608req.accepts('application/json');609// => true610611req.accepts('image/png');612req.accepts('png');613// => false614</code></pre>615616<h3 id="req-param-name-">req.param(name)</h3>617618<p>Return the value of param <em>name</em> when present.</p>619620<ul>621<li>Checks route placeholders, ex: /user/:id</li>622<li>Checks query string params, ex: ?id=12</li>623<li>Checks urlencoded body params, ex: id=12</li>624</ul>625626627<p>To utilize urlencoded request bodies, <em>req.body</em>628should be an object. This can be done by using629the <em>connect.bodyDecoder</em> middleware.</p>630631<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>632633<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>634635<pre><code>req.flash('info', 'email sent');636req.flash('error', 'email delivery failed');637req.flash('info', 'email re-sent');638// => 2639640req.flash('info');641// => ['email sent', 'email re-sent']642643req.flash('info');644// => []645646req.flash();647// => { error: ['email delivery failed'], info: [] }648</code></pre>649650<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>651652<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header653to see if it was issued by an <em>XMLHttpRequest</em>:</p>654655<pre><code>req.xhr656req.isXMLHttpRequest657</code></pre>658659<h3 id="res-header-key-val-">res.header(key[, val])</h3>660661<p>Get or set the response header <em>key</em>.</p>662663<pre><code>res.header('Content-Length');664// => undefined665666res.header('Content-Length', 123);667// => 123668669res.header('Content-Length');670// => 123671</code></pre>672673<h3 id="res-contentType-type-">res.contentType(type)</h3>674675<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>676677<pre><code> var filename = 'path/to/image.png';678 res.contentType(filename);679 // res.headers['Content-Type'] is now "image/png"680</code></pre>681682<h3 id="res-attachment-filename-">res.attachment([filename])</h3>683684<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>685686<pre><code> res.attachment('path/to/my/image.png');687</code></pre>688689<h3 id="res-sendfile-path-">res.sendfile(path)</h3>690691<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>692693<pre><code>res.sendfile('path/to/my.file');694</code></pre>695696<p>This is <em>not</em> a substitution for Connect's <em>staticProvider</em> middleware, it does not697support HTTP caching, and does not perform any security checks. This method is utilized698by <em>res.download()</em> to transfer static files, and allows you do to so from outside of699the public directory, so suitable security checks should be applied.</p>700701<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>702703<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>704705<pre><code>res.download('path/to/image.png');706res.download('path/to/image.png', 'foo.png');707</code></pre>708709<p>This is equivalent to:</p>710711<pre><code>res.attachment(file);712res.sendfile(file);713</code></pre>714715<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>716717<p>The <code>res.send()</code> method is a high level response utility allowing you to pass718objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status719code based responses. The following are all valid uses:</p>720721<pre><code> res.send(new Buffer('wahoo'));722 res.send({ some: 'json' });723 res.send('<p>some html</p>');724 res.send('Sorry, cant find that', 404);725 res.send('text', { 'Content-Type': 'text/plain' }, 201);726 res.send(404);727</code></pre>728729<p>By default the <em>Content-Type</em> response header is set, however if explicitly730assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>731it will not be set again.</p>732733<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>734735<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>736737<pre><code>res.redirect('/', 301);738res.redirect('/account');739res.redirect('http://google.com');740res.redirect('home');741res.redirect('back');742</code></pre>743744<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.745The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes746the "home" setting and defaults to "/".</p>747748<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>749750<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.751When a callback function is given a response will <em>not</em> be made752automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>753754<p> Most engines accept one or more of the following options,755 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>756757<ul>758<li><em>context|scope</em> Template evaluation context (<em>this</em>)</li>759<li><em>locals</em> Object containing local variables</li>760<li><em>cache</em> Cache intermediate JavaScript in memory (the default in <em>production</em> mode)</li>761<li><em>debug</em> Output debugging information</li>762</ul>763764765<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>766767<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available768to the view as a local variable.</p>769770<ul>771<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>772773<ul>774<li>as: 'something' will add the <em>something</em> local variable</li>775<li>as: this will use the collection value as the template context</li>776<li>as: global will merge the collection value's properties with <em>locals</em></li>777</ul>778</li>779<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.780For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>781</ul>782783784<p>The following are equivalent, and the name of collection value when passed785to the partial will be <em>movie</em> as derived from the name.</p>786787<pre><code>partial('movie.jade', { collection: movies });788partial('movie.jade', movies);789partial('movie', movies);790// In view: movie.director791</code></pre>792793<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>794795<pre><code>partial('movie', { collection: movies, as: 'video' });796// In view: video.director797</code></pre>798799<p>Also we can make our movie the value of <em>this</em> within our view so that instead800of <em>movie.director</em> we could use <em>this.director</em>.</p>801802<pre><code>partial('movie', { collection: movies, as: this });803// In view: this.director804</code></pre>805806<p>Another alternative is to "explode" the properties of the collection item into807pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>808809<pre><code>partials('movie', { collection: movies, as: global });810// In view: director811</code></pre>812813<h3 id="app-set-name-val-">app.set(name[, val])</h3>814815<p>Apply an application level setting <em>name</em> to <em>val</em>, or816get the value of <em>name</em> when <em>val</em> is not present:</p>817818<pre><code>app.set('reload views', 200);819app.set('reload views');820// => 200821</code></pre>822823<h3 id="app-enable-name-">app.enable(name)</h3>824825<p>Enable the given setting <em>name</em>:</p>826827<pre><code>app.enable('some arbitrary setting');828app.set('some arbitrary setting');829// => true830</code></pre>831832<h3 id="app-disable-name-">app.disable(name)</h3>833834<p>Disable the given setting <em>name</em>:</p>835836<pre><code>app.disable('some setting');837app.set('some setting');838// => false839</code></pre>840841<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>842843<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>844845<pre><code>app.configure(function(){846 // executed for each env847});848849app.configure('development', function(){850 // executed for 'development' only851});852</code></pre>853854<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>855856<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>857858<pre><code>app.redirect('google', 'http://google.com');859</code></pre>860861<p>Now in a route we may call:</p>862863<p> res.redirect('google');</p>864865<p>We may also map dynamic redirects:</p>866867<pre><code>app.redirect('comments', function(req, res, params){868 return '/post/' + params.id + '/comments';869});870</code></pre>871872<p>So now we may do the following, and the redirect will dynamically adjust to873the context of the request. If we called this route with <em>GET /post/12</em> our874redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>875876<pre><code>app.get('/post/:id', function(req, res){877 res.redirect('comments');878});879</code></pre>880881<h3 id="app-error-function-">app.error(function)</h3>882883<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.884Note that we may set several error handlers by making several calls to this method, however the handler885should call <em>next(err)</em> if it does not wish to deal with the exception:</p>886887<pre><code>app.error(function(err, req, res, next){888 res.send(err.message, 500);889});890</code></pre>891892<h3 id="app-helpers-obj-">app.helpers(obj)</h3>893894<p>Registers static view helpers.</p>895896<pre><code>app.helpers({897 name: function(first, last){ return first + ', ' + last },898 firstName: 'tj',899 lastName: 'holowaychuk'900});901</code></pre>902903<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,904as well as the <em>name()</em> function exposed.</p>905906<pre><code><%= name(firstName, lastName) %>907</code></pre>908909<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>910911<p>Registers dynamic view helpers. Dynamic view helpers912are simply functions which accept <em>req</em>, <em>res</em>, and <em>params</em>, and are913evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function914becomes the local variable it is associated with.</p>915916<pre><code>app.dynamicHelpers({917 session: function(req, res, params){918 return req.session;919 }920});921</code></pre>922923<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>924925<pre><code><%= session.name %>926</code></pre>927928<h3 id="app-mounted-fn-">app.mounted(fn)</h3>929930<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>931932<pre><code>var app = express.createServer(),933 blog = express.createServer();934935blog.mounted(function(parent){936 // parent is app937 // "this" is blog938});939940app.use(blog);941</code></pre>942943<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>944945<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all946connections will be accepted via <em>INADDR_ANY</em>.</p>947948<pre><code>app.listen();949app.listen(3000);950app.listen(3000, 'n.n.n.n');951</code></pre>952953<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>954955<pre><code>app.listen('/tmp/express.sock');956</code></pre>957958<p>Then try it out:</p>959960<pre><code>$ telnet /tmp/express.sock961GET / HTTP/1.1962963HTTP/1.1 200 OK964Content-Type: text/plain965Content-Length: 11966967Hello World968</code></pre>969970</div>971 </div>972 </div>973 </body>974</html>