Skip to content
Myr

guide.html

This file

Path

docs/guide.html

926 lines · 28.7 KiB · HTML

Last changed by

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

History of this file

Take it

1<html>2	<head>3		<title>Express - node web framework</title>4		<style>5		    #header {6				position: absolute;7				top: 10px;8				left: 0;9		        padding: 12px 0;10				text-indent: 40px;11				width: 100%;12		        border-top: 1px solid rgba(0,0,0,0.7);13		        border-bottom: 1px solid rgba(0,0,0,0.7);14		        background: rgba(255,255,255,0.1) url(http://www.sencha.com/favicon.ico) no-repeat 15px 50%;15				text-align: left;16				color: #fff;17		    }18			#tagline {19			  margin-left: 75px;20			  margin-bottom: 30px;21			  color: rgba(255,255,255,0.7); }22			html {23			  background: #1c1c1c url(images/bg.tile.jpg); }2425			body {26			  margin: 0;27			  padding-bottom: 30px;28			  font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";29			  font-size: 14px;30			  line-height: 1.5;31			  -webkit-text-stroke: 1px rgba(0, 0, 0, 0.1);32			  -moz-text-stroke: 1px rgba(0, 0, 0, 0.1);33			  background: url(images/bg.jpg) 50% 0 no-repeat;34			  color: #8b8b8b; }3536			* {37			  outline: none; }3839			em {40			  color: white; }4142			a img {43			  border: none !important; }4445			a {46			  font-weight: bold;47			  text-decoration: none;48			  color: white;49			  -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;50			  -webkit-transition-duration: 0.15s;51			  -webkit-transition-timing-function: ease-out; }52			  a:hover {53			    opacity: 0.8; }5455			h1, h2, h3 {56			  margin: 45px 0 0 0;57			  color: white;58			  text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }5960			h3 {61			  font-size: 18px; }6263			pre {64			  margin: 20px 10px;65			  padding: 25px 20px;66			  background: rgba(0,0,0,0.5);67			  border: 1px solid #323232;68			  -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);69			  -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);70			  -webkit-border-radius: 5px;71			  -moz-border-radius: 5px; }7273			code {74			  font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }7576			ul {77			  margin: 15px 0;78			  padding: 0 0 0 35px; }79			  ul li {80			    margin: 0;81			    padding: 2px 0;82			    list-style: square; }8384			.sect {85			  margin-left: 40px; }8687			#logo {88			  display: block;89			  margin-left: 30%;90			  margin-bottom: 30px;91			  width: 194px;92			  height: 51px;93			  background: url(images/logo.png) 0 0 no-repeat;94			  text-indent: -99999px; }95			  #logo:hover {96			    opacity: 0.7; }97			  #logo:active {98			    opacity: 0.3; }99100			#ribbon {101			  position: fixed;102			  top: 0;103			  right: 0;104			  z-index: 2; }105106			#wrapper {107			  width: 100%;108			  min-height: 800px;109			  background: url(images/top.png) 0 0 repeat-x; }110111			#container {112			  margin: 0 auto;113			  padding-top: 110px;114			  width: 550px; }115116			#toc {117				position: fixed;118				top: 60px;119				left: 0;120				margin: 0 0 0 15px;121				padding: 15px;122				height: 100%;123				background: rgba(0,0,0,0.2);124				border-right: 1px solid rgba(255,255,255,0.05);125			}126			#toc li {127				padding: 0;128				list-style: none;129			}130			#toc li a {131				font-size: 11px;132			}133			#menu {134			  margin-left: 65px;135			  padding: 0;136			  padding-bottom: 30px; }137			  #menu li {138			    display: inline;139			    list-style: none; }140			    #menu li a {141			      display: block;142			      float: left;143			      margin: 0 2px;144			      padding: 3px 15px;145			      background: rgba(0,0,0,0.2);146			      -webkit-border-radius: 8px;147			      -moz-border-radius: 8px;148			      -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);149			      -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);150			      -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;151			      -webkit-transition-duration: 0.15s;152			      -webkit-transition-timing-function: ease-out; }153			      #menu li a:hover,154			      #menu li a.active {155			        background: rgba(0,0,0,0.5); }156			      #menu li a:active {157			        background: rgba(0,0,0,0.1);158			        -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);159			        -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }160		</style>161	</head>162	<body>163		<a href='http://github.com/visionmedia/express'> 164		  <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 165		</a>166		<div id="header"><strong>Sencha</strong> labs</div>167		<div id="wrapper">168			<div id="container"><ul id="toc">169<li><a href="#Installation">Installation</a></li>170<li><a href="#Creating-An-Application">Creating An Application</a></li>171<li><a href="#Configuration">Configuration</a></li>172<li><a href="#Settings">Settings</a></li>173<li><a href="#Routing">Routing</a></li>174<li><a href="#Passing-Route-Control">Passing Route Control</a></li>175<li><a href="#Middleware">Middleware</a></li>176<li><a href="#Error-Handling">Error Handling</a></li>177<li><a href="#View-Rendering">View Rendering</a></li>178<li><a href="#View-Partials">View Partials</a></li>179<li><a href="#Template-Engines">Template Engines</a></li>180<li><a href="#req-header-key-defaultValue-">req.header()</a></li>181<li><a href="#req-accepts-type-">req.accepts()</a></li>182<li><a href="#req-param-name-">req.param()</a></li>183<li><a href="#req-flash-type-msg-">req.flash()</a></li>184<li><a href="#req-isXMLHttpRequest">req.isXMLHttpRequest</a></li>185<li><a href="#res-header-key-val-">res.header()</a></li>186<li><a href="#res-contentType-type-">res.contentType()</a></li>187<li><a href="#res-attachment-filename-">res.attachment()</a></li>188<li><a href="#res-sendfile-path-">res.sendfile()</a></li>189<li><a href="#res-download-file-filename-">res.download()</a></li>190<li><a href="#res-send-body-status-headers-status-status-">res.send()</a></li>191<li><a href="#res-redirect-url-status-">res.redirect()</a></li>192<li><a href="#res-render-view-options-fn-">res.render()</a></li>193<li><a href="#res-partial-view-options-">res.partial()</a></li>194<li><a href="#app-set-name-val-">app.set()</a></li>195<li><a href="#app-enable-name-">app.enable()</a></li>196<li><a href="#app-disable-name-">app.disable()</a></li>197<li><a href="#app-configure-env-function-function-">app.configure()</a></li>198<li><a href="#app-redirect-name-val-">app.redirect()</a></li>199<li><a href="#app-error-function-">app.error()</a></li>200<li><a href="#app-helpers-obj-">app.helpers()</a></li>201<li><a href="#app-dynamicHelpers-obj-">app.dynamicHelpers()</a></li>202<li><a href="#app-listen-port-host-">app.listen()</a></li>203</ul>204				<a href='http://github.com/visionmedia/express' id='logo'>Express</a> 205				<p id="tagline">206				   High performance, high class web development for207				  <a href="http://nodejs.org">Node.js</a>208				</p>209				<ul id="menu">210					<li><a href="index.html">Home</a></li>211					<li><a href="guide.html">Guide</a></li>212					<li><a href="contrib.html">Contributing</a></li>213					<li><a href="migrate.html">1.x Migration</a></li>214				</ul>215<div class='mp'>216<h3 id="Installation">Installation</h3>217218<p>curl (or similar):</p>219220<pre><code>$ curl -# http://expressjs.com/install.sh | sh221</code></pre>222223<p>npm:</p>224225<pre><code>$ npm install connect226$ npm install express227</code></pre>228229<p>git clone, first update the submodules:</p>230231<pre><code>$ git submodule update --init232$ make install233$ make install-support234</code></pre>235236<h3 id="Creating-An-Application">Creating An Application</h3>237238<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however239follows the same idiom by providing <em>express.createServer()</em> as shown below. This means240that you can utilize Express server's transparently with other libraries.</p>241242<pre><code>var app = require('express').createServer();243244app.get('/', function(req, res){245    res.send('hello world');246});247248app.listen(3000);249</code></pre>250251<h3 id="Configuration">Configuration</h3>252253<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers254can use the <em>configure()</em> method to setup needs required by the current environment. When255<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment256prior to the environment specific callback.</p>257258<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces259in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.</p>260261<pre><code>app.configure(function(){262    app.use(connect.methodOverride());263    app.use(connect.bodyDecoder());264});265266app.configure('development', function(){267    app.use(connect.errorHandler({ dumpExceptions: true, showStack: true }));268});269270app.configure('production', function(){271    app.use(connect.errorHandler());272});273</code></pre>274275<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>276277<pre><code>app.configure(function(){278    app.set('views', __dirname + '/views');279    app.set('views');280    // =&gt; "... views directory ..."281282    app.enable('some feature');283    // same as app.set('some feature', true);284285    app.disable('some feature');286    // same as app.set('some feature', false);287});288</code></pre>289290<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,291or more specifically <em>EXPRESS_ENV</em>, for example:</p>292293<pre><code>$ EXPRESS_ENV=production node app.js294</code></pre>295296<h3 id="Settings">Settings</h3>297298<p>Express supports the following settings out of the box:</p>299300<ul>301<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> to utilize</li>302<li><em>home</em> Application base path used with <em>res.redirect()</em></li>303<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>304<li><em>view engine</em> Default view engine name for views rendered without extensions</li>305<li><em>reload views</em> Reloads altered views, by default watches for <em>mtime</em> changes with306  with a 5 minute interval. Example: <em>app.set('reload views', 60000);</em></li>307</ul>308309310<h3 id="Routing">Routing</h3>311312<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.313For example we may want to render a user's account for the path <em>/user/12</em>, this314can be done by defining the route below. The values associated to the named placeholders,315are passed as the <em>third</em> argument, which here we name <em>params</em>.</p>316317<pre><code>app.get('/user/:id', function(req, res, params){318    res.send('user ' + params.id);319});320</code></pre>321322<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example323when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>324325<pre><code>\/user\/([^\/]+)\/?326</code></pre>327328<p>Literal regular expressions may also be passed for complex uses:</p>329330<pre><code>app.get(/^\/foo(bar)?$/, function(){});331</code></pre>332333<p>Below are some route examples, and the associated paths that they334may consume:</p>335336<pre><code> "/user/:id"337 /user/12338339 "/users/:id?"340 /users/5341 /users342343 "/files/*"344 /files/jquery.js345 /files/javascripts/jquery.js346347 "/file/*.*"348 /files/jquery.js349 /files/javascripts/jquery.js350351 "/user/:id/:operation?"352 /user/1353 /user/1/edit354355 "/products.:format"356 /products.json357 /products.xml358359 "/products.:format?"360 /products.json361 /products.xml362 /products363</code></pre>364365<h3 id="Passing-Route-Control">Passing Route Control</h3>366367<p>We may pass control to the next <em>matching</em> route, by calling the <em>fourth</em> parameter,368the <em>next()</em> function. When a match cannot be made, control is passed back to Connect.</p>369370<pre><code>app.get('/users/:id?', function(req, res, params){371    if (params.id) {372        // do something373    } else {374        next();375    }376});377378app.get('/users', function(req, res, params){379    // do something else380});381</code></pre>382383<h3 id="Middleware">Middleware</h3>384385<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/extjs/Connect">Connect</a> can be386passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>387388<pre><code>var connect = require('connect'),389    express = require('express');390391var app = express.createServer(392    connect.logger(),393    connect.bodyDecoder()394);395</code></pre>396397<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>398399<pre><code>app.use(connect.logger({ format: ':method :uri' }));400</code></pre>401402<h3 id="Error-Handling">Error Handling</h3>403404<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,405or passed to <em>next(err)</em>. Below is an example which serves different pages based on our406ad-hoc <em>NotFound</em> exception:</p>407408<pre><code>function NotFound(msg){409    this.name = 'NotFound';410    Error.call(this, msg);411    Error.captureStackTrace(this, arguments.callee);412}413414sys.inherits(NotFound, Error);415416app.get('/404', function(req, res){417    throw new NotFound;418});419420app.get('/500', function(req, res){421    throw new Error('keyboard cat!');422});423</code></pre>424425<p>We can call <em>app.error()</em> several times as shown below.426Here we check for an instanceof <em>NotFound</em> and show the427404 page, or we pass on to the next error handler.</p>428429<pre><code>app.error(function(err, req, res, next){430    if (err instanceof NotFound) {431        res.render('404.jade');432    } else {433        next(err);434    }435});436</code></pre>437438<p>Here we assume all errors as 500 for the simplicity of439this demo, however you can choose whatever you like</p>440441<pre><code>app.error(function(err, req, res){442    res.render('500.jade', {443       locals: {444           error: err445       } 446    });447});448</code></pre>449450<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware451to report on exceptions. For example if we wish to output exceptions452in "development" mode to <em>stderr</em> we can use:</p>453454<pre><code>app.use(connect.errorHandler({ dumpExceptions: true }));455</code></pre>456457<p>Also during development we may want fancy html pages to show exceptions458that are passed or thrown, so we can set <em>showStack</em> to true:</p>459460<pre><code>app.use(connect.errorHandler({ showStack: true, dumpExceptions: true }));461</code></pre>462463<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>464is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>465466<h3 id="View-Rendering">View Rendering</h3>467468<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name469of the module that will be required. For example the view <em>layout.ejs</em> will470tell the view system to <em>require('ejs')</em>, the module being loaded must (currently)471export the method <em>exports.render(str, options)</em> to comply with Express, however472with will likely be extensible in the future.</p>473474<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,475and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as476the <em>body</em> local variable in <em>layout.haml</em>.</p>477478<pre><code>app.get('/', function(req, res){479    res.render('index.haml', {480        locals: { title: 'My Site' }481    });482});483</code></pre>484485<p>The new <em>view engine</em> setting allows us to specify our default template engine,486so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>487488<pre><code>app.set('view engine', 'jade');489</code></pre>490491<p>Allowing us to render with:</p>492493<pre><code>res.render('index');494</code></pre>495496<p>vs:</p>497498<pre><code>res.render('index.jade');499</code></pre>500501<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still502mix and match template engines:</p>503504<pre><code>res.render('another-page.ejs');505</code></pre>506507<h3 id="View-Partials">View Partials</h3>508509<p>The Express view system has built-in support for partials and collections, which are510sort of "mini" views representing a document fragment. For example rather than iterating511in a view to display comments, we would use a partial with collection support:</p>512513<pre><code>partial('comment.haml', { collection: comments });514</code></pre>515516<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,517however if we wished we could use an ejs partial, within a haml view for example.</p>518519<pre><code>partial('comment', { collection: comments });520</code></pre>521522<p>And once again even further, when rendering a collection we can simply pass523an array, if no other options are desired:</p>524525<pre><code>partial('comments', comments);526</code></pre>527528<p>When using the partial collection support a few "magic" variables are provided529for free:</p>530531<ul>532<li><em>firstInCollection</em>  True if this is the first object</li>533<li><em>indexInCollection</em>  Index of the object in the collection</li>534<li>_lastInCollection _  True if this is the last object</li>535</ul>536537538<h3 id="Template-Engines">Template Engines</h3>539540<p>Below are a few template engines commonly used with Express:</p>541542<ul>543<li><a href="http://github.com/visionmedia/jade">Jade</a> haml.js successor</li>544<li><a href="http://github.com/visionmedia/haml.js">Haml</a> indented templates</li>545<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>546</ul>547548549<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>550551<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>552553<pre><code>req.header('Host');554req.header('host');555req.header('Accept', '*/*');556</code></pre>557558<h3 id="req-accepts-type-">req.accepts(type)</h3>559560<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>561562<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise563the given <em>type</em> is matched by an exact match, and then subtypes. You564may pass the subtype such as "html" which is then converted internally565to "text/html" using the mime lookup table.</p>566567<pre><code>// Accept: text/html568req.accepts('html');569// =&gt; true570571// Accept: text/*; application/json572req.accepts('html');573req.accepts('text/html');574req.accepts('text/plain');575req.accepts('application/json');576// =&gt; true577578req.accepts('image/png');579req.accepts('png');580// =&gt; false581</code></pre>582583<h3 id="req-param-name-">req.param(name)</h3>584585<p>Return the value of param <em>name</em> when present.</p>586587<ul>588<li>Checks route placeholders, ex: /user/:id</li>589<li>Checks query string params, ex: ?id=12</li>590<li>Checks urlencoded body params, ex: id=12</li>591</ul>592593594<p>To utilize urlencoded request bodies, <em>req.body</em>595should be an object. This can be done by using596the <em>connect.bodyDecoder</em> middleware.</p>597598<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>599600<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>601602<pre><code>req.flash('info', 'email sent');603req.flash('error', 'email delivery failed');604req.flash('info', 'email re-sent');605// =&gt; 2606607req.flash('info');608// =&gt; ['email sent', 'email re-sent']609610req.flash('info');611// =&gt; []612613req.flash();614// =&gt; { error: ['email delivery failed'], info: [] }615</code></pre>616617<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>618619<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header620to see if it was issued by an <em>XMLHttpRequest</em>:</p>621622<pre><code>req.xhr623req.isXMLHttpRequest624</code></pre>625626<h3 id="res-header-key-val-">res.header(key[, val])</h3>627628<p>Get or set the response header <em>key</em>.</p>629630<pre><code>res.header('Content-Length');631// =&gt; undefined632633res.header('Content-Length', 123);634// =&gt; 123635636res.header('Content-Length');637// =&gt; 123638</code></pre>639640<h3 id="res-contentType-type-">res.contentType(type)</h3>641642<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>643644<pre><code>  var filename = 'path/to/image.png';645  res.contentType(filename);646  // res.headers['Content-Type'] is now "image/png"647</code></pre>648649<h3 id="res-attachment-filename-">res.attachment([filename])</h3>650651<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>652653<pre><code>  res.attachment('path/to/my/image.png');654</code></pre>655656<h3 id="res-sendfile-path-">res.sendfile(path)</h3>657658<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>659660<pre><code>res.sendfile('path/to/my.file');661</code></pre>662663<p>This is <em>not</em> a substitution for Connect's <em>staticProvider</em> middleware, it does not664support HTTP caching, and does not perform any security checks. This method is utilized665by <em>res.download()</em> to transfer static files, and allows you do to so from outside of666the public directory, so suitable security checks should be applied.</p>667668<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>669670<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>671672<pre><code>res.download('path/to/image.png');673res.download('path/to/image.png', 'foo.png');674</code></pre>675676<p>This is equivalent to:</p>677678<pre><code>res.attachment(file);679res.sendfile(file);680</code></pre>681682<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>683684<p>The <code>res.send()</code> method is a high level response utility allowing you to pass685objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status686code based responses. The following are all valid uses:</p>687688<pre><code> res.send(new Buffer('wahoo'));689 res.send({ some: 'json' });690 res.send('&lt;p&gt;some html&lt;/p&gt;');691 res.send('Sorry, cant find that', 404);692 res.send('text', { 'Content-Type': 'text/plain' }, 201);693 res.send(404);694</code></pre>695696<p>By default the <em>Content-Type</em> response header is set, however if explicitly697assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>698it will not be set again.</p>699700<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>701702<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>703704<pre><code>res.redirect('/', 301);705res.redirect('/account');706res.redirect('http://google.com');707res.redirect('home');708res.redirect('back');709</code></pre>710711<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.712The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes713the "home" setting and defaults to "/".</p>714715<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>716717<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.718When a callback function is given a response will <em>not</em> be made719automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>720721<p> Most engines accept one or more of the following options,722 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>723724<ul>725<li><em>context|scope</em>   Template evaluation context (<em>this</em>)</li>726<li><em>locals</em>          Object containing local variables</li>727<li><em>cache</em>           Cache intermediate JavaScript in memory (the default in <em>production</em> mode)</li>728<li><em>debug</em>           Output debugging information</li>729</ul>730731732<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>733734<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available735to the view as a local variable.</p>736737<ul>738<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>739740<ul>741<li>as: 'something' will add the <em>something</em> local variable</li>742<li>as: this will use the collection value as the template context</li>743<li>as: global will merge the collection value's properties with <em>locals</em></li>744</ul>745</li>746<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.747For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>748</ul>749750751<p>The following are equivalent, and the name of collection value when passed752to the partial will be <em>movie</em> as derived from the name.</p>753754<pre><code>partial('movie.jade', { collection: movies });755partial('movie.jade', movies);756partial('movie', movies);757// In view: movie.director758</code></pre>759760<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>761762<pre><code>partial('movie', { collection: movies, as: 'video' });763// In view: video.director764</code></pre>765766<p>Also we can make our movie the value of <em>this</em> within our view so that instead767of <em>movie.director</em> we could use <em>this.director</em>.</p>768769<pre><code>partial('movie', { collection: movies, as: this });770// In view: this.director771</code></pre>772773<p>Another alternative is to "explode" the properties of the collection item into774pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>775776<pre><code>partials('movie', { collection: movies, as: global });777// In view: director778</code></pre>779780<h3 id="app-set-name-val-">app.set(name[, val])</h3>781782<p>Apply an application level setting <em>name</em> to <em>val</em>, or783get the value of <em>name</em> when <em>val</em> is not present:</p>784785<pre><code>app.set('reload views', 200);786app.set('reload views');787// =&gt; 200788</code></pre>789790<h3 id="app-enable-name-">app.enable(name)</h3>791792<p>Enable the given setting <em>name</em>:</p>793794<pre><code>app.enable('some arbitrary setting');795app.set('some arbitrary setting');796// =&gt; true797</code></pre>798799<h3 id="app-disable-name-">app.disable(name)</h3>800801<p>Disable the given setting <em>name</em>:</p>802803<pre><code>app.disable('some setting');804app.set('some setting');805// =&gt; false806</code></pre>807808<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>809810<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>811812<pre><code>app.configure(function(){813    // executed for each env814});815816app.configure('development', function(){817    // executed for 'development' only818});819</code></pre>820821<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>822823<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>824825<pre><code>app.redirect('google', 'http://google.com');826</code></pre>827828<p>Now in a route we may call:</p>829830<p>   res.redirect('google');</p>831832<p>We may also map dynamic redirects:</p>833834<pre><code>app.redirect('comments', function(req, res, params){835    return '/post/' + params.id + '/comments';836});837</code></pre>838839<p>So now we may do the following, and the redirect will dynamically adjust to840the context of the request. If we called this route with <em>GET /post/12</em> our841redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>842843<pre><code>app.get('/post/:id', function(req, res){844    res.redirect('comments');845});846</code></pre>847848<h3 id="app-error-function-">app.error(function)</h3>849850<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.851Note that we may set several error handlers by making several calls to this method, however the handler852should call <em>next(err)</em> if it does not wish to deal with the exception:</p>853854<pre><code>app.error(function(err, req, res, next){855    res.send(err.message, 500);856});857</code></pre>858859<h3 id="app-helpers-obj-">app.helpers(obj)</h3>860861<p>Registers static view helpers.</p>862863<pre><code>app.helpers({864    name: function(first, last){ return first + ', ' + last },865    firstName: 'tj',866    lastName: 'holowaychuk'867});868</code></pre>869870<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,871as well as the <em>name()</em> function exposed.</p>872873<pre><code>&lt;%= name(firstName, lastName) %>874</code></pre>875876<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>877878<p>Registers dynamic view helpers. Dynamic view helpers879are simply functions which accept <em>req</em>, <em>res</em>, and <em>params</em>, and are880evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function881becomes the local variable it is associated with.</p>882883<pre><code>app.dynamicHelpers({884    session: function(req, res, params){885        return req.session;886    }887});888</code></pre>889890<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>891892<pre><code>&lt;%= session.name %&gt;893</code></pre>894895<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>896897<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all898connections will be accepted via <em>INADDR_ANY</em>.</p>899900<pre><code>app.listen();901app.listen(3000);902app.listen(3000, 'n.n.n.n');903</code></pre>904905<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>906907<pre><code>app.listen('/tmp/express.sock');908</code></pre>909910<p>Then try it out:</p>911912<pre><code>$ telnet /tmp/express.sock913GET / HTTP/1.1914915HTTP/1.1 200 OK916Content-Type: text/plain917Content-Length: 11918919Hello World920</code></pre>921922</div>923			</div>924		</div>925	</body>926</html>