Skip to content
Myr

regenerated docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent eefe51c · Browse files · 15 files+351 added−3244 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+351 added−3244 removed

  • other:+351 added−3244 removed

15 files+351 added−3244 removed

deleted:docs/applications.1-70 removed
1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "APPLICATIONS" "" "March 2011" "" ""5.6.SH "NAME"7\fBapplications\fR8.9.P10Learnboost \fIhttp://learnboost\.com\fR is a free online gradebook application, aimed to crush the competition with innovative, realtime, enjoyable features\.11.12.P13 \fIhttp://learnboost\.com\fR14.15.P16Storify \fIhttp://storify\.com\fR lets you turn what people post on social media websites into compelling stories\.17.18.P19 \fIhttp://storify\.com\fR20.21.P22Pakistan Survey \fIhttp://pakistansurvey\.org/\fR by Development Seed \fIhttp://developmentseed\.org\fR, provides in\-depth agency\-specific analysis from regional experts with data from 1,000 interviews across 120 villages in all seven tribal agencies and mapping of 142 reported drone strikes in FATA through July 2010\.23.24.P25 \fIhttp://pakistansurvey\.org\fR26.27.P28Markup\.IO \fIhttp://markup\.io\fR allows you to draw directly on \fIany\fR website, then share with others to share your thoughts\.29.30.P31 \fIhttp://markup\.io\fR32.33.P34Scrabb\.ly \fIhttp://scrabb\.ly\fR is a massively multiplayer scrabble game initially created for the Node Knockout \fIhttp://nodeknockout\.com/\fR competition\.35.36.P37 \fIhttp://scrabb\.ly\fR38.39.P40ClickDummy \fIhttp://clickdummy\.net/\fR is a rapid mockup prototyping application for designers and dummies\.41.42.P43 \fIhttp://clickdummy\.net\fR44.45.P46Node Knockout \fIhttp://nodeknockout\.com\fR organized the first ever node\-specific competition with hundreds of contestants\.47.48.P49 \fIhttp://nodeknockout\.com\fR50.51.P52Widescript \fIhttp://widescript\.com\fR is an innovative app that helps you focus and interact with your texts \- on your desktop, your couch or on the go\.53.54.P55 \fIhttp://widescript\.com\fR56.57.P58e\-resistable \fIhttp://www\.e\-resistible\.co\.uk/\fR is an online order takeaway system providing an intuitive way to fill your belly from your computer!59.60.P61 \fIhttp://www\.e\-resistible\.co\.uk\fR62.63.P64Top Twitter Trends \fIhttp://toptwittertrends\.com\fR utilizes MongoDB, Socket\.IO, jQuery and many other exciting libraries to bring you trending tweets in realtime\.65.66.P67 \fIhttp://toptwittertrends\.com\fR68.69.P70The applications shown above are not listed in any specific order\. To have an application added or removed please contact TJ Holowaychuk \fIhttp://github\.com/visionmedia\fR\.
modified:docs/applications.html+12 added-23 removed
188 unmodified lines
189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193<div class='mp'>194<h2 id="Express">Express</h2>195<p class="man-name">196 <code>applications</code>197</p>193<p>&lt;br /&gt;</p>194199200<br />201202195<p><a href="http://learnboost.com">Learnboost</a> is a free online gradebook application, aimed to crush the competition with innovative, realtime, enjoyable features.</p>196205<p><a href="http://learnboost.com"><img src="images/apps/learnboost.png" alt="LearnBoost" /></a></p>197<p>[<img alt="LearnBoost" src="images/apps/learnboost.png)](http://learnboost.com" /></p>198199<p><a href="http://storify.com">Storify</a> lets you turn what people post on social media websites into compelling stories.</p>200209<p><a href="http://storify.com"><img src="images/apps/storify.png" alt="Storify" /></a></p>201<p>[<img alt="Storify" src="images/apps/storify.png)](http://storify.com" /></p>202203<p><a href="http://pakistansurvey.org/">Pakistan Survey</a> by <a href="http://developmentseed.org">Development Seed</a>, provides in-depth agency-specific analysis from regional experts with data from 1,000 interviews across 120 villages in all seven tribal agencies and mapping of 142 reported drone strikes in FATA through July 2010.</p>204213<p><a href="http://pakistansurvey.org"><img src="images/apps/developmentseed.png" alt="Pakistan Survey" /></a></p>205<p>[<img alt="Pakistan Survey" src="images/apps/developmentseed.png)](http://pakistansurvey.org" /></p>206207<p><a href="http://markup.io">Markup.IO</a> allows you to draw directly on <em>any</em> website, then share with others to share your thoughts.</p>208217<p><a href="http://markup.io"><img src="images/apps/markupio.png" alt="Markup.IO" /></a></p>209<p>[<img alt="Markup.IO" src="images/apps/markupio.png)](http://markup.io" /></p>210211<p><a href="http://scrabb.ly">Scrabb.ly</a> is a massively multiplayer scrabble game initially created for the <a href="http://nodeknockout.com/">Node Knockout</a> competition.</p>212221<p><a href="http://scrabb.ly"><img src="images/apps/scrabbly.png" alt="Online Realtime Scrabble" /></a></p>213<p>[<img alt="Online Realtime Scrabble" src="images/apps/scrabbly.png)](http://scrabb.ly" /></p>214215<p><a href="http://clickdummy.net/">ClickDummy</a> is a rapid mockup prototyping application for designers and dummies.</p>216225<p><a href="http://clickdummy.net"><img src="images/apps/clickdummy.png" alt="Mockup Prototying" /></a></p>217<p>[<img alt="Mockup Prototying" src="images/apps/clickdummy.png)](http://clickdummy.net" /></p>218219<p><a href="http://nodeknockout.com">Node Knockout</a> organized the first ever node-specific competition with hundreds of contestants.</p>220229<p><a href="http://nodeknockout.com"><img src="images/apps/nodeko.png" alt="Node Knockout Competition Express" /></a></p>221<p>[<img alt="Node Knockout Competition Express" src="images/apps/nodeko.png)](http://nodeknockout.com" /></p>222223<p><a href="http://widescript.com">Widescript</a> is an innovative app that helps you focus and interact with your texts - on your desktop, your couch or on the go.</p>224233<p><a href="http://widescript.com"><img src="images/apps/widescript.png" alt="Widescript" /></a></p>225<p>[<img alt="Widescript" src="images/apps/widescript.png)](http://widescript.com" /></p>226227<p><a href="http://www.e-resistible.co.uk/">e-resistable</a> is an online order takeaway system providing an intuitive way to fill your belly from your computer!</p>228237<p><a href="http://www.e-resistible.co.uk"><img src="images/apps/e-resistable.png" alt="Online Takeaway" /></a></p>229<p>[<img alt="Online Takeaway" src="images/apps/e-resistable.png)](http://www.e-resistible.co.uk" /></p>230231<p><a href="http://toptwittertrends.com">Top Twitter Trends</a> utilizes MongoDB, Socket.IO, jQuery and many other exciting libraries to bring you trending tweets in realtime.</p>232241<p><a href="http://toptwittertrends.com"><img src="images/apps/toptwittertrends.png" alt="Twitter Trends" /></a></p>233<p>[<img alt="Twitter Trends" src="images/apps/toptwittertrends.png)](http://toptwittertrends.com" /></p>234243<br />235<p>&lt;br /&gt;</p>236245237<p>The applications shown above are not listed in any specific order. To have an application added or removed please contact <a href="http://github.com/visionmedia">TJ Holowaychuk</a>.</p>247248</div>238 </div>239 </div>240 </body>241</html>
deleted:docs/contrib.1-82 removed
1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "CONTRIB" "" "March 2011" "" ""5.6.SH "NAME"7\fBcontrib\fR8.9.SS "Development Dependencies"10Express development dependencies are stored within the \fI\./support\fR directory\. To update them execute:11.12.IP "" 413.14.nf1516$ git submodule update \-\-init17.18.fi19.20.IP "" 021.22.SS "Running Tests"23Express uses the Expresso \fIhttp://github\.com/visionmedia/expresso\fR TDD framework to write and run elegant test suites extremely fast\. To run all test suites simply execute:24.25.IP "" 426.27.nf2829$ make test30.31.fi32.33.IP "" 034.35.P36To target specific suites we may specify the files via:37.38.IP "" 439.40.nf4142$ make test TESTS=test/view\.test\.js43.44.fi45.46.IP "" 047.48.P49To check test coverage run:50.51.IP "" 452.53.nf5455$ make test\-cov56.57.fi58.59.IP "" 060.61.SS "Contributions"62To accept a contribution, you should follow these guidelines:63.64.IP "\(bu" 465All tests \fImust\fR pass66.67.IP "\(bu" 468Your alterations or additions \fImust\fR include tests69.70.IP "\(bu" 471Your commit(s) should be \fIfocused\fR, do not commit once for several changes72.73.IP "\(bu" 474Do \fInot\fR alter release information such as the \fIversion\fR, or \fIHistory\.md\fR75.76.IP "\(bu" 477Indents are \fI2\fR spaces\.78.79.IP "" 080.81.SS "Documentation"82To contribute documentation edit the markdown files in \fI\./docs\fR, however do \fInot\fR run \fImake docs\fR, as they will be re\-built and published with each release\.
modified:docs/contrib.html+5 added-23 removed
188 unmodified lines
189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193<div class='mp'>194<h2 id="Express">Express</h2>195<p class="man-name">196 <code>contrib</code>197</p>193<h3 id="Development-Dependencies">Development Dependencies</h3>194195<p>Express development dependencies are stored within the <em>./support</em> directory. To196update them execute:</p>197203<pre><code>$ git submodule update --init204</code></pre>198<pre><code>$ git submodule update --init</code></pre>199200<h3 id="Running-Tests">Running Tests</h3>201202<p>Express uses the <a href="http://github.com/visionmedia/expresso">Expresso</a> TDD203framework to write and run elegant test suites extremely fast. To run all test suites204simply execute:</p>205212<pre><code>$ make test213</code></pre>206<pre><code>$ make test</code></pre>207208<p>To target specific suites we may specify the files via:</p>209217<pre><code>$ make test TESTS=test/view.test.js218</code></pre>210<pre><code>$ make test TESTS=test/view.test.js</code></pre>211212<p>To check test coverage run:</p>213222<pre><code>$ make test-cov223</code></pre>214<pre><code>$ make test-cov</code></pre>215216<h3 id="Contributions">Contributions</h3>217218<p>To accept a contribution, you should follow these guidelines:</p>219229<ul>230<li>All tests <em>must</em> pass</li>231<li>Your alterations or additions <em>must</em> include tests</li>232<li>Your commit(s) should be <em>focused</em>, do not commit once for several changes</li>233<li>Do <em>not</em> alter release information such as the <em>version</em>, or <em>History.md</em></li>234<li>Indents are <em>2</em> spaces.</li>235</ul>220<ul><li>All tests <em>must</em> pass</li><li>Your alterations or additions <em>must</em> include tests</li><li>Your commit(s) should be <em>focused</em>, do not commit once for several changes</li><li>Do <em>not</em> alter release information such as the <em>version</em>, or <em>History.md</em></li><li>Indents are <em>2</em> spaces.</li></ul>221237222<h3 id="Documentation">Documentation</h3>223224<p>To contribute documentation edit the markdown files in <em>./docs</em>, however225do <em>not</em> run <em>make docs</em>, as they will be re-built and published with each release.</p>242243</div>226 </div>227 </div>228 </body>229</html>
deleted:docs/executable.1-31 removed
1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "EXECUTABLE" "" "March 2011" "" ""5.6.SH "NAME"7\fBexecutable\fR8.9.SH "Synopsis"10.11.nf1213express [options] [PATH]14.15.fi16.17.SH "Description"18The \fIexpress\fR executable generates apps at the given \fBPATH\fR or the current working directory\. Although Express is not bound to a specific application structure, this executable creates a maintainable base app\.19.20.SH "Options"21.22.nf2324 \-s, \-\-sessions Add session support25 \-t, \-\-template ENGINE Add template ENGINE support (jade|ejs)\. Defaults to jade26 \-c, \-\-css ENGINE Add stylesheet ENGINE support (less|sass|stylus)\. Defaults to plain css27 \-v, \-\-version Output framework version28 \-h, \-\-help Output help information29.30.fi31
modified:docs/executable.html+3 added-12 removed
188 unmodified lines
189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193<div class='mp'>194<h2 id="Express">Express</h2>195<p class="man-name">196 <code>executable</code>197</p>193<h2 id="Synopsis">Synopsis</h2>194200<pre><code>express [options] [PATH]201</code></pre>195<pre><code>express [options] [PATH]</code></pre>196197<h2 id="Description">Description</h2>198205<p>The <em>express</em> executable generates apps at the given <strong>PATH</strong> or the199<p>The <em>express</em> executable generates apps at the given <strong>PATH</strong> or the 200current working directory. Although Express is not bound to a specific201application structure, this executable creates a maintainable base app.</p>202203<h2 id="Options">Options</h2>
1 unmodified line
205<pre><code> -s, --sessions Add session support206 -t, --template ENGINE Add template ENGINE support (jade|ejs). Defaults to jade207 -c, --css ENGINE Add stylesheet ENGINE support (less|sass|stylus). Defaults to plain css208 -v, --version Output framework version215 -h, --help Output help information216</code></pre>217218</div>209 -h, --help Output help information</code></pre>210 </div>211 </div>212 </body>213</html>
deleted:docs/guide.1-2099 removed
1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "GUIDE" "" "March 2011" "" ""5.6.SH "NAME"7\fBguide\fR8.9.SS "Installation"10.11.nf1213$ npm install express14.15.fi16.17.SS "Creating A Server"18To create an instance of the \fIexpress\.HTTPServer\fR, simply invoke the \fIcreateServer()\fR method\. With our instance \fIapp\fR we can then define routes based on the HTTP verbs, in this example \fIapp\.get()\fR\.19.20.IP "" 421.22.nf2324var app = require(\'express\')\.createServer();2526app\.get(\'/\', function(req, res){27 res\.send(\'hello world\');28});2930app\.listen(3000);31.32.fi33.34.IP "" 035.36.SS "Creating An HTTPS Server"37To initialize a \fIexpress\.HTTPSServer\fR we do the same as above, however we pass an options object, accepting \fIkey\fR, \fIcert\fR and the others mentioned in node\'s https documentation \fIhttp://nodejs\.org/docs/v0\.3\.7/api/https\.html#https\.createServer\fR\.38.39.IP "" 440.41.nf4243 var app = require(\'express\')\.createServer({ key: \.\.\. });44.45.fi46.47.IP "" 048.49.SS "Configuration"50Express supports arbitrary environments, such as \fIproduction\fR and \fIdevelopment\fR\. Developers can use the \fIconfigure()\fR method to setup needs required by the current environment\. When \fIconfigure()\fR is called without an environment name it will be run in \fIevery\fR environment prior to the environment specific callback\.51.52.P53In the example below we only \fIdumpExceptions\fR, and respond with exception stack traces in \fIdevelopment\fR mode, however for both environments we utilize \fImethodOverride\fR and \fIbodyParser\fR\. Note the use of \fIapp\.router\fR, which can (optionally) be used to mount the application routes, otherwise the first call to \fIapp\.get()\fR, \fIapp\.post()\fR, etc will mount the routes\.54.55.IP "" 456.57.nf5859app\.configure(function(){60 app\.use(express\.methodOverride());61 app\.use(express\.bodyParser());62 app\.use(app\.router);63});6465app\.configure(\'development\', function(){66 app\.use(express\.static(__dirname + \'/public\'));67 app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));68});6970app\.configure(\'production\', function(){71 var oneYear = 31557600000;72 app\.use(express\.static({ root: __dirname + \'/public\', maxAge: oneYear }));73 app\.use(express\.errorHandler());74});75.76.fi77.78.IP "" 079.80.P81For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:82.83.IP "" 484.85.nf8687 app\.configure(function(){88 app\.set(\'views\', __dirname + \'/views\');89 app\.set(\'views\');90 // => "/absolute/path/to/views"9192 app\.enable(\'some feature\');93 // same as app\.set(\'some feature\', true);9495 app\.disable(\'some feature\');96 // same as app\.set(\'some feature\', false);9798 app\.enabled(\'some feature\')99 // => false100 });101.102.fi103.104.IP "" 0105.106.P107To alter the environment we can set the \fINODE_ENV\fR environment variable, for example:108.109.IP "" 4110.111.nf112113$ NODE_ENV=production node app\.js114.115.fi116.117.IP "" 0118.119.P120This is \fIvery\fR important, as many caching mechanisms are \fIonly enabled\fR when in production\.121.122.SS "Settings"123Express supports the following settings out of the box:124.125.IP "\(bu" 4126\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.127.128.IP "\(bu" 4129\fIviews\fR Root views directory defaulting to \fBCWD/views\fR130.131.IP "\(bu" 4132\fIview engine\fR Default view engine name for views rendered without extensions133.134.IP "\(bu" 4135\fIview options\fR An object specifying global view options136.137.IP "" 0138.139.SS "Routing"140Express utilizes the HTTP verbs to provide a meaningful, expressive routing API\. For example we may want to render a user\'s account for the path \fI/user/12\fR, this can be done by defining the route below\. The values associated to the named placeholders are available as \fBreq\.params\fR\.141.142.IP "" 4143.144.nf145146app\.get(\'/user/:id\', function(req, res){147 res\.send(\'user \' + req\.params\.id);148});149.150.fi151.152.IP "" 0153.154.P155A route is simple a string which is compiled to a \fIRegExp\fR internally\. For example when \fI/user/:id\fR is compiled, a simplified version of the regexp may look similar to:156.157.IP "" 4158.159.nf160161\e/user\e/([^\e/]+)\e/?162.163.fi164.165.IP "" 0166.167.P168Regular expression literals may also be passed for complex uses\. Since capture groups with literal \fIRegExp\fR\'s are anonymous we can access them directly \fBreq\.params\fR\. So our first capture group would be \fIreq\.params[0]\fR and the second would follow as \fIreq\.params[1]\fR\.169.170.IP "" 4171.172.nf173174app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){175 res\.send(req\.params);176});177.178.fi179.180.IP "" 0181.182.P183Curl requests against the previously defined route:184.185.IP "" 4186.187.nf188189 $ curl http://dev:3000/user190 [null,null]191 $ curl http://dev:3000/users192 [null,null]193 $ curl http://dev:3000/users/1194 ["1",null]195 $ curl http://dev:3000/users/1\.\.15196 ["1","15"]197.198.fi199.200.IP "" 0201.202.P203Below are some route examples, and the associated paths that they may consume:204.205.IP "" 4206.207.nf208209 "/user/:id"210 /user/12211212 "/users/:id?"213 /users/5214 /users215216 "/files/*"217 /files/jquery\.js218 /files/javascripts/jquery\.js219220 "/file/*\.*"221 /files/jquery\.js222 /files/javascripts/jquery\.js223224 "/user/:id/:operation?"225 /user/1226 /user/1/edit227228 "/products\.:format"229 /products\.json230 /products\.xml231232 "/products\.:format?"233 /products\.json234 /products\.xml235 /products236237 "/user/:id\.:format?"238 /user/12239 /user/12\.json240.241.fi242.243.IP "" 0244.245.P246For example we can \fBPOST\fR some json, and echo the json back using the \fIbodyParser\fR middleware which will parse json request bodies (as well as others), and place the result in \fIreq\.body\fR:247.248.IP "" 4249.250.nf251252var express = require(\'express\')253 , app = express\.createServer();254255app\.use(express\.bodyParser());256257app\.post(\'/\', function(req, res){258 res\.send(req\.body);259});260261app\.listen(3000);262.263.fi264.265.IP "" 0266.267.P268Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use \fI\'/user/:id(\ed+)\'\fR which will \fInot\fR match unless the placeholder value contains only digits\.269.270.SS "Passing Route Control"271We may pass control to the next \fImatching\fR route, by calling the \fIthird\fR argument, the \fInext()\fR function\. When a match cannot be made, control is passed back to Connect, and middleware continue to be invoked in the order that they are added via \fIuse()\fR\. The same is true for several routes which have the same path defined, they will simply be executed in order until one does \fInot\fR call \fInext()\fR and decides to respond\.272.273.IP "" 4274.275.nf276277app\.get(\'/users/:id?\', function(req, res, next){278 var id = req\.params\.id;279 if (id) {280 // do something281 } else {282 next();283 }284});285286app\.get(\'/users\', function(req, res){287 // do something else288});289.290.fi291.292.IP "" 0293.294.P295The \fIapp\.all()\fR method is useful for applying the same logic for all HTTP verbs in a single call\. Below we use this to load a user from our fake database, and assign it to \fIreq\.user\fR\.296.297.IP "" 4298.299.nf300301var express = require(\'express\')302 , app = express\.createServer();303304var users = [{ name: \'tj\' }];305306app\.all(\'/user/:id/:op?\', function(req, res, next){307 req\.user = users[req\.params\.id];308 if (req\.user) {309 next();310 } else {311 next(new Error(\'cannot find user \' + req\.params\.id));312 }313});314315app\.get(\'/user/:id\', function(req, res){316 res\.send(\'viewing \' + req\.user\.name);317});318319app\.get(\'/user/:id/edit\', function(req, res){320 res\.send(\'editing \' + req\.user\.name);321});322323app\.put(\'/user/:id\', function(req, res){324 res\.send(\'updating \' + req\.user\.name);325});326327app\.get(\'*\', function(req, res){328 res\.send(\'what???\', 404);329});330331app\.listen(3000);332.333.fi334.335.IP "" 0336.337.SS "Middleware"338Middleware via Connect \fIhttp://github\.com/senchalabs/connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:339.340.IP "" 4341.342.nf343344 var express = require(\'express\');345346var app = express\.createServer(347 express\.logger()348 , express\.bodyParser()349 );350.351.fi352.353.IP "" 0354.355.P356Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks, in a progressive manor\.357.358.IP "" 4359.360.nf361362app\.use(express\.logger({ format: \':method :uri\' }));363.364.fi365.366.IP "" 0367.368.P369Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:370.371.IP "" 4372.373.nf374375var connect = require(\'connect\');376app\.use(connect\.logger());377app\.use(connect\.bodyParser());378.379.fi380.381.IP "" 0382.383.P384This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:385.386.IP "" 4387.388.nf389390app\.use(express\.logger());391app\.use(express\.bodyParser());392.393.fi394.395.IP "" 0396.397.SS "Route Middleware"398Routes may utilize route\-specific middleware by passing one or more additional callbacks (or arrays) to the method\. This feature is extremely useful for restricting access, loading data used by the route etc\.399.400.P401Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.402.403.IP "" 4404.405.nf406407app\.get(\'/user/:id\', function(req, res, next){408 loadUser(req\.params\.id, function(err, user){409 if (err) return next(err);410 res\.send(\'Viewing user \' + user\.name);411 });412});413.414.fi415.416.IP "" 0417.418.P419To keep things DRY and to increase readability we can apply this logic within a middleware\. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time\.420.421.IP "" 4422.423.nf424425function loadUser(req, res, next) {426 // You would fetch your user from the db427 var user = users[req\.params\.id];428 if (user) {429 req\.user = user;430 next();431 } else {432 next(new Error(\'Failed to load user \' + req\.params\.id));433 }434}435436app\.get(\'/user/:id\', loadUser, function(req, res){437 res\.send(\'Viewing user \' + req\.user\.name);438});439.440.fi441.442.IP "" 0443.444.P445Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account\. In the example below only the authenticated user may edit his/her account\.446.447.IP "" 4448.449.nf450451function andRestrictToSelf(req, res, next) {452 req\.authenticatedUser\.id == req\.user\.id453 ? next()454 : next(new Error(\'Unauthorized\'));455}456457app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){458 res\.send(\'Editing user \' + req\.user\.name);459});460.461.fi462.463.IP "" 0464.465.P466Keeping in mind that middleware are simply functions, we can define function that \fIreturns\fR the middleware in order to create a more expressive and flexible solution as shown below\.467.468.IP "" 4469.470.nf471472function andRestrictTo(role) {473 return function(req, res, next) {474 req\.authenticatedUser\.role == role475 ? next()476 : next(new Error(\'Unauthorized\'));477 }478}479480app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){481 res\.send(\'Deleted user \' + req\.user\.name);482});483.484.fi485.486.IP "" 0487.488.P489Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.490.491.IP "" 4492.493.nf494495var a = [middleware1, middleware2]496 , b = [middleware3, middleware4]497 , all = [a, b];498499app\.get(\'/foo\', a, function(){});500app\.get(\'/bar\', a, function(){});501502app\.get(\'/\', a, middleware3, middleware4, function(){});503app\.get(\'/\', a, b, function(){});504app\.get(\'/\', all, function(){});505.506.fi507.508.IP "" 0509.510.P511For this example in full, view the route middleware example \fIhttp://github\.com/visionmedia/express/blob/master/examples/route\-middleware/app\.js\fR in the repository\.512.513.SS "HTTP Methods"514We have seen \fIapp\.get()\fR a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as \fIapp\.post()\fR, \fIapp\.del()\fR, etc\.515.516.P517A common example for \fIPOST\fR usage, is when "submitting" a form\. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it\.518.519.IP "" 4520.521.nf522523 <form method="post" action="/">524 <input type="text" name="user[name]" />525 <input type="text" name="user[email]" />526 <input type="submit" value="Submit" />527 </form>528.529.fi530.531.IP "" 0532.533.P534By default Express does not know what to do with this request body, so we should add the \fIbodyParser\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR and \fIapplication/json\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:535.536.IP "" 4537.538.nf539540app\.use(express\.bodyParser());541.542.fi543.544.IP "" 0545.546.P547Our route below will now have access to the \fIreq\.body\.user\fR object which will contain the \fIname\fR and \fIemail\fR properties when defined\.548.549.IP "" 4550.551.nf552553app\.post(\'/\', function(req, res){554 console\.log(req\.body\.user);555 res\.redirect(\'back\');556});557.558.fi559.560.IP "" 0561.562.P563When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyParser\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.564.565.IP "" 4566.567.nf568569app\.use(express\.bodyParser());570app\.use(express\.methodOverride());571.572.fi573.574.IP "" 0575.576.P577The reason that these are not always defaults, is simply because these are not required for Express to be fully functional\. Depending on the needs of your application, you may not need these at all, your methods such as \fIPUT\fR and \fIDELETE\fR can still be accessed by clients which can use them directly, although \fImethodOverride\fR provides a great solution for forms\. Below shows what the usage of \fIPUT\fR might look like:578.579.IP "" 4580.581.nf582583<form method="post" action="/">584 <input type="hidden" name="_method" value="put" />585 <input type="text" name="user[name]" />586 <input type="text" name="user[email]" />587 <input type="submit" value="Submit" />588</form>589590app\.put(\'/\', function(){591 console\.log(req\.body\.user);592 res\.redirect(\'back\');593});594.595.fi596.597.IP "" 0598.599.SS "Error Handling"600Express provides the \fIapp\.error()\fR method which receives exceptions thrown within a route, or passed to \fInext(err)\fR\. Below is an example which serves different pages based on our ad\-hoc \fINotFound\fR exception:601.602.IP "" 4603.604.nf605606function NotFound(msg){607 this\.name = \'NotFound\';608 Error\.call(this, msg);609 Error\.captureStackTrace(this, arguments\.callee);610}611612NotFound\.protoype\.__proto__ = Error\.prototype;613614app\.get(\'/404\', function(req, res){615 throw new NotFound;616});617618app\.get(\'/500\', function(req, res){619 throw new Error(\'keyboard cat!\');620});621.622.fi623.624.IP "" 0625.626.P627We can call \fIapp\.error()\fR several times as shown below\. Here we check for an instanceof \fINotFound\fR and show the 404 page, or we pass on to the next error handler\.628.629.P630Note that these handlers can be defined anywhere, as they will be placed below the route handlers on \fIlisten()\fR\. This allows for definition within \fIconfigure()\fR blocks so we can handle exceptions in different ways based on the environment\.631.632.IP "" 4633.634.nf635636app\.error(function(err, req, res, next){637 if (err instanceof NotFound) {638 res\.render(\'404\.jade\');639 } else {640 next(err);641 }642});643.644.fi645.646.IP "" 0647.648.P649Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like\. For example when node performs filesystem syscalls, you may receive an error object with the \fIerror\.code\fR of \fIENOENT\fR, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired\.650.651.IP "" 4652.653.nf654655app\.error(function(err, req, res){656 res\.render(\'500\.jade\', {657 error: err658 });659});660.661.fi662.663.IP "" 0664.665.P666Our apps could also utilize the Connect \fIerrorHandler\fR middleware to report on exceptions\. For example if we wish to output exceptions in "development" mode to \fIstderr\fR we can use:667.668.IP "" 4669.670.nf671672app\.use(express\.errorHandler({ dumpExceptions: true }));673.674.fi675.676.IP "" 0677.678.P679Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:680.681.IP "" 4682.683.nf684685app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));686.687.fi688.689.IP "" 0690.691.P692The \fIerrorHandler\fR middleware also responds with \fIjson\fR if \fIAccept: application/json\fR is present, which is useful for developing apps that rely heavily on client\-side JavaScript\.693.694.SS "Route Param Pre\-conditions"695Route param pre\-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls\. For example if you are constantly fetching common data for several routes, such as loading a user for \fI/user/:id\fR, we might typically do something like below:696.697.IP "" 4698.699.nf700701app\.get(\'/user/:userId\', function(req, res, next){702 User\.get(req\.params\.userId, function(err, user){703 if (err) return next(err);704 res\.send(\'user \' + user\.name);705 });706});707.708.fi709.710.IP "" 0711.712.P713With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database\. Below we invoke \fIapp\.param()\fR with the parameter name we wish to map to some middleware, as you can see we receive the \fIid\fR argument which contains the placeholder value\. Using this we load the user and perform error handling as usual, and simple call \fInext()\fR to pass control to the next precondition or route handler\.714.715.IP "" 4716.717.nf718719app\.param(\'userId\', function(req, res, next, id){720 User\.get(id, function(err, user){721 if (err) return next(err);722 if (!user) return next(new Error(\'failed to find user\'));723 req\.user = user;724 next();725 });726});727.728.fi729.730.IP "" 0731.732.P733Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:734.735.IP "" 4736.737.nf738739app\.get(\'/user/:userId\', function(req, res){740 res\.send(\'user \' + req\.user\.name);741});742.743.fi744.745.IP "" 0746.747.P748For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument)\. Any errors thrown will be passed to \fInext(err)\fR\.749.750.IP "" 4751.752.nf753754app\.param(\'number\', function(n){ return parseInt(n, 10); });755.756.fi757.758.IP "" 0759.760.P761We may also apply the same callback to several placeholders, for example a route GET \fI/commits/:from\-:to\fR are both numbers, so we may define them as an array:762.763.IP "" 4764.765.nf766767app\.param([\'from\', \'to\'], function(n){ return parseInt(n, 10); });768.769.fi770.771.IP "" 0772.773.SS "View Rendering"774View filenames take the form "<name>\.<engine>", where <engine> is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.compile(str, options)\fR, and return a \fIFunction\fR to comply with Express\. To alter this behaviour \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by ejs\.775.776.P777Below is an example using Jade \fIhttp://github\.com/visionmedia/jade\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.jade\fR will be passed as the \fIbody\fR local variable in \fIlayout\.jade\fR\.778.779.IP "" 4780.781.nf782783app\.get(\'/\', function(req, res){784 res\.render(\'index\.jade\', { title: \'My Site\' });785});786.787.fi788.789.IP "" 0790.791.P792The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using jade we could set:793.794.IP "" 4795.796.nf797798app\.set(\'view engine\', \'jade\');799.800.fi801.802.IP "" 0803.804.P805Allowing us to render with:806.807.IP "" 4808.809.nf810811res\.render(\'index\');812.813.fi814.815.IP "" 0816.817.P818vs:819.820.IP "" 4821.822.nf823824res\.render(\'index\.jade\');825.826.fi827.828.IP "" 0829.830.P831When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:832.833.IP "" 4834.835.nf836837res\.render(\'another\-page\.ejs\');838.839.fi840.841.IP "" 0842.843.P844Express also provides the \fIview options\fR setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:845.846.IP "" 4847.848.nf849850app\.set(\'view options\', {851 layout: false852});853.854.fi855.856.IP "" 0857.858.P859Which can then be overridden within the \fIres\.render()\fR call if need be:860.861.IP "" 4862.863.nf864865res\.render(\'myview\.ejs\', { layout: true });866.867.fi868.869.IP "" 0870.871.P872When an alternate layout is required, we may also specify a path\. For example if we have \fIview engine\fR set to \fIjade\fR and a file named \fI\./views/mylayout\.jade\fR we can simply pass:873.874.IP "" 4875.876.nf877878res\.render(\'page\', { layout: \'mylayout\' });879.880.fi881.882.IP "" 0883.884.P885Otherwise we must specify the extension:886.887.IP "" 4888.889.nf890891res\.render(\'page\', { layout: \'mylayout\.jade\' });892.893.fi894.895.IP "" 0896.897.P898These paths may also be absolute:899.900.IP "" 4901.902.nf903904res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });905.906.fi907.908.IP "" 0909.910.P911A good example of this is specifying custom \fIejs\fR opening and closing tags:912.913.IP "" 4914.915.nf916917app\.set(\'view options\', {918 open: \'{{\',919 close: \'}}\'920});921.922.fi923.924.IP "" 0925.926.SS "View Partials"927The Express view system has built\-in support for partials and collections, which are "mini" views representing a document fragment\. For example rather than iterating in a view to display comments, we would use a partial with collection support:928.929.IP "" 4930.931.nf932933partial(\'comment\', { collection: comments });934.935.fi936.937.IP "" 0938.939.P940If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:941.942.IP "" 4943.944.nf945946partial(\'comment\', comments);947.948.fi949.950.IP "" 0951.952.P953When using the partial collection support a few "magic" variables are provided for free:954.955.IP "\(bu" 4956\fIfirstInCollection\fR true if this is the first object957.958.IP "\(bu" 4959\fIindexInCollection\fR index of the object in the collection960.961.IP "\(bu" 4962\fIlastInCollection\fR true if this is the last object963.964.IP "\(bu" 4965\fIcollectionLength\fR length of the collection966.967.IP "" 0968.969.P970Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well\. So for example if we were to render a blog post with \fIpartial(\'blog/post\', post)\fR it would generate the \fIpost\fR local, but the view calling this function had the local \fIuser\fR, it would be available to the \fIblog/post\fR view as well\.971.972.P973For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.974.975.P976\fBNOTE:\fR be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views\. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead\.977.978.SS "View Lookup"979View lookup is performed relative to the parent view, for example if we had a page view named \fIviews/user/list\.jade\fR, and within that view we did \fIpartial(\'edit\')\fR it would attempt to load \fIviews/user/edit\.jade\fR, whereas \fIpartial(\'\.\./messages\')\fR would load \fIviews/messages\.jade\fR\.980.981.P982The view system also allows for index templates, allowing you to have a directory of the same name\. For example within a route we may have \fIres\.render(\'users\')\fR either \fIviews/users\.jade\fR, or \fIviews/users/index\.jade\fR\.983.984.P985When utilizing index views as shown above, we may reference \fIviews/users/index\.jade\fR from a view in the same directory by \fIpartial(\'users\')\fR, and the view system will try \fI\.\./users/index\fR, preventing us from needing to call \fIpartial(\'index\')\fR\.986.987.SS "Template Engines"988Below are a few template engines commonly used with Express:989.990.IP "\(bu" 4991Jade \fIhttp://jade\-lang\.com\fR haml\.js successor992.993.IP "\(bu" 4994EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript995.996.IP "\(bu" 4997CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating998.999.IP "\(bu" 41000jQuery Templates \fIhttps://github\.com/kof/node\-jqtpl\fR for node1001.1002.IP "" 01003.1004.SS "Session Support"1005Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieParser\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.1006.1007.IP "" 41008.1009.nf10101011app\.use(express\.cookieParser());1012app\.use(express\.session({ secret: "keyboard cat" }));1013.1014.fi1015.1016.IP "" 01017.1018.P1019By default the \fIsession\fR middleware uses the memory store bundled with Connect, however many implementations exist\. For example connect\-redis \fIhttp://github\.com/visionmedia/connect\-redis\fR supplies a Redis \fIhttp://code\.google\.com/p/redis/\fR session store and can be used as shown below:1020.1021.IP "" 41022.1023.nf10241025var RedisStore = require(\'connect\-redis\');1026app\.use(express\.cookieParser());1027app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));1028.1029.fi1030.1031.IP "" 01032.1033.P1034Now the \fIreq\.session\fR and \fIreq\.sessionStore\fR properties will be accessible to all routes and subsequent middleware\. Properties on \fIreq\.session\fR are automatically saved on a response, so for example if we wish to shopping cart data:1035.1036.IP "" 41037.1038.nf10391040var RedisStore = require(\'connect\-redis\');1041app\.use(express\.bodyParser());1042app\.use(express\.cookieParser());1043app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));10441045app\.post(\'/add\-to\-cart\', function(req, res){1046 // Perhaps we posted several items with a form1047 // (use the bodyParser() middleware for this)1048 var items = req\.body\.items;1049 req\.session\.items = items;1050 res\.redirect(\'back\');1051});10521053app\.get(\'/add\-to\-cart\', function(req, res){1054 // When redirected back to GET /add\-to\-cart1055 // we could check req\.session\.items && req\.session\.items\.length1056 // to print out a message1057 if (req\.session\.items && req\.session\.items\.length) {1058 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);1059 }1060 res\.render(\'shopping\-cart\');1061});1062.1063.fi1064.1065.IP "" 01066.1067.P1068The \fIreq\.session\fR object also has methods such as \fISession#touch()\fR, \fISession#destroy()\fR, \fISession#regenerate()\fR among others to maintain and manipulate sessions\. For more information view the Connect Session \fIhttp://senchalabs\.github\.com/connect/middleware\-session\.html\fR documentation\.1069.1070.SS "Migration Guide"1071Express 1\.x developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application to work with Express 2\.x, Connect 1\.x, and Node 0\.4\.x\.1072.1073.SS "req\.header(key[, defaultValue])"1074Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1075.1076.IP "" 41077.1078.nf10791080req\.header(\'Host\');1081req\.header(\'host\');1082req\.header(\'Accept\', \'*/*\');1083.1084.fi1085.1086.IP "" 01087.1088.P1089The \fIReferrer\fR and \fIReferer\fR header fields are special\-cased, either will work:1090.1091.IP "" 41092.1093.nf10941095// sent Referrer: http://google\.com10961097req\.header(\'Referer\');1098// => "http://google\.com"10991100req\.header(\'Referrer\');1101// => "http://google\.com"1102.1103.fi1104.1105.IP "" 01106.1107.SS "req\.accepts(type)"1108Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1109.1110.P1111When the \fIAccept\fR header is not present \fItrue\fR is returned\. Otherwise the given \fItype\fR is matched by an exact match, and then subtypes\. You may pass the subtype such as "html" which is then converted internally to "text/html" using the mime lookup table\.1112.1113.IP "" 41114.1115.nf11161117// Accept: text/html1118req\.accepts(\'html\');1119// => true11201121// Accept: text/*; application/json1122req\.accepts(\'html\');1123req\.accepts(\'text/html\');1124req\.accepts(\'text/plain\');1125req\.accepts(\'application/json\');1126// => true11271128req\.accepts(\'image/png\');1129req\.accepts(\'png\');1130// => false1131.1132.fi1133.1134.IP "" 01135.1136.SS "req\.is(type)"1137Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.1138.1139.IP "" 41140.1141.nf11421143 // With Content\-Type: text/html; charset=utf\-81144 req\.is(\'html\');1145 req\.is(\'text/html\');1146 // => true11471148 // When Content\-Type is application/json1149 req\.is(\'json\');1150 req\.is(\'application/json\');1151 // => true11521153 req\.is(\'html\');1154 // => false1155.1156.fi1157.1158.IP "" 01159.1160.P1161Ad\-hoc callbacks can also be registered with Express, to perform assertions again the request, for example if we need an expressive way to check if our incoming request is an image, we can register \fI"an image"\fR callback:1162.1163.IP "" 41164.1165.nf11661167 app\.is(\'an image\', function(req){1168 return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1169 });1170.1171.fi1172.1173.IP "" 01174.1175.P1176Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1177.1178.IP "" 41179.1180.nf11811182 app\.post(\'/image/upload\', function(req, res, next){1183 if (req\.is(\'an image\')) {1184 // do something1185 } else {1186 next();1187 }1188 });1189.1190.fi1191.1192.IP "" 01193.1194.P1195Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1196.1197.P1198Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1199.1200.IP "" 41201.1202.nf12031204req\.is(\'image/*\');1205.1206.fi1207.1208.IP "" 01209.1210.P1211We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1212.1213.IP "" 41214.1215.nf12161217req\.is(\'*/json\');1218.1219.fi1220.1221.IP "" 01222.1223.SS "req\.param(name[, default])"1224Return the value of param \fIname\fR when present or \fIdefault\fR\.1225.1226.IP "\(bu" 41227Checks route params (\fIreq\.params\fR), ex: /user/:id1228.1229.IP "\(bu" 41230Checks query string params (\fIreq\.query\fR), ex: ?id=121231.1232.IP "\(bu" 41233Checks urlencoded body params (\fIreq\.body\fR), ex: id=121234.1235.IP "" 01236.1237.P1238To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the _express\.bodyParser middleware\.1239.1240.SS "req\.flash(type[, msg])"1241Queue flash \fImsg\fR of the given \fItype\fR\.1242.1243.IP "" 41244.1245.nf12461247req\.flash(\'info\', \'email sent\');1248req\.flash(\'error\', \'email delivery failed\');1249req\.flash(\'info\', \'email re\-sent\');1250// => 212511252req\.flash(\'info\');1253// => [\'email sent\', \'email re\-sent\']12541255req\.flash(\'info\');1256// => []12571258req\.flash();1259// => { error: [\'email delivery failed\'], info: [] }1260.1261.fi1262.1263.IP "" 01264.1265.P1266Flash notification message may also utilize formatters, by default only the %s string formatter is available:1267.1268.IP "" 41269.1270.nf12711272req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1273.1274.fi1275.1276.IP "" 01277.1278.SS "req\.isXMLHttpRequest"1279Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1280.1281.IP "" 41282.1283.nf12841285req\.xhr1286req\.isXMLHttpRequest1287.1288.fi1289.1290.IP "" 01291.1292.SS "res\.header(key[, val])"1293Get or set the response header \fIkey\fR\.1294.1295.IP "" 41296.1297.nf12981299res\.header(\'Content\-Length\');1300// => undefined13011302res\.header(\'Content\-Length\', 123);1303// => 12313041305res\.header(\'Content\-Length\');1306// => 1231307.1308.fi1309.1310.IP "" 01311.1312.SS "res\.contentType(type)"1313Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1314.1315.IP "" 41316.1317.nf13181319 var filename = \'path/to/image\.png\';1320 res\.contentType(filename);1321 // Content\-Type is now "image/png"1322.1323.fi1324.1325.IP "" 01326.1327.SS "res\.attachment([filename])"1328Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1329.1330.IP "" 41331.1332.nf13331334 res\.attachment(\'path/to/my/image\.png\');1335.1336.fi1337.1338.IP "" 01339.1340.SS "res\.sendfile(path[, options[, callback]])"1341Used by \fBres\.download()\fR to transfer an arbitrary file\.1342.1343.IP "" 41344.1345.nf13461347res\.sendfile(\'path/to/my\.file\');1348.1349.fi1350.1351.IP "" 01352.1353.P1354This method accepts an optional callback which is called when an error occurs, or when the transfer is complete\. By default failures call \fBnext(err)\fR, however when a callback is supplied you must do this explicitly, or act on the error\.1355.1356.IP "" 41357.1358.nf13591360res\.sendfile(path, function(err){1361 if (err) {1362 next(err);1363 } else {1364 console\.log(\'transferred %s\', path);1365 }1366});1367.1368.fi1369.1370.IP "" 01371.1372.P1373Options may also be passed to the internal \fIfs\.createReadStream()\fR call, for example altering the \fIbufferSize\fR:1374.1375.IP "" 41376.1377.nf13781379res\.sendfile(path, { bufferSize: 1024 }, function(err){1380 // handle1381});1382.1383.fi1384.1385.IP "" 01386.1387.SS "res\.download(file[, filename[, callback]])"1388Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1389.1390.IP "" 41391.1392.nf13931394res\.download(\'path/to/image\.png\');1395res\.download(\'path/to/image\.png\', \'foo\.png\');1396.1397.fi1398.1399.IP "" 01400.1401.P1402This is equivalent to:1403.1404.IP "" 41405.1406.nf14071408res\.attachment(file);1409res\.sendfile(file);1410.1411.fi1412.1413.IP "" 01414.1415.P1416An optional callback may be supplied as either the second or third argument, which is passed to \fIres\.sendfile()\fR:1417.1418.IP "" 41419.1420.nf14211422res\.download(path, \'expenses\.doc\', function(err){1423 // handle1424});1425.1426.fi1427.1428.IP "" 01429.1430.SS "res\.send(body|status[, headers|status[, status]])"1431The \fIres\.send()\fR method is a high level response utility allowing you to pass objects to respond with json, strings for html, Buffer instances, or numbers representing the status code\. The following are all valid uses:1432.1433.IP "" 41434.1435.nf14361437 res\.send(); // 2041438 res\.send(new Buffer(\'wahoo\'));1439 res\.send({ some: \'json\' });1440 res\.send(\'<p>some html</p>\');1441 res\.send(\'Sorry, cant find that\', 404);1442 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1443 res\.send(404);1444.1445.fi1446.1447.IP "" 01448.1449.P1450By default the \fIContent\-Type\fR response header is set, however if explicitly assigned through \fBres\.send()\fR or previously with \fBres\.header()\fR or \fBres\.contentType()\fR it will not be set again\.1451.1452.P1453Note that this method \fIend()\fRs the response, so you will want to use node\'s \fIres\.write()\fR for multiple writes or streaming\.1454.1455.SS "res\.redirect(url[, status])"1456Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1457.1458.IP "" 41459.1460.nf14611462res\.redirect(\'/\', 301);1463res\.redirect(\'/account\');1464res\.redirect(\'http://google\.com\');1465res\.redirect(\'home\');1466res\.redirect(\'back\');1467.1468.fi1469.1470.IP "" 01471.1472.P1473Express supports "redirect mapping", which by default provides \fIhome\fR, and \fIback\fR\. The \fIback\fR map checks the \fIReferrer\fR and \fIReferer\fR headers, while \fIhome\fR utilizes the "home" setting and defaults to "/"\.1474.1475.SS "res\.cookie(name, val[, options])"1476Sets the given cookie \fIname\fR to \fIval\fR, with options \fIhttpOnly\fR, \fIsecure\fR, \fIexpires\fR etc\.1477.1478.IP "" 41479.1480.nf14811482// "Remember me" for 15 minutes1483res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1484.1485.fi1486.1487.IP "" 01488.1489.P1490The \fImaxAge\fR property may be used to set \fIexpires\fR relative to \fIDate\.now()\fR in milliseconds, so our example above can now become:1491.1492.IP "" 41493.1494.nf14951496res\.cookie(\'rememberme\', \'yes\', { maxAge: 900000 });1497.1498.fi1499.1500.IP "" 01501.1502.P1503To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1504.1505.IP "" 41506.1507.nf15081509app\.use(express\.cookieParser());15101511app\.get(\'/\', function(req, res){1512 // use req\.cookies\.rememberme1513});1514.1515.fi1516.1517.IP "" 01518.1519.SS "res\.clearCookie(name)"1520Clear cookie \fIname\fR by setting "expires" far in the past\.1521.1522.IP "" 41523.1524.nf15251526res\.clearCookie(\'rememberme\');1527.1528.fi1529.1530.IP "" 01531.1532.SS "res\.render(view[, options[, fn]])"1533Render \fIview\fR with the given \fIoptions\fR and optional callback \fIfn\fR\. When a callback function is given a response will \fInot\fR be made automatically, however otherwise a response of \fI200\fR and \fItext/html\fR is given\.1534.1535.P1536The \fIoptions\fR passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:1537.1538.IP "" 41539.1540.nf15411542var user = { name: \'tj\' };1543res\.render(\'index\', { layout: false, user: user });1544.1545.fi1546.1547.IP "" 01548.1549.SS "res\.partial(view[, options])"1550Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1551.1552.IP "\(bu" 41553\fIobject\fR the object named by \fIas\fR or derived from the view name1554.1555.IP "\(bu" 41556\fIas\fR Variable name for each \fIcollection\fR or \fIobject\fR value, defaults to the view name\.1557.1558.IP "\(bu" 41559as: \'something\' will add the \fIsomething\fR local variable1560.1561.IP "\(bu" 41562as: this will use the collection value as the template context1563.1564.IP "\(bu" 41565as: global will merge the collection value\'s properties with \fIlocals\fR1566.1567.IP "" 015681569.1570.IP "\(bu" 41571\fIcollection\fR Array of objects, the name is derived from the view name itself\. For example \fIvideo\.html\fR will have a object \fIvideo\fR available to it\.1572.1573.IP "" 01574.1575.P1576The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1577.1578.IP "" 41579.1580.nf15811582partial(\'theatre/movie\.jade\', { collection: movies });1583partial(\'theatre/movie\.jade\', movies);1584partial(\'movie\.jade\', { collection: movies });1585partial(\'movie\.jade\', movies);1586partial(\'movie\', movies);1587// In view: movie\.director1588.1589.fi1590.1591.IP "" 01592.1593.P1594To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1595.1596.IP "" 41597.1598.nf15991600partial(\'movie\', { collection: movies, as: \'video\' });1601// In view: video\.director1602.1603.fi1604.1605.IP "" 01606.1607.P1608Also we can make our movie the value of \fIthis\fR within our view so that instead of \fImovie\.director\fR we could use \fIthis\.director\fR\.1609.1610.IP "" 41611.1612.nf16131614partial(\'movie\', { collection: movies, as: this });1615// In view: this\.director1616.1617.fi1618.1619.IP "" 01620.1621.P1622Another alternative is to "explode" the properties of the collection item into pseudo globals (local variables) by using \fIas: global\fR, which again is syntactic sugar:1623.1624.IP "" 41625.1626.nf16271628partial(\'movie\', { collection: movies, as: global });1629// In view: director1630.1631.fi1632.1633.IP "" 01634.1635.P1636This same logic applies to a single partial object usage:1637.1638.IP "" 41639.1640.nf16411642partial(\'movie\', { object: movie, as: this });1643// In view: this\.director16441645partial(\'movie\', { object: movie, as: global });1646// In view: director16471648partial(\'movie\', { object: movie, as: \'video\' });1649// In view: video\.director16501651partial(\'movie\', { object: movie });1652// In view: movie\.director1653.1654.fi1655.1656.IP "" 01657.1658.P1659When a non\-collection (does \fInot\fR have \fI\.length\fR) is passed as the second argument, it is assumed to be the \fIobject\fR, after which the object\'s local variable name is derived from the view name:1660.1661.IP "" 41662.1663.nf16641665partial(\'movie\', movie);1666// => In view: movie\.director1667.1668.fi1669.1670.IP "" 01671.1672.P1673This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:1674.1675.IP "" 41676.1677.nf16781679app\.get(\'/users\', function(req, res){1680 if (req\.xhr) {1681 // respond with the each user in the collection1682 // passed to the "user" view1683 res\.partial(\'user\', users);1684 } else {1685 // respond with layout, and users page1686 // which internally does partial(\'user\', users)1687 // along with other UI1688 res\.render(\'users\', { users: users });1689 }1690});1691.1692.fi1693.1694.IP "" 01695.1696.SS "res\.local(name[, val])"1697Get or set the given local variable \fIname\fR\. The locals built up for a response are applied to those given to the view rendering methods such as \fBres\.render()\fR\.1698.1699.IP "" 41700.1701.nf17021703 app\.all(\'/movie/:id\', function(req, res, next){1704 Movie\.get(req\.params\.id, function(err, movie){1705 // Assigns res\.locals\.movie = movie1706 res\.local(\'movie\', movie);1707 });1708 });17091710 app\.get(\'/movie/:id\', function(req, res){1711 // movie is already a local, however we1712 // can pass more if we wish1713 res\.render(\'movie\', { displayReviews: true });1714 });1715.1716.fi1717.1718.IP "" 01719.1720.SS "app\.set(name[, val])"1721Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1722.1723.IP "" 41724.1725.nf17261727app\.set(\'views\', __dirname + \'/views\');1728app\.set(\'views\');1729// => \.\.\.path\.\.\.1730.1731.fi1732.1733.IP "" 01734.1735.P1736Alternatively you may simply access the settings via \fIapp\.settings\fR:1737.1738.IP "" 41739.1740.nf17411742app\.settings\.views1743// => \.\.\.path\.\.\.1744.1745.fi1746.1747.IP "" 01748.1749.SS "app\.enable(name)"1750Enable the given setting \fIname\fR:1751.1752.IP "" 41753.1754.nf17551756app\.enable(\'some arbitrary setting\');1757app\.set(\'some arbitrary setting\');1758// => true17591760app\.enabled(\'some arbitrary setting\');1761// => true1762.1763.fi1764.1765.IP "" 01766.1767.SS "app\.enabled(name)"1768Check if setting \fIname\fR is enabled:1769.1770.IP "" 41771.1772.nf17731774app\.enabled(\'view cache\');1775// => false17761777app\.enable(\'view cache\');1778app\.enabled(\'view cache\');1779// => true1780.1781.fi1782.1783.IP "" 01784.1785.SS "app\.disable(name)"1786Disable the given setting \fIname\fR:1787.1788.IP "" 41789.1790.nf17911792app\.disable(\'some setting\');1793app\.set(\'some setting\');1794// => false17951796app\.disabled(\'some setting\');1797// => false1798.1799.fi1800.1801.IP "" 01802.1803.SS "app\.disabled(name)"1804Check if setting \fIname\fR is disabled:1805.1806.IP "" 41807.1808.nf18091810app\.enable(\'view cache\');18111812app\.disabled(\'view cache\');1813// => false18141815app\.disable(\'view cache\');1816app\.disabled(\'view cache\');1817// => true1818.1819.fi1820.1821.IP "" 01822.1823.SS "app\.configure(env|function[, function])"1824Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1825.1826.IP "" 41827.1828.nf18291830app\.configure(function(){1831 // executed for each env1832});18331834app\.configure(\'development\', function(){1835 // executed for \'development\' only1836});1837.1838.fi1839.1840.IP "" 01841.1842.SS "app\.redirect(name, val)"1843For use with \fIres\.redirect()\fR we can map redirects at the application level as shown below:1844.1845.IP "" 41846.1847.nf18481849app\.redirect(\'google\', \'http://google\.com\');1850.1851.fi1852.1853.IP "" 01854.1855.P1856Now in a route we may call:1857.1858.P1859res\.redirect(\'google\');1860.1861.P1862We may also map dynamic redirects:1863.1864.IP "" 41865.1866.nf18671868app\.redirect(\'comments\', function(req, res){1869 return \'/post/\' + req\.params\.id + \'/comments\';1870});1871.1872.fi1873.1874.IP "" 01875.1876.P1877So now we may do the following, and the redirect will dynamically adjust to the context of the request\. If we called this route with \fIGET /post/12\fR our redirect \fILocation\fR would be \fI/post/12/comments\fR\.1878.1879.IP "" 41880.1881.nf18821883app\.get(\'/post/:id\', function(req, res){1884 res\.redirect(\'comments\');1885});1886.1887.fi1888.1889.IP "" 01890.1891.P1892When mounted, \fIres\.redirect()\fR will respect the mount\-point\. For example if a blog app is mounted at \fI/blog\fR, the following will redirect to \fI/blog/posts\fR:1893.1894.IP "" 41895.1896.nf18971898res\.redirect(\'/posts\');1899.1900.fi1901.1902.IP "" 01903.1904.SS "app\.error(function)"1905Adds an error handler \fIfunction\fR which will receive the exception as the first parameter as shown below\. Note that we may set several error handlers by making several calls to this method, however the handler should call \fInext(err)\fR if it does not wish to deal with the exception:1906.1907.IP "" 41908.1909.nf19101911app\.error(function(err, req, res, next){1912 res\.send(err\.message, 500);1913});1914.1915.fi1916.1917.IP "" 01918.1919.SS "app\.helpers(obj)"1920Registers static view helpers\.1921.1922.P1923app\.helpers({1924.1925.IP "" 41926.1927.nf19281929 name: function(first, last){ return first + \', \' + last }1930, firstName: \'tj\'1931, lastName: \'holowaychuk\'1932.1933.fi1934.1935.IP "" 01936.1937.P1938});1939.1940.P1941Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1942.1943.IP "" 41944.1945.nf19461947<%= name(firstName, lastName) %>1948.1949.fi1950.1951.IP "" 01952.1953.SS "app\.dynamicHelpers(obj)"1954Registers dynamic view helpers\. Dynamic view helpers are simply functions which accept \fIreq\fR, \fIres\fR, and are evaluated against the \fIServer\fR instance before a view is rendered\. The \fIreturn value\fR of this function becomes the local variable it is associated with\.1955.1956.IP "" 41957.1958.nf19591960app\.dynamicHelpers({1961 session: function(req, res){1962 return req\.session;1963 }1964});1965.1966.fi1967.1968.IP "" 01969.1970.P1971All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1972.1973.IP "" 41974.1975.nf19761977<%= session\.name %>1978.1979.fi1980.1981.IP "" 01982.1983.SS "app\.mounted(fn)"1984Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1985.1986.IP "" 41987.1988.nf19891990var app = express\.createServer(),1991 blog = express\.createServer();19921993blog\.mounted(function(parent){1994 // parent is app1995 // "this" is blog1996});19971998app\.use(blog);1999.2000.fi2001.2002.IP "" 02003.2004.SS "app\.register(ext, exports)"2005Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:2006.2007.IP "" 42008.2009.nf20102011 app\.register(\'\.html\', require(\'jade\'));2012.2013.fi2014.2015.IP "" 02016.2017.P2018This is also useful for libraries that may not match extensions correctly\. For example my haml\.js library is installed from npm as "hamljs" so instead of layout\.hamljs, we can register the engine as "\.haml":2019.2020.IP "" 42021.2022.nf20232024 app\.register(\'\.haml\', require(\'haml\-js\'));2025.2026.fi2027.2028.IP "" 02029.2030.P2031For engines that do not comply with the Express specification, we can also wrap their api this way\. Below we map \fI\.md\fR to render markdown files, rendering the html once since it will not change on subsequent calls, and support local substitution in the form of "{name}"\.2032.2033.IP "" 42034.2035.nf20362037 app\.register(\'\.md\', {2038 compile: function(str, options){2039 var html = md\.toHTML(str);2040 return function(locals){2041 return html\.replace(/\e{([^}]+)\e}/g, function(_, name){2042 return locals[name];2043 });2044 };2045 }2046 });2047.2048.fi2049.2050.IP "" 02051.2052.SS "app\.listen([port[, host]])"2053Bind the app server to the given \fIport\fR, which defaults to 3000\. When \fIhost\fR is omitted all connections will be accepted via \fIINADDR_ANY\fR\.2054.2055.IP "" 42056.2057.nf20582059app\.listen();2060app\.listen(3000);2061app\.listen(3000, \'n\.n\.n\.n\');2062.2063.fi2064.2065.IP "" 02066.2067.P2068The \fIport\fR argument may also be a string representing the path to a unix domain socket:2069.2070.IP "" 42071.2072.nf20732074app\.listen(\'/tmp/express\.sock\');2075.2076.fi2077.2078.IP "" 02079.2080.P2081Then try it out:2082.2083.IP "" 42084.2085.nf20862087$ telnet /tmp/express\.sock2088GET / HTTP/1\.120892090HTTP/1\.1 200 OK2091Content\-Type: text/plain2092Content\-Length: 1120932094Hello World2095.2096.fi2097.2098.IP "" 02099
modified:docs/guide.html+264 added-371 removed
196 unmodified lines
197<li><a href="#Template-Engines">Template Engines</a></li>198<li><a href="#Session-Support">Session Support</a></li>199<li><a href="#Migration-Guide">Migration Guide</a></li>200<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">201<li><a href="#req-header-key-defaultValue-">header()</a></li>202<li><a href="#req-accepts-type-">accepts()</a></li>203<li><a href="#req-is-type-">is()</a></li>204<li><a href="#req-param-name-default-">param()</a></li>205<li><a href="#req-flash-type-msg-">flash()</a></li>201<li><a href="#req-header-key-defaultValue">header()</a></li>202<li><a href="#req-accepts-type">accepts()</a></li>203<li><a href="#req-is-type">is()</a></li>204<li><a href="#req-param-name-default">param()</a></li>205<li><a href="#req-flash-type-msg">flash()</a></li>206<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>207</ul></li>208<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">209<li><a href="#res-header-key-val-">header()</a></li>210<li><a href="#res-contentType-type-">contentType()</a></li>211<li><a href="#res-attachment-filename-">attachment()</a></li>212<li><a href="#res-sendfile-path-options-callback-">sendfile()</a></li>213<li><a href="#res-download-file-filename-callback-">download()</a></li>214<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>215<li><a href="#res-redirect-url-status-">redirect()</a></li>216<li><a href="#res-cookie-name-val-options-">cookie()</a></li>217<li><a href="#res-clearCookie-name-">clearCookie()</a></li>218<li><a href="#res-render-view-options-fn-">render()</a></li>219<li><a href="#res-partial-view-options-">partial()</a></li>220<li><a href="#res-local-name-val-">local()</a></li>209<li><a href="#res-header-key-val">header()</a></li>210<li><a href="#res-charset">charset</a></li>211<li><a href="#res-contentType-type">contentType()</a></li>212<li><a href="#res-attachment-filename">attachment()</a></li>213<li><a href="#res-sendfile-path-options-callback">sendfile()</a></li>214<li><a href="#res-download-file-filename-callback">download()</a></li>215<li><a href="#res-send-body-status-headers-status-status">send()</a></li>216<li><a href="#res-redirect-url-status">redirect()</a></li>217<li><a href="#res-cookie-name-val-options">cookie()</a></li>218<li><a href="#res-clearCookie-name">clearCookie()</a></li>219<li><a href="#res-render-view-options-fn">render()</a></li>220<li><a href="#res-partial-view-options">partial()</a></li>221<li><a href="#res-local-name-val">local()</a></li>222<li><a href="#res-local-obj">local()</a></li>223</ul></li>224<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">223<li><a href="#app-set-name-val-">set()</a></li>224<li><a href="#app-enable-name-">enable()</a></li>225<li><a href="#app-enabled-name-">enabled()</a></li>226<li><a href="#app-disable-name-">disable()</a></li>227<li><a href="#app-disabled-name-">disabled()</a></li>228<li><a href="#app-configure-env-function-function-">configure()</a></li>229<li><a href="#app-redirect-name-val-">redirect()</a></li>230<li><a href="#app-error-function-">error()</a></li>231<li><a href="#app-helpers-obj-">helpers()</a></li>232<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>233<li><a href="#app-mounted-fn-">mounted()</a></li>234<li><a href="#app-register-ext-exports-">register()</a></li>235<li><a href="#app-listen-port-host-">listen()</a></li>225<li><a href="#app-set-name-val">set()</a></li>226<li><a href="#app-enable-name">enable()</a></li>227<li><a href="#app-enabled-name">enabled()</a></li>228<li><a href="#app-disable-name">disable()</a></li>229<li><a href="#app-disabled-name">disabled()</a></li>230<li><a href="#app-configure-env-function-function">configure()</a></li>231<li><a href="#app-redirect-name-val">redirect()</a></li>232<li><a href="#app-error-function">error()</a></li>233<li><a href="#app-helpers-obj">helpers()</a></li>234<li><a href="#app-dynamicHelpers-obj">dynamicHelpers()</a></li>235<li><a href="#app-mounted-fn">mounted()</a></li>236<li><a href="#app-register-ext-exports">register()</a></li>237<li><a href="#app-listen-port-host">listen()</a></li>238</ul></li>239</ul>240 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 241 <p id="tagline">
5 unmodified lines
247 <li><a href="guide.html">Guide</a></li>248 <li><a href="screencasts.html">Screencasts</a></li>249 <li><a href="applications.html">Applications</a></li>250 </ul>249<div class='mp'>250<h2 id="Express">Express</h2>251<p class="man-name">252 <code>guide</code>253</p>251<h3 id="Installation">Installation</h3>252256<pre><code>$ npm install express257</code></pre>253<pre><code>$ npm install express</code></pre>254255<h3 id="Creating-A-Server">Creating A Server</h3>256257<p> To create an instance of the <em>express.HTTPServer</em>, simply invoke the <em>createServer()</em> method. With our instance <em>app</em> we can then define routes based on the HTTP verbs, in this example <em>app.get()</em>.</p>
3 unmodified lines
261app.get('/', function(req, res){262 res.send('hello world');263});264269app.listen(3000);270</code></pre>265app.listen(3000);</code></pre>266267<h3 id="Creating-An-HTTPS-Server">Creating An HTTPS Server</h3>268269<p> To initialize a <em>express.HTTPSServer</em> we do the same as above, however we270 pass an options object, accepting <em>key</em>, <em>cert</em> and the others mentioned in node's <a href="http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer">https documentation</a>.</p>271277<pre><code> var app = require('express').createServer({ key: ... });278</code></pre>272<pre><code> var app = require('express').createServer({ key: ... });</code></pre>273274<h3 id="Configuration">Configuration</h3>275276<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers277can use the <em>configure()</em> method to setup needs required by the current environment. When284<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment278<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment 279prior to the environment specific callback.</p>280281<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces282in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.283Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,284otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>285286<pre><code>app.configure(function(){293 app.use(express.methodOverride());294 app.use(express.bodyParser());295 app.use(app.router);287 app.use(express.methodOverride());288 app.use(express.bodyParser());289 app.use(app.router);290});291292app.configure('development', function(){299 app.use(express.static(__dirname + '/public'));300 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));293 app.use(express.static(__dirname + '/public'));294 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));295});296297app.configure('production', function(){298 var oneYear = 31557600000;305 app.use(express.static({ root: __dirname + '/public', maxAge: oneYear }));299 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));300 app.use(express.errorHandler());307});308</code></pre>301});</code></pre>302303<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>304305<pre><code> app.configure(function(){
8 unmodified lines
314 // same as app.set('some feature', false);315316 app.enabled('some feature')317 // =&gt; false325 });326</code></pre>318 });</code></pre>319328<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>320<p>To alter the environment we can set the <em>NODE</em>ENV_ environment variable, for example:</p>321330<pre><code>$ NODE_ENV=production node app.js331</code></pre>322<pre><code>$ NODE_ENV=production node app.js</code></pre>323324<p>This is <em>very</em> important, as many caching mechanisms are <em>only enabled</em> when in production.</p>325326<h3 id="Settings">Settings</h3>327328<p>Express supports the following settings out of the box:</p>329339<ul>340<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>341<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>342<li><em>view engine</em> Default view engine name for views rendered without extensions</li>343<li><em>view options</em> An object specifying global view options</li>344</ul>330<ul><li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li><li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li><li><em>view engine</em> Default view engine name for views rendered without extensions</li><li><em>view options</em> An object specifying global view options</li></ul>331346332<h3 id="Routing">Routing</h3>333334<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.335For example we may want to render a user's account for the path <em>/user/12</em>, this351can be done by defining the route below. The values associated to the named placeholders336can be done by defining the route below. The values associated to the named placeholders 337are available as <code>req.params</code>.</p>338339<pre><code>app.get('/user/:id', function(req, res){355 res.send('user ' + req.params.id);356});357</code></pre>340 res.send('user ' + req.params.id);341});</code></pre>342343<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example344when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>345362<pre><code>\/user\/([^\/]+)\/?363</code></pre>346<pre><code>\/user\/([^\/]+)\/?</code></pre>347348<p>Regular expression literals may also be passed for complex uses. Since capture349groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>. So our first capture group would be <em>req.params[0]</em> and the second would follow as <em>req.params[1]</em>.</p>350351<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){352 res.send(req.params);370});371</code></pre>353});</code></pre>354355<p>Curl requests against the previously defined route:</p>356357<pre><code> $ curl http://dev:3000/user
2 unmodified lines
360 [null,null]361 $ curl http://dev:3000/users/1362 ["1",null]363 $ curl http://dev:3000/users/1..15382 ["1","15"]383</code></pre>364 ["1","15"]</code></pre>365366<p>Below are some route examples, and the associated paths that they367may consume:</p>368
26 unmodified lines
395 /products396397 "/user/:id.:format?"398 /user/12418 /user/12.json419</code></pre>399 /user/12.json</code></pre>400401<p>For example we can <strong>POST</strong> some json, and echo the json back using the <em>bodyParser</em> middleware which will parse json request bodies (as well as others), and place the result in <em>req.body</em>:</p>402403<pre><code>var express = require('express')
4 unmodified lines
408app.post('/', function(req, res){409 res.send(req.body);410});411432app.listen(3000);433</code></pre>412app.listen(3000);</code></pre>413414<p>Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use <em>'/user/:id(\d+)'</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>415416<h3 id="Passing-Route-Control">Passing Route Control</h3>
2 unmodified lines
419the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,420and middleware continue to be invoked in the order that they are added via <em>use()</em>. The same is true for several routes which have the same path defined, they will simply be executed in order until one does <em>not</em> call <em>next()</em> and decides to respond.</p>421422<pre><code>app.get('/users/:id?', function(req, res, next){444 var id = req.params.id;445 if (id) {446 // do something447 } else {448 next();449 }423 var id = req.params.id;424 if (id) {425 // do something426 } else {427 next();428 }429});430431app.get('/users', function(req, res){453 // do something else454});455</code></pre>432 // do something else433});</code></pre>434435<p>The <em>app.all()</em> method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to <em>req.user</em>.</p>436437<pre><code>var express = require('express')
25 unmodified lines
463app.get('*', function(req, res){464 res.send('what???', 404);465});466489app.listen(3000); 490</code></pre>467app.listen(3000); </code></pre>468469<h3 id="Middleware">Middleware</h3>470471<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be
1 unmodified line
473474<pre><code> var express = require('express');475476var app = express.createServer(500 express.logger()501 , express.bodyParser()502 );503</code></pre>477 express.logger()478 , express.bodyParser()479 );</code></pre>480481<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>482507<pre><code>app.use(express.logger({ format: ':method :uri' }));508</code></pre>483<pre><code>app.use(express.logger({ format: ':method :uri' }));</code></pre>484485<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>486487<pre><code>var connect = require('connect');488app.use(connect.logger());514app.use(connect.bodyParser());515</code></pre>489app.use(connect.bodyParser());</code></pre>490491<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>492493<pre><code>app.use(express.logger());520app.use(express.bodyParser());521</code></pre>494app.use(express.bodyParser());</code></pre>495496<h3 id="Route-Middleware">Route Middleware</h3>497498<p>Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.</p>499527<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>500<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user. </p>501502<pre><code>app.get('/user/:id', function(req, res, next){503 loadUser(req.params.id, function(err, user){504 if (err) return next(err);505 res.send('Viewing user ' + user.name);506 });534});535</code></pre>507});</code></pre>508537<p>To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time.</p>509<p>To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time. </p>510511<pre><code>function loadUser(req, res, next) {512 // You would fetch your user from the db513 var user = users[req.params.id];
6 unmodified lines
520}521522app.get('/user/:id', loadUser, function(req, res){523 res.send('Viewing user ' + req.user.name);552});553</code></pre>524});</code></pre>525526<p>Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.</p>527528<pre><code>function andRestrictToSelf(req, res, next) {
3 unmodified lines
532}533534app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){535 res.send('Editing user ' + req.user.name);565});566</code></pre>536});</code></pre>537538<p>Keeping in mind that middleware are simply functions, we can define function that <em>returns</em> the middleware in order to create a more expressive and flexible solution as shown below.</p>539540<pre><code>function andRestrictTo(role) {
5 unmodified lines
546}547548app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){549 res.send('Deleted user ' + req.user.name);580});581</code></pre>550});</code></pre>551552<p>Commonly used "stacks" of middleware can be passed as an array (<em>applied recursively</em>), which can be mixed and matched to any degree.</p>553554<pre><code>var a = [middleware1, middleware2]
4 unmodified lines
559app.get('/bar', a, function(){});560561app.get('/', a, middleware3, middleware4, function(){});562app.get('/', a, b, function(){});594app.get('/', all, function(){});595</code></pre>563app.get('/', all, function(){});</code></pre>564565<p>For this example in full, view the <a href="http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js">route middleware example</a> in the repository.</p>566567<h3 id="HTTP-Methods">HTTP Methods</h3>
5 unmodified lines
573<pre><code> &lt;form method="post" action="/"&gt;574 &lt;input type="text" name="user[name]" /&gt;575 &lt;input type="text" name="user[email]" /&gt;576 &lt;input type="submit" value="Submit" /&gt;609 &lt;/form&gt;610</code></pre>577 &lt;/form&gt;</code></pre>578579<p>By default Express does not know what to do with this request body, so we should add the <em>bodyParser</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> and <em>application/json</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>580614<pre><code>app.use(express.bodyParser());615</code></pre>581<pre><code>app.use(express.bodyParser());</code></pre>582583<p>Our route below will now have access to the <em>req.body.user</em> object which will contain the <em>name</em> and <em>email</em> properties when defined.</p>584585<pre><code>app.post('/', function(req, res){586 console.log(req.body.user);587 res.redirect('back');622});623</code></pre>588});</code></pre>589590<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyParser</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>591592<pre><code>app.use(express.bodyParser());628app.use(express.methodOverride());629</code></pre>593app.use(express.methodOverride());</code></pre>594595<p>The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as <em>PUT</em> and <em>DELETE</em> can still be accessed by clients which can use them directly, although <em>methodOverride</em> provides a great solution for forms. Below shows what the usage of <em>PUT</em> might look like:</p>596597<pre><code>&lt;form method="post" action="/"&gt;
5 unmodified lines
603604app.put('/', function(){605 console.log(req.body.user);606 res.redirect('back');643});644</code></pre>607});</code></pre>608609<h3 id="Error-Handling">Error Handling</h3>610611<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,
13 unmodified lines
625});626627app.get('/500', function(req, res){628 throw new Error('keyboard cat!');666});667</code></pre>629});</code></pre>630631<p>We can call <em>app.error()</em> several times as shown below.632Here we check for an instanceof <em>NotFound</em> and show the633404 page, or we pass on to the next error handler.</p>634635<p>Note that these handlers can be defined anywhere, as they674will be placed below the route handlers on <em>listen()</em>. This636will be placed below the route handlers on <em>listen()</em>. This 637allows for definition within <em>configure()</em> blocks so we can638handle exceptions in different ways based on the environment.</p>639640<pre><code>app.error(function(err, req, res, next){
1 unmodified line
642 res.render('404.jade');643 } else {644 next(err);645 }684});685</code></pre>646});</code></pre>647648<p>Here we assume all errors as 500 for the simplicity of649this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the <em>error.code</em> of <em>ENOENT</em>, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.</p>650651<pre><code>app.error(function(err, req, res){652 res.render('500.jade', {653 error: err654 });694});695</code></pre>655});</code></pre>656657<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware698to report on exceptions. For example if we wish to output exceptions658to report on exceptions. For example if we wish to output exceptions 659in "development" mode to <em>stderr</em> we can use:</p>660701<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));702</code></pre>661<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));</code></pre>662663<p>Also during development we may want fancy html pages to show exceptions664that are passed or thrown, so we can set <em>showStack</em> to true:</p>665707<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));708</code></pre>666<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));</code></pre>667668<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>669is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>670
5 unmodified lines
676 User.get(req.params.userId, function(err, user){677 if (err) return next(err);678 res.send('user ' + user.name);679 });722}); 723</code></pre>680}); </code></pre>681682<p>With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>683684<pre><code>app.param('userId', function(req, res, next, id){
2 unmodified lines
687 if (!user) return next(new Error('failed to find user'));688 req.user = user;689 next();690 });734});735</code></pre>691});</code></pre>692693<p>Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:</p>694695<pre><code>app.get('/user/:userId', function(req, res){696 res.send('user ' + req.user.name);741});742</code></pre>697});</code></pre>698699<p>For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to <em>next(err)</em>.</p>700746<pre><code>app.param('number', function(n){ return parseInt(n, 10); });747</code></pre>701<pre><code>app.param('number', function(n){ return parseInt(n, 10); });</code></pre>702703<p>We may also apply the same callback to several placeholders, for example a route GET <em>/commits/:from-:to</em> are both numbers, so we may define them as an array:</p>704751<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });752</code></pre>705<pre><code>app.param(['from', 'to'], function(n){ return parseInt(n, 10); });</code></pre>706707<h3 id="View-Rendering">View Rendering</h3>708756<p>View filenames take the form "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name709<p>View filenames take the form "&amp;lt;name&amp;gt;.&amp;lt;engine&amp;gt;", where &amp;lt;engine&amp;gt; is the name710of the module that will be required. For example the view <em>layout.ejs</em> will711tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.compile(str, options)</em>, and return a <em>Function</em> to comply with Express. To alter this behaviour712<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.</p>713714<p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,762and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as715and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as 716the <em>body</em> local variable in <em>layout.jade</em>.</p>717718<pre><code>app.get('/', function(req, res){766 res.render('index.jade', { title: 'My Site' });767});768</code></pre>719 res.render('index.jade', { title: 'My Site' });720});</code></pre>721722<p>The new <em>view engine</em> setting allows us to specify our default template engine,723so for example when using jade we could set:</p>724773<pre><code>app.set('view engine', 'jade');774</code></pre>725<pre><code>app.set('view engine', 'jade');</code></pre>726727<p>Allowing us to render with:</p>728778<pre><code>res.render('index');779</code></pre>729<pre><code>res.render('index');</code></pre>730731<p>vs:</p>732783<pre><code>res.render('index.jade');784</code></pre>733<pre><code>res.render('index.jade');</code></pre>734735<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still736mix and match template engines:</p>737789<pre><code>res.render('another-page.ejs');790</code></pre>738<pre><code>res.render('another-page.ejs');</code></pre>739740<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>741742<pre><code>app.set('view options', {743 layout: false796});797</code></pre>744});</code></pre>745746<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>747801<pre><code>res.render('myview.ejs', { layout: true });802</code></pre>748<pre><code>res.render('myview.ejs', { layout: true });</code></pre>749750<p>When an alternate layout is required, we may also specify a path. For example if we have <em>view engine</em> set to <em>jade</em> and a file named <em>./views/mylayout.jade</em> we can simply pass:</p>751806<pre><code>res.render('page', { layout: 'mylayout' });807</code></pre>752<pre><code>res.render('page', { layout: 'mylayout' });</code></pre>753754<p>Otherwise we must specify the extension:</p>755811<pre><code>res.render('page', { layout: 'mylayout.jade' });812</code></pre>756<pre><code>res.render('page', { layout: 'mylayout.jade' });</code></pre>757758<p>These paths may also be absolute:</p>759816<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });817</code></pre>760<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });</code></pre>761762<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>763764<pre><code>app.set('view options', {765 open: '{{',766 close: '}}'824});825</code></pre>767});</code></pre>768769<h3 id="View-Partials">View Partials</h3>770771<p>The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating830in a view to display comments, we would use a partial with collection support:</p>772in a view to display comments, we could use partial collection:</p>773832<pre><code>partial('comment', { collection: comments });833</code></pre>774<pre><code>partial('comment', { collection: comments });</code></pre>775835<p>If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>776<p>If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>777837<pre><code>partial('comment', comments);838</code></pre>778<pre><code>partial('comment', comments);</code></pre>779840<p>When using the partial collection support a few "magic" variables are provided780<p>When using the partial collection support a few "magic" locals are provided781for free:</p>782843<ul>844<li><em>firstInCollection</em> true if this is the first object</li>845<li><em>indexInCollection</em> index of the object in the collection</li>846<li><em>lastInCollection</em> true if this is the last object</li>847<li><em>collectionLength</em> length of the collection</li>848</ul>783<ul><li><em>firstInCollection</em> true if this is the first object</li><li><em>indexInCollection</em> index of the object in the collection</li><li><em>lastInCollection</em> true if this is the last object</li><li><em>collectionLength</em> length of the collection</li></ul>784850785<p>Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well. So for example if we were to render a blog post with <em>partial('blog/post', post)</em> it would generate the <em>post</em> local, but the view calling this function had the local <em>user</em>, it would be available to the <em>blog/post</em> view as well.</p>786787<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>788
10 unmodified lines
799<h3 id="Template-Engines">Template Engines</h3>800801<p>Below are a few template engines commonly used with Express:</p>802869<ul>870<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>871<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>872<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>873<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>874</ul>803<ul><li><a href="http://github.com/visionmedia/haml.js">Haml</a> haml implementation</li><li><a href="http://jade-lang.com">Jade</a> haml.js successor</li><li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li><li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li><li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li></ul>804876805<h3 id="Session-Support">Session Support</h3>806807<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieParser</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>808809<pre><code>app.use(express.cookieParser());882app.use(express.session({ secret: "keyboard cat" }));883</code></pre>810app.use(express.session({ secret: "keyboard cat" }));</code></pre>811812<p>By default the <em>session</em> middleware uses the memory store bundled with Connect, however many implementations exist. For example <a href="http://github.com/visionmedia/connect-redis">connect-redis</a> supplies a <a href="http://code.google.com/p/redis/">Redis</a> session store and can be used as shown below:</p>813814<pre><code>var RedisStore = require('connect-redis');815app.use(express.cookieParser());889app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));890</code></pre>816app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));</code></pre>817818<p>Now the <em>req.session</em> and <em>req.sessionStore</em> properties will be accessible to all routes and subsequent middleware. Properties on <em>req.session</em> are automatically saved on a response, so for example if we wish to shopping cart data:</p>819820<pre><code>var RedisStore = require('connect-redis');
16 unmodified lines
837 if (req.session.items &amp;&amp; req.session.items.length) {838 req.flash('info', 'You have %s items in your cart', req.session.items.length);839 }840 res.render('shopping-cart');915});916</code></pre>841});</code></pre>842843<p>The <em>req.session</em> object also has methods such as <em>Session#touch()</em>, <em>Session#destroy()</em>, <em>Session#regenerate()</em> among others to maintain and manipulate sessions. For more information view the <a href="http://senchalabs.github.com/connect/middleware-session.html">Connect Session</a> documentation.</p>844845<h3 id="Migration-Guide">Migration Guide</h3>846847<p> Express 1.x developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application to work with Express 2.x, Connect 1.x, and Node 0.4.x.</p>848924<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>849<h3 id="req-header-key-defaultValue">req.header(key[, defaultValue])</h3>850851<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>852853<pre><code>req.header('Host');854req.header('host');930req.header('Accept', '*/*');931</code></pre>855req.header('Accept', '*/*');</code></pre>856857<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>858859<pre><code>// sent Referrer: http://google.com
1 unmodified line
861req.header('Referer');862// =&gt; "http://google.com"863864req.header('Referrer');941// =&gt; "http://google.com"942</code></pre>865// =&gt; "http://google.com"</code></pre>866944<h3 id="req-accepts-type-">req.accepts(type)</h3>867<h3 id="req-accepts-type">req.accepts(type)</h3>868869<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>870871<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise
13 unmodified lines
885// =&gt; true886887req.accepts('image/png');888req.accepts('png');966// =&gt; false967</code></pre>889// =&gt; false</code></pre>890969<h3 id="req-is-type-">req.is(type)</h3>891<h3 id="req-is-type">req.is(type)</h3>892893<p>Check if the incoming request contains the <em>Content-Type</em>894header field, and it contains the give mime <em>type</em>.</p>895
7 unmodified lines
903 req.is('application/json');904 // =&gt; true905906 req.is('html');985 // =&gt; false986</code></pre>907 // =&gt; false</code></pre>908909<p>Ad-hoc callbacks can also be registered with Express, to perform910assertions again the request, for example if we need an expressive911way to check if our incoming request is an image, we can register <em>"an image"</em>912callback:</p>913914<pre><code> app.is('an image', function(req){915 return 0 == req.headers['content-type'].indexOf('image');995 });996</code></pre>916 });</code></pre>917918<p>Now within our route callbacks, we can use to to assert content types919such as <em>"image/jpeg"</em>, <em>"image/png"</em>, etc.</p>920
2 unmodified lines
923 // do something924 } else {925 next();926 }1007 });1008</code></pre>927 });</code></pre>928929<p>Keep in mind this method is <em>not</em> limited to checking <em>Content-Type</em>, you930can perform any request assertion you wish.</p>931932<p>Wildcard matches can also be made, simplifying our example above for <em>"an image"</em>, by asserting the <em>subtype</em> only:</p>9331015<pre><code>req.is('image/*');1016</code></pre>934<pre><code>req.is('image/*');</code></pre>935936<p>We may also assert the <em>type</em> as shown below, which would return true for <em>"application/json"</em>, and <em>"text/json"</em>.</p>9371020<pre><code>req.is('*/json');1021</code></pre>938<pre><code>req.is('*/json');</code></pre>9391023<h3 id="req-param-name-default-">req.param(name[, default])</h3>940<h3 id="req-param-name-default">req.param(name[, default])</h3>941942<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>9431027<ul>1028<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>1029<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1030<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1031</ul>944<ul><li>Checks route params (<em>req.params</em>), ex: /user/:id</li><li>Checks query string params (<em>req.query</em>), ex: ?id=12</li><li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li></ul>9451033946<p>To utilize urlencoded request bodies, <em>req.body</em>947should be an object. This can be done by using948the _express.bodyParser middleware.</p>9491038<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>950<h3 id="req-flash-type-msg">req.flash(type[, msg])</h3>951952<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>953954<pre><code>req.flash('info', 'email sent');
7 unmodified lines
962req.flash('info');963// =&gt; []964965req.flash();1054// =&gt; { error: ['email delivery failed'], info: [] }1055</code></pre>966// =&gt; { error: ['email delivery failed'], info: [] }</code></pre>967968<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>9691059<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);1060</code></pre>970<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);</code></pre>971972<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>973974<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header975to see if it was issued by an <em>XMLHttpRequest</em>:</p>976977<pre><code>req.xhr1068req.isXMLHttpRequest1069</code></pre>978req.isXMLHttpRequest</code></pre>9791071<h3 id="res-header-key-val-">res.header(key[, val])</h3>980<h3 id="res-header-key-val">res.header(key[, val])</h3>981982<p>Get or set the response header <em>key</em>.</p>983984<pre><code>res.header('Content-Length');
2 unmodified lines
987res.header('Content-Length', 123);988// =&gt; 123989990res.header('Content-Length');1082// =&gt; 1231083</code></pre>991// =&gt; 123</code></pre>9921085<h3 id="res-contentType-type-">res.contentType(type)</h3>993<h3 id="res-charset">res.charset</h3>994995<p>Sets the charset for subsequent <code>Content-Type</code> header fields. For example <code>res.send()</code> and <code>res.render()</code> default to "utf8", so we may explicitly set the charset before rendering a template:</p>996997<pre><code>res.charset = 'ISO-8859-1';998res.render('users');</code></pre>9991000<p>or before responding with <code>res.send()</code>:</p>10011002<pre><code>res.charset = 'ISO-8859-1';1003res.send(str);</code></pre>10041005<p>or with node's <code>res.end()</code>:</p>10061007<pre><code>res.charset = 'ISO-8859-1';1008res.header('Content-Type', 'text/plain');1009res.end(str);</code></pre>10101011<h3 id="res-contentType-type">res.contentType(type)</h3>10121013<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>10141015<pre><code> var filename = 'path/to/image.png';1016 res.contentType(filename);1091 // Content-Type is now "image/png"1092</code></pre>1017 // Content-Type is now "image/png"</code></pre>10181094<h3 id="res-attachment-filename-">res.attachment([filename])</h3>1019<p>A literal <em>Content-Type</em> works as well:</p>10201021<pre><code> res.contentType('application/json');</code></pre>10221023<p>Or simply the extension without leading <code>.</code>:</p>10241025<pre><code> res.contentType('json');</code></pre>10261027<h3 id="res-attachment-filename">res.attachment([filename])</h3>10281029<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>10301098<pre><code> res.attachment('path/to/my/image.png');1099</code></pre>1031<pre><code> res.attachment('path/to/my/image.png');</code></pre>10321101<h3 id="res-sendfile-path-options-callback-">res.sendfile(path[, options[, callback]])</h3>1033<h3 id="res-sendfile-path-options-callback">res.sendfile(path[, options[, callback]])</h3>10341103<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>1035<p>Used by <code>res.download()</code> to transfer an arbitrary file. </p>10361105<pre><code>res.sendfile('path/to/my.file');1106</code></pre>1037<pre><code>res.sendfile('path/to/my.file');</code></pre>10381039<p>This method accepts an optional callback which is called when1040an error occurs, or when the transfer is complete. By default failures call <code>next(err)</code>, however when a callback is supplied you must do this explicitly, or act on the error.</p>1041
2 unmodified lines
1044 next(err);1045 } else {1046 console.log('transferred %s', path);1047 }1117});1118</code></pre>1048});</code></pre>10491050<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>10511052<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1053 // handle1124});1125</code></pre>1054});</code></pre>10551127<h3 id="res-download-file-filename-callback-">res.download(file[, filename[, callback]])</h3>1056<h3 id="res-download-file-filename-callback">res.download(file[, filename[, callback]])</h3>10571058<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>10591060<pre><code>res.download('path/to/image.png');1132res.download('path/to/image.png', 'foo.png');1133</code></pre>1061res.download('path/to/image.png', 'foo.png');</code></pre>10621063<p>This is equivalent to:</p>10641065<pre><code>res.attachment(file);1138res.sendfile(file);1139</code></pre>1066res.sendfile(file);</code></pre>10671068<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>:</p>10691070<pre><code>res.download(path, 'expenses.doc', function(err){1071 // handle1145});1146</code></pre>1072});</code></pre>10731148<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>1074<h3 id="res-send-body-status-headers-status-status">res.send(body|status[, headers|status[, status]])</h3>10751076<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1077objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>1078
2 unmodified lines
1081 res.send({ some: 'json' });1082 res.send('&lt;p&gt;some html&lt;/p&gt;');1083 res.send('Sorry, cant find that', 404);1084 res.send('text', { 'Content-Type': 'text/plain' }, 201);1159 res.send(404);1160</code></pre>1085 res.send(404);</code></pre>10861087<p>By default the <em>Content-Type</em> response header is set, however if explicitly1088assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1089it will not be set again.</p>10901091<p>Note that this method <em>end()</em>s the response, so you will want to use node's <em>res.write()</em> for multiple writes or streaming.</p>10921168<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>1093<h3 id="res-redirect-url-status">res.redirect(url[, status])</h3>10941095<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>10961097<pre><code>res.redirect('/', 301);1098res.redirect('/account');1099res.redirect('http://google.com');1100res.redirect('home');1176res.redirect('back');1177</code></pre>1101res.redirect('back');</code></pre>11021103<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.1104The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes1105the "home" setting and defaults to "/".</p>11061183<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>1107<h3 id="res-cookie-name-val-options">res.cookie(name, val[, options])</h3>11081109<p>Sets the given cookie <em>name</em> to <em>val</em>, with options <em>httpOnly</em>, <em>secure</em>, <em>expires</em> etc.</p>11101111<pre><code>// "Remember me" for 15 minutes 1188res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1189</code></pre>1112res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });</code></pre>11131114<p>The <em>maxAge</em> property may be used to set <em>expires</em> relative to <em>Date.now()</em> in milliseconds, so our example above can now become:</p>11151193<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });1194</code></pre>1116<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });</code></pre>11171118<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>11191120<pre><code>app.use(express.cookieParser());11211122app.get('/', function(req, res){1123 // use req.cookies.rememberme1202});1203</code></pre>1124});</code></pre>11251205<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>1126<h3 id="res-clearCookie-name">res.clearCookie(name)</h3>11271128<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>11291209<pre><code>res.clearCookie('rememberme');1210</code></pre>1130<pre><code>res.clearCookie('rememberme');</code></pre>11311212<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>1132<h3 id="res-render-view-options-fn">res.render(view[, options[, fn]])</h3>11331134<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1135When a callback function is given a response will <em>not</em> be made1136automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>11371138<p>The <em>options</em> passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:</p>11391140<pre><code>var user = { name: 'tj' };1221res.render('index', { layout: false, user: user });1222</code></pre>1141res.render('index', { layout: false, user: user });</code></pre>11421224<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>1143<h3 id="res-partial-view-options">res.partial(view[, options])</h3>11441145<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1146to the view as a local variable.</p>11471229<ul>1230<li><em>object</em> the object named by <em>as</em> or derived from the view name</li>1231<li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p>1148<ul><li><em>object</em> the object named by <em>as</em> or derived from the view name</li><li><p><em>as</em> Variable name for each <em>collection</em> or <em>object</em> value, defaults to the view name.</p><ul><li>as: 'something' will add the <em>something</em> local variable</li><li>as: this will use the collection value as the template context</li><li><p>as: global will merge the collection value's properties with <em>locals</em></p></li></ul></li><li><p><em>collection</em> Array of objects, the name is derived from the view name itself. 1149For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li></ul>11501233<ul>1234<li>as: 'something' will add the <em>something</em> local variable</li>1235<li>as: this will use the collection value as the template context</li>1236<li>as: global will merge the collection value's properties with <em>locals</em></li>1237</ul>1238</li>1239<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.1240For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>1241</ul>124212431151<p>The following are equivalent, and the name of collection value when passed1152to the partial will be <em>movie</em> as derived from the name.</p>11531154<pre><code>partial('theatre/movie.jade', { collection: movies });1155partial('theatre/movie.jade', movies);1156partial('movie.jade', { collection: movies });1157partial('movie.jade', movies);1158partial('movie', movies);1252// In view: movie.director1253</code></pre>1159// In view: movie.director</code></pre>11601161<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>11621163<pre><code>partial('movie', { collection: movies, as: 'video' });1258// In view: video.director1259</code></pre>1164// In view: video.director</code></pre>11651166<p>Also we can make our movie the value of <em>this</em> within our view so that instead1167of <em>movie.director</em> we could use <em>this.director</em>.</p>11681169<pre><code>partial('movie', { collection: movies, as: this });1265// In view: this.director1266</code></pre>1170// In view: this.director</code></pre>11711268<p>Another alternative is to "explode" the properties of the collection item into1172<p>Another alternative is to "expand" the properties of the collection item into1173pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>11741175<pre><code>partial('movie', { collection: movies, as: global });1272// In view: director1273</code></pre>1176// In view: director</code></pre>11771178<p>This same logic applies to a single partial object usage:</p>11791180<pre><code>partial('movie', { object: movie, as: this });
5 unmodified lines
1186partial('movie', { object: movie, as: 'video' });1187// In view: video.director11881189partial('movie', { object: movie });1287// In view: movie.director1288</code></pre>1190// In view: movie.director</code></pre>11911192<p>When a non-collection (does <em>not</em> have <em>.length</em>) is passed as the second argument, it is assumed to be the <em>object</em>, after which the object's local variable name is derived from the view name:</p>11931292<pre><code>partial('movie', movie);1293// =&gt; In view: movie.director1294</code></pre>1194<pre><code>var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1195partial('movie', movie)1196// =&gt; In view: movie.director</code></pre>11971198<p>The exception of this, is when a "plain" object, aka "{}" or "new Object" is passed, which is considered an object with local variable. For example some may expect a "movie" local with the following, however since it is a plain object "director" and "title" are simply locals:</p>11991200<pre><code>var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1201partial('movie', movie)</code></pre>12021203<p>For cases like this where passing a plain object is desired, simply assign it to a key, or use the <code>object</code> key which will use the filename-derived variable name. The examples below are equivalent:</p>12041205<pre><code> partial('movie', { locals: { movie: movie }})1206 partial('movie', { movie: movie })1207 partial('movie', { object: movie })</code></pre>12081209<p>This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:</p>12101211<pre><code>app.get('/users', function(req, res){1212 if (req.xhr) {
5 unmodified lines
1218 // which internally does partial('user', users)1219 // along with other UI1220 res.render('users', { users: users });1221 }1309});1310</code></pre>1222});</code></pre>12231312<h3 id="res-local-name-val-">res.local(name[, val])</h3>1224<h3 id="res-local-name-val">res.local(name[, val])</h3>12251226<p>Get or set the given local variable <em>name</em>. The locals built up for a response are applied to those given to the view rendering methods such as <code>res.render()</code>.</p>12271228<pre><code> app.all('/movie/:id', function(req, res, next){
6 unmodified lines
1235 app.get('/movie/:id', function(req, res){1236 // movie is already a local, however we1237 // can pass more if we wish1238 res.render('movie', { displayReviews: true });1327 });1328</code></pre>1239 });</code></pre>12401330<h3 id="app-set-name-val-">app.set(name[, val])</h3>1241<h3 id="res-local-obj">res.local(obj)</h3>12421243<p> Assign several locals with the given <em>obj</em>. The following are equivalent:</p>12441245<pre><code> res.local('foo', bar);1246 res.local('bar', baz);12471248 res.locals({ foo: bar, bar, baz });</code></pre>12491250<h3 id="app-set-name-val">app.set(name[, val])</h3>12511252<p>Apply an application level setting <em>name</em> to <em>val</em>, or1253get the value of <em>name</em> when <em>val</em> is not present:</p>12541255<pre><code>app.set('views', __dirname + '/views');1256app.set('views');1337// =&gt; ...path...1338</code></pre>1257// =&gt; ...path...</code></pre>12581259<p>Alternatively you may simply access the settings via <em>app.settings</em>:</p>12601261<pre><code>app.settings.views1343// =&gt; ...path...1344</code></pre>1262// =&gt; ...path...</code></pre>12631346<h3 id="app-enable-name-">app.enable(name)</h3>1264<h3 id="app-enable-name">app.enable(name)</h3>12651266<p>Enable the given setting <em>name</em>:</p>12671268<pre><code>app.enable('some arbitrary setting');1269app.set('some arbitrary setting');1270// =&gt; true12711272app.enabled('some arbitrary setting');1355// =&gt; true1356</code></pre>1273// =&gt; true</code></pre>12741358<h3 id="app-enabled-name-">app.enabled(name)</h3>1275<h3 id="app-enabled-name">app.enabled(name)</h3>12761277<p>Check if setting <em>name</em> is enabled:</p>12781279<pre><code>app.enabled('view cache');1280// =&gt; false12811282app.enable('view cache');1283app.enabled('view cache');1367// =&gt; true1368</code></pre>1284// =&gt; true</code></pre>12851370<h3 id="app-disable-name-">app.disable(name)</h3>1286<h3 id="app-disable-name">app.disable(name)</h3>12871288<p>Disable the given setting <em>name</em>:</p>12891290<pre><code>app.disable('some setting');1291app.set('some setting');1292// =&gt; false12931294app.disabled('some setting');1379// =&gt; false1380</code></pre>1295// =&gt; false</code></pre>12961382<h3 id="app-disabled-name-">app.disabled(name)</h3>1297<h3 id="app-disabled-name">app.disabled(name)</h3>12981299<p>Check if setting <em>name</em> is disabled:</p>13001301<pre><code>app.enable('view cache');
2 unmodified lines
1304// =&gt; false13051306app.disable('view cache');1307app.disabled('view cache');1393// =&gt; true1394</code></pre>1308// =&gt; true</code></pre>13091396<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>1310<h3 id="app-configure-env-function-function">app.configure(env|function[, function])</h3>13111312<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>13131314<pre><code>app.configure(function(){
1 unmodified line
1316});13171318app.configure('development', function(){1319 // executed for 'development' only1406});1407</code></pre>1320});</code></pre>13211409<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>1322<h3 id="app-redirect-name-val">app.redirect(name, val)</h3>13231324<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>13251413<pre><code>app.redirect('google', 'http://google.com');1414</code></pre>1326<pre><code>app.redirect('google', 'http://google.com');</code></pre>13271328<p>Now in a route we may call:</p>13291330<p> res.redirect('google');</p>
1 unmodified line
1332<p>We may also map dynamic redirects:</p>13331334<pre><code>app.redirect('comments', function(req, res){1335 return '/post/' + req.params.id + '/comments';1424});1425</code></pre>1336});</code></pre>13371338<p>So now we may do the following, and the redirect will dynamically adjust to1339the context of the request. If we called this route with <em>GET /post/12</em> our1340redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>13411342<pre><code>app.get('/post/:id', function(req, res){1343 res.redirect('comments');1433});1434</code></pre>1344});</code></pre>13451346<p>When mounted, <em>res.redirect()</em> will respect the mount-point. For example if a blog app is mounted at <em>/blog</em>, the following will redirect to <em>/blog/posts</em>:</p>13471438<pre><code>res.redirect('/posts');1439</code></pre>1348<pre><code>res.redirect('/posts');</code></pre>13491441<h3 id="app-error-function-">app.error(function)</h3>1350<h3 id="app-error-function">app.error(function)</h3>13511352<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1353Note that we may set several error handlers by making several calls to this method, however the handler1354should call <em>next(err)</em> if it does not wish to deal with the exception:</p>13551356<pre><code>app.error(function(err, req, res, next){1357 res.send(err.message, 500);1449});1450</code></pre>1358});</code></pre>13591452<h3 id="app-helpers-obj-">app.helpers(obj)</h3>1360<h3 id="app-helpers-obj">app.helpers(obj)</h3>13611362<p>Registers static view helpers.</p>13631456<p> app.helpers({</p>1364<p> app.helpers({1365 name: function(first, last){ return first + ', ' + last }1366 , firstName: 'tj'1367 , lastName: 'holowaychuk'1368 });</p>13691458<pre><code> name: function(first, last){ return first + ', ' + last }1459, firstName: 'tj'1460, lastName: 'holowaychuk'1461</code></pre>14621463<p> });</p>14641370<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1371as well as the <em>name()</em> function exposed.</p>13721468<pre><code>&lt;%= name(firstName, lastName) %>1469</code></pre>1373<pre><code>&lt;%= name(firstName, lastName) %&gt;</code></pre>13741471<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>1375<h3 id="app-dynamicHelpers-obj">app.dynamicHelpers(obj)</h3>13761377<p>Registers dynamic view helpers. Dynamic view helpers1378are simply functions which accept <em>req</em>, <em>res</em>, and are1379evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function
2 unmodified lines
1382<pre><code>app.dynamicHelpers({1383 session: function(req, res){1384 return req.session;1385 }1482});1483</code></pre>1386});</code></pre>13871388<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>13891487<pre><code>&lt;%= session.name %&gt;1488</code></pre>1390<pre><code>&lt;%= session.name %&gt;</code></pre>13911490<h3 id="app-mounted-fn-">app.mounted(fn)</h3>1392<h3 id="app-mounted-fn">app.mounted(fn)</h3>13931394<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>13951396<pre><code>var app = express.createServer(),
3 unmodified lines
1400 // parent is app1401 // "this" is blog1402});14031502app.use(blog);1503</code></pre>1404app.use(blog);</code></pre>14051505<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>1406<h3 id="app-register-ext-exports">app.register(ext, exports)</h3>14071408<p>Register the given template engine <em>exports</em>1409as <em>ext</em>. For example we may wish to map ".html"1410files to jade:</p>14111511<pre><code> app.register('.html', require('jade'));1512</code></pre>1412<pre><code> app.register('.html', require('jade'));</code></pre>14131414<p>This is also useful for libraries that may not1415match extensions correctly. For example my haml.js1416library is installed from npm as "hamljs" so instead1417of layout.hamljs, we can register the engine as ".haml":</p>14181519<pre><code> app.register('.haml', require('haml-js'));1520</code></pre>1419<pre><code> app.register('.haml', require('haml-js'));</code></pre>14201421<p>For engines that do not comply with the Express1422specification, we can also wrap their api this way. Below1423we map <em>.md</em> to render markdown files, rendering the html once
8 unmodified lines
1432 return locals[name];1433 });1434 };1435 }1537 });1538</code></pre>1436 });</code></pre>14371540<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>1438<h3 id="app-listen-port-host">app.listen([port[, host]])</h3>14391440<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1543connections will be accepted via <em>INADDR_ANY</em>.</p>1441connections will be accepted via <em>INADDR</em>ANY_.</p>14421443<pre><code>app.listen();1444app.listen(3000);1547app.listen(3000, 'n.n.n.n');1548</code></pre>1445app.listen(3000, 'n.n.n.n');</code></pre>14461447<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>14481552<pre><code>app.listen('/tmp/express.sock');1553</code></pre>1449<pre><code>app.listen('/tmp/express.sock');</code></pre>14501451<p>Then try it out:</p>14521453<pre><code>$ telnet /tmp/express.sock
2 unmodified lines
1456HTTP/1.1 200 OK1457Content-Type: text/plain1458Content-Length: 1114591564Hello World1565</code></pre>15661567</div>1460Hello World</code></pre>1461 </div>1462 </div>1463 </body>1464</html>
deleted:docs/index.1-126 removed
1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "INDEX" "" "March 2011" "" ""5.6.SH "NAME"7\fBindex\fR8.9.IP "" 410.11.nf1213var app = express\.createServer();1415app\.get(\'/\', function(req, res){16 res\.send(\'Hello World\');17});1819app\.listen(3000);20.21.fi22.23.IP "" 024.25.SH "Features"26.27.IP "\(bu" 428Robust routing29.30.IP "\(bu" 431Redirection helpers32.33.IP "\(bu" 434Dynamic view helpers35.36.IP "\(bu" 437Application level view options38.39.IP "\(bu" 440Content negotiation41.42.IP "\(bu" 443Application mounting44.45.IP "\(bu" 446Focus on high performance47.48.IP "\(bu" 449View rendering and partials support50.51.IP "\(bu" 452Environment based configuration53.54.IP "\(bu" 455Session based flash notifications56.57.IP "\(bu" 458Built on Connect \fIhttp://github\.com/senchalabs/connect\fR59.60.IP "\(bu" 461Executable \fIexecutable\.html\fR for generating applications quickly62.63.IP "\(bu" 464High test coverage65.66.IP "" 067.68.SH "Contributors"69The following are the major contributors of Express (in no specific order)\.70.71.IP "\(bu" 472TJ Holowaychuk (visionmedia \fIhttp://github\.com/visionmedia\fR)73.74.IP "\(bu" 475Ciaran Jessup (ciaranj \fIhttp://github\.com/ciaranj\fR)76.77.IP "\(bu" 478Aaron Heckmann (aheckmann \fIhttp://github\.com/aheckmann\fR)79.80.IP "\(bu" 481Guillermo Rauch (guille \fIhttp://github\.com/guille\fR)82.83.IP "" 084.85.SH "Third\-Party Modules"86The following modules compliment or extend Express directly:87.88.IP "\(bu" 489express\-resource \fIhttp://github\.com/visionmedia/express\-resource\fR provides resourceful routing90.91.IP "\(bu" 492express\-messages \fIhttp://github\.com/visionmedia/express\-messages\fR flash message notification rendering93.94.IP "\(bu" 495express\-configure \fIhttp://github\.com/visionmedia/express\-configure\fR async configuration support (load settings from redis etc)96.97.IP "\(bu" 498express\-namespace \fIhttp://github\.com/visionmedia/express\-namespace\fR namespaced routing support99.100.IP "" 0101.102.SH "More Information"103.104.IP "\(bu" 4105Google Group \fIhttp://groups\.google\.com/group/express\-js\fR for discussion106.107.IP "\(bu" 4108Follow tjholowaychuk \fIhttp://twitter\.com/tjholowaychuk\fR on twitter for updates109.110.IP "\(bu" 4111View the Connect \fIhttp://senchalabs\.github\.com/connect\fR documentation112.113.IP "\(bu" 4114View the Connect Wiki \fIhttp://wiki\.github\.com/senchalabs/connect/\fR for contrib middleware115.116.IP "\(bu" 4117View the examples \fIhttp://github\.com/visionmedia/express/tree/master/examples/\fR118.119.IP "\(bu" 4120View the source \fIhttp://github\.com/visionmedia/express\fR121.122.IP "\(bu" 4123View the contrib guide \fIcontrib\.html\fR124.125.IP "" 0126
modified:docs/index.html+5 added-49 removed
188 unmodified lines
189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193<div class='mp'>194<h2 id="Express">Express</h2>195<p class="man-name">196 <code>index</code>197</p>193<pre><code>var app = express.createServer();194195app.get('/', function(req, res){196 res.send('Hello World');197});198204app.listen(3000);205</code></pre>199app.listen(3000);</code></pre>200201<h2 id="Features">Features</h2>202209<ul>210<li>Robust routing</li>211<li>Redirection helpers</li>212<li>Dynamic view helpers</li>213<li>Application level view options</li>214<li>Content negotiation</li>215<li>Application mounting</li>216<li>Focus on high performance</li>217<li>View rendering and partials support</li>218<li>Environment based configuration</li>219<li>Session based flash notifications</li>220<li>Built on <a href="http://github.com/senchalabs/connect">Connect</a></li>221<li><a href="executable.html">Executable</a> for generating applications quickly</li>222<li>High test coverage</li>223</ul>203<ul><li>Robust routing</li><li>Redirection helpers</li><li>Dynamic view helpers</li><li>Application level view options</li><li>Content negotiation</li><li>Application mounting</li><li>Focus on high performance</li><li>View rendering and partials support</li><li>Environment based configuration</li><li>Session based flash notifications</li><li>Built on <a href="http://github.com/senchalabs/connect">Connect</a></li><li><a href="executable.html">Executable</a> for generating applications quickly</li><li>High test coverage</li></ul>204225205<h2 id="Contributors">Contributors</h2>206207<p>The following are the major contributors of Express (in no specific order).</p>208230<ul>231<li>TJ Holowaychuk (<a href="http://github.com/visionmedia">visionmedia</a>)</li>232<li>Ciaran Jessup (<a href="http://github.com/ciaranj">ciaranj</a>)</li>233<li>Aaron Heckmann (<a href="http://github.com/aheckmann">aheckmann</a>)</li>234<li>Guillermo Rauch (<a href="http://github.com/guille">guille</a>)</li>235</ul>209<ul><li>TJ Holowaychuk (<a href="http://github.com/visionmedia)">visionmedia</a></li><li>Ciaran Jessup (<a href="http://github.com/ciaranj)">ciaranj</a></li><li>Aaron Heckmann (<a href="http://github.com/aheckmann)">aheckmann</a></li><li>Guillermo Rauch (<a href="http://github.com/guille)">guille</a></li></ul>210237211<h2 id="Third-Party-Modules">Third-Party Modules</h2>212213<p>The following modules compliment or extend Express directly:</p>214242<ul>243<li><a href="http://github.com/visionmedia/express-resource">express-resource</a> provides resourceful routing</li>244<li><a href="http://github.com/visionmedia/express-messages">express-messages</a> flash message notification rendering</li>245<li><a href="http://github.com/visionmedia/express-configure">express-configure</a> async configuration support (load settings from redis etc)</li>246<li><a href="http://github.com/visionmedia/express-namespace">express-namespace</a> namespaced routing support</li>247</ul>215<ul><li><a href="http://github.com/visionmedia/express-resource">express-resource</a> provides resourceful routing</li><li><a href="http://github.com/visionmedia/express-messages">express-messages</a> flash message notification rendering</li><li><a href="http://github.com/visionmedia/express-configure">express-configure</a> async configuration support (load settings from redis etc)</li><li><a href="http://github.com/visionmedia/express-namespace">express-namespace</a> namespaced routing support</li></ul>216249217<h2 id="More-Information">More Information</h2>218252<ul>253<li><a href="http://groups.google.com/group/express-js">Google Group</a> for discussion</li>254<li>Follow <a href="http://twitter.com/tjholowaychuk">tjholowaychuk</a> on twitter for updates</li>255<li>View the <a href="http://senchalabs.github.com/connect">Connect</a> documentation</li>256<li>View the <a href="http://wiki.github.com/senchalabs/connect/">Connect Wiki</a> for contrib middleware</li>257<li>View the <a href="http://github.com/visionmedia/express/tree/master/examples/">examples</a></li>258<li>View the <a href="http://github.com/visionmedia/express">source</a></li>259<li>View the <a href="contrib.html">contrib guide</a></li>260</ul>261262263</div>219<ul><li><a href="http://groups.google.com/group/express-js">Google Group</a> for discussion</li><li>Follow <a href="http://twitter.com/tjholowaychuk">tjholowaychuk</a> on twitter for updates</li><li>View the <a href="http://senchalabs.github.com/connect">Connect</a> documentation</li><li>View the <a href="http://wiki.github.com/senchalabs/connect/">Connect Wiki</a> for contrib middleware</li><li>View the <a href="http://github.com/visionmedia/express/tree/master/examples/">examples</a></li><li>View the <a href="http://github.com/visionmedia/express">source</a></li><li>View the <a href="contrib.html">contrib guide</a></li></ul>220 </div>221 </div>222 </body>223</html>
deleted:docs/migrate.1-272 removed
1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "MIGRATE" "" "March 2011" "" ""5.6.SH "NAME"7\fBmigrate\fR8.9.SS "Express 1\.x to 2\.x Migration"10.11.SS "HTTPS"12Creating an HTTPS server is simply, simply pass the TLS options to \fIexpress\.createServer()\fR:13.14.IP "" 415.16.nf1718 var app = express\.createServer({19 key: \.\.\.20 , cert: \.\.\.21 });2223 app\.listen(443);24.25.fi26.27.IP "" 028.29.SS "req\.header() Referrer"30Previously if anyone was doing something similar to:31.32.IP "" 433.34.nf3536 req\.headers\.referrer || req\.headers\.referer37 req\.header(\'Referrer\') || req\.header(\'Referer\')38.39.fi40.41.IP "" 042.43.P44With the new special\-case we may now simply use \fIReferrer\fR which will return either if defined:45.46.IP "" 447.48.nf4950 req\.header(\'Referrer\')51.52.fi53.54.IP "" 055.56.SS "res\.local(name, val)"57Previously all local variables had to be passed to \fIres\.render()\fR, or either \fIapp\.helpers()\fR or \fIapp\.dynamicHelpers()\fR, now we may do this at the request\-level progressively\. The \fIres\.local()\fR method accepts a \fIname\fR and \fIval\fR, however the locals passed to \fIres\.render()\fR will take precedence\.58.59.P60For example we may utilize this feature to create locals in middleware:61.62.IP "" 463.64.nf6566 function loadUser(req, res, next) {67 User\.get(req\.params\.id, function(err, user){68 res\.local(\'user\', user);69 next();70 });71 }7273 app\.get(\'/user/:id\', loadUser, function(req, res){74 res\.render(\'user\');75 });76.77.fi78.79.IP "" 080.81.SS "req\.param(name[, defaultValue])"82Previously only \fIname\fR was accepted, so some of you may have been doing the following:83.84.IP "" 485.86.nf8788 var id = req\.param(\'id\') || req\.user\.id;89.90.fi91.92.IP "" 093.94.P95The new \fIdefaultValue\fR argument can handle this nicely:96.97.IP "" 498.99.nf100101 var id = req\.param(\'id\', req\.user\.id);102.103.fi104.105.IP "" 0106.107.SS "app\.helpers() / app\.locals()"108\fIapp\.locals()\fR is now an alias of \fIapp\.helpers()\fR, as helpers makes more sense for functions\.109.110.SS "req\.accepts(type)"111\fIreq\.accepts()\fR now accepts extensions:112.113.IP "" 4114.115.nf116117 // Accept: text/html118 req\.accepts(\'html\');119 req\.accepts(\'\.html\');120 // => true121122 // Accept: text/*; application/json123 req\.accepts(\'html\');124 req\.accepts(\'text/*\');125 req\.accepts(\'text/plain\');126 req\.accepts(\'application/json\');127 // => true128129 req\.accepts(\'image/png\');130 req\.accepts(\'png\');131 // => false132.133.fi134.135.IP "" 0136.137.SS "res\.cookie()"138Previously only directly values could be passed, so for example:139.140.IP "" 4141.142.nf143144res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000) });145.146.fi147.148.IP "" 0149.150.P151However now we have the alternative \fImaxAge\fR property which may be used to set \fIexpires\fR relative to \fIDate\.now()\fR in milliseconds, so our example above can now become:152.153.IP "" 4154.155.nf156157res\.cookie(\'rememberme\', \'yes\', { maxAge: 900000 });158.159.fi160.161.IP "" 0162.163.SS "res\.download() / res\.sendfile()"164Both of these methods now utilize Connect\'s static file server behind the scenes (actually the previous Express code was ported to Connect 1\.0)\. With this change comes a change to the callback as well\. Previously the \fIpath\fR and \fIstream\fR were passed, however now only an \fIerror\fR is passed, when no error has occurred the callback will be invoked indicating that the file transfer is complete\. The callback remains optional:165.166.IP "" 4167.168.nf169170 res\.download(\'/path/to/file\');171172 res\.download(\'/path/to/file\', function(err){173 if (err) {174 console\.error(err);175 } else {176 console\.log(\'transferred\');177 }178 });179.180.fi181.182.IP "" 0183.184.P185The \fIstream threshold\fR setting was removed\.186.187.SS "res\.render()"188Previously locals were passed as a separate key:189.190.IP "" 4191.192.nf193194 res\.render(\'user\', { layout: false, locals: { user: user }});195.196.fi197.198.IP "" 0199.200.P201In Express 2\.0 both the locals and the options are one in the same, meaning you cannot have a local variable named \fIlayout\fR as it is reserved for express, however this cleans up the API:202.203.IP "" 4204.205.nf206207 res\.render(\'user\', { layout: false, user: user });208.209.fi210.211.IP "" 0212.213.SS "res\.partial()"214Express 2\.0 adds the \fIres\.partial()\fR method, helpful for rendering partial fragments over WebSockets or Ajax requests etc\. The API is identical to the \fIpartial()\fR calls within views\.215.216.IP "" 4217.218.nf219220 // render a collection of comments221 res\.partial(\'comment\', [comment1, comment2]);222223 // render a single comment224 res\.partial(\'comment\', comment);225.226.fi227.228.IP "" 0229.230.SS "Template Engine Compliance"231To comply with Express previously engines needed the following signature:232.233.IP "" 4234.235.nf236237 engine\.render(str, options, function(err){});238.239.fi240.241.IP "" 0242.243.P244Now they must export a \fIcompile()\fR function, returning a function which when called with local variables will render the template\. This allows Express to cache the compiled function in memory during production\.245.246.IP "" 4247.248.nf249250 var fn = engine\.compile(str, options);251 fn(locals);252.253.fi254.255.IP "" 0256.257.SS "View Partial Lookup"258Previously partials were loaded relative to the now removed \fIview partials\fR directory setting, or by default \fIviews/partials\fR, now they are relative to the view calling them, read more on view lookup \fIguide\.html#View\-Lookup\fR\.259.260.SS "Mime Types"261Express and Connect now utilize the \fImime\fR module in npm, so to add more use:262.263.IP "" 4264.265.nf266267 require(\'mime\')\.define({ \'foo/bar\': [\'foo\', \'bar\'] });268.269.fi270.271.IP "" 0272
modified:docs/migrate.html+57 added-46 removed
188 unmodified lines
189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193<div class='mp'>194<h2 id="Express">Express</h2>195<p class="man-name">196 <code>migrate</code>197</p>193<h3 id="Express-1-x-to-2-x-Migration">Express 1.x to 2.x Migration</h3>194195<h3 id="HTTPS">HTTPS</h3>196
3 unmodified lines
200 key: ...201 , cert: ...202 });203209 app.listen(443);210</code></pre>204 app.listen(443);</code></pre>205206<h3 id="req-header-Referrer">req.header() Referrer</h3>207208<p> Previously if anyone was doing something similar to:</p>209210<pre><code> req.headers.referrer || req.headers.referer217 req.header('Referrer') || req.header('Referer')218</code></pre>211 req.header('Referrer') || req.header('Referer')</code></pre>212213<p> With the new special-case we may now simply use <em>Referrer</em> which will return either if defined:</p>214222<pre><code> req.header('Referrer')223</code></pre>215<pre><code> req.header('Referrer')</code></pre>216225<h3 id="res-local-name-val-">res.local(name, val)</h3>217<h3 id="res-local-name-val">res.local(name, val)</h3>218219<p> Previously all local variables had to be passed to <em>res.render()</em>, or either <em>app.helpers()</em> or <em>app.dynamicHelpers()</em>, now we may do this at the request-level progressively. The <em>res.local()</em> method accepts a <em>name</em> and <em>val</em>, however the locals passed to <em>res.render()</em> will take precedence.</p>220221<p> For example we may utilize this feature to create locals in middleware:</p>
6 unmodified lines
228 }229230 app.get('/user/:id', loadUser, function(req, res){231 res.render('user');240 });241</code></pre>232 });</code></pre>233243<h3 id="req-param-name-defaultValue-">req.param(name[, defaultValue])</h3>234<h3 id="req-param-name-defaultValue">req.param(name[, defaultValue])</h3>235236<p> Previously only <em>name</em> was accepted, so some of you may have been doing the following:</p>237247<pre><code> var id = req.param('id') || req.user.id;248</code></pre>238<pre><code> var id = req.param('id') || req.user.id;</code></pre>239240<p> The new <em>defaultValue</em> argument can handle this nicely:</p>241252<pre><code> var id = req.param('id', req.user.id);253</code></pre>242<pre><code> var id = req.param('id', req.user.id);</code></pre>243255<h3 id="app-helpers-app-locals-">app.helpers() / app.locals()</h3>244<h3 id="app-helpers-app-locals">app.helpers() / app.locals()</h3>245246<p> <em>app.locals()</em> is now an alias of <em>app.helpers()</em>, as helpers makes more sense for functions.</p>247259<h3 id="req-accepts-type-">req.accepts(type)</h3>248<h3 id="req-accepts-type">req.accepts(type)</h3>249250<p> <em>req.accepts()</em> now accepts extensions:</p>251252<pre><code> // Accept: text/html
9 unmodified lines
262 // =&gt; true263264 req.accepts('image/png');265 req.accepts('png');277 // =&gt; false278</code></pre>266 // =&gt; false</code></pre>267280<h3 id="res-cookie-">res.cookie()</h3>268<h3 id="res-cookie">res.cookie()</h3>269270<p> Previously only directly values could be passed, so for example:</p>271284<pre><code>res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000) });285</code></pre>272<pre><code>res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000) });</code></pre>273274<p>However now we have the alternative <em>maxAge</em> property which may be used to set <em>expires</em> relative to <em>Date.now()</em> in milliseconds, so our example above can now become:</p>275289<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });290</code></pre>276<pre><code>res.cookie('rememberme', 'yes', { maxAge: 900000 });</code></pre>277292<h3 id="res-download-res-sendfile-">res.download() / res.sendfile()</h3>278<h3 id="res-download-res-sendfile">res.download() / res.sendfile()</h3>279280<p> Both of these methods now utilize Connect's static file server behind the scenes (actually the previous Express code was ported to Connect 1.0). With this change comes a change to the callback as well. Previously the <em>path</em> and <em>stream</em> were passed, however now only an <em>error</em> is passed, when no error has occurred the callback will be invoked indicating that the file transfer is complete. The callback remains optional:</p>281282<pre><code> res.download('/path/to/file');
3 unmodified lines
286 console.error(err);287 } else {288 console.log('transferred');289 }304 });305</code></pre>290 });</code></pre>291292<p> The <em>stream threshold</em> setting was removed.</p>293309<h3 id="res-render-">res.render()</h3>294<h3 id="res-render">res.render()</h3>295296<p> Previously locals were passed as a separate key:</p>297313<pre><code> res.render('user', { layout: false, locals: { user: user }});314</code></pre>298<pre><code> res.render('user', { layout: false, locals: { user: user }});</code></pre>299300<p> In Express 2.0 both the locals and the options are one in the same, meaning you cannot have a local variable named <em>layout</em> as it is reserved for express, however this cleans up the API:</p>301318<pre><code> res.render('user', { layout: false, user: user });319</code></pre>302<pre><code> res.render('user', { layout: false, user: user });</code></pre>303321<h3 id="res-partial-">res.partial()</h3>304<h3 id="res-partial">res.partial()</h3>305306<p> Express 2.0 adds the <em>res.partial()</em> method, helpful for rendering partial fragments over WebSockets or Ajax requests etc. The API is identical to the <em>partial()</em> calls within views.</p>307308<pre><code> // render a collection of comments309 res.partial('comment', [comment1, comment2]); 310311 // render a single comment329 res.partial('comment', comment);330</code></pre>312 res.partial('comment', comment);</code></pre>313314<h3 id="partial-locals">partial() locals</h3>315316<p> Both <em>res.partial()</em> and the <em>partial()</em> functions accept an single object consisting of both the options and the locals. Previously with Express 1.x you may pass <em>user</em> to a partial, along with <em>date</em> like so:</p>317318<pre><code> partial('user', { object: user, locals: { date: new Date }})</code></pre>319320<p>or perhaps if you preferred not to use the inferred name <em>user</em> you may used a local for this as well:</p>321322<pre><code> partial('user', { locals: { user: user, date: new Date }})</code></pre>323324<p> With recent changes to Express 2.x the object passed is now both, so the following is valid for the <em>object</em> option and locals:</p>325326<pre><code> partial('user', { object: user, date: new Date })</code></pre>327328<p> Or the following which is equivalent, however the local var name is explicitly set to <em>user</em> instead of deduced from the filename.</p>329330<pre><code> partial('user', { user: user, date: new Date })</code></pre>331332<p> When a "basic" object aka <em>{}</em> or <em>new Object</em> is passed, it is considered options, otherwise it is considered the <em>object</em>. The following are equivalent:</p>333334<pre><code> partial('user', user); 335 partial('user', { object: user }); </code></pre>336337<h3 id="Template-Engine-Compliance">Template Engine Compliance</h3>338339<p> To comply with Express previously engines needed the following signature:</p>340336<pre><code> engine.render(str, options, function(err){});337</code></pre>341<pre><code> engine.render(str, options, function(err){});</code></pre>342343<p> Now they must export a <em>compile()</em> function, returning a function which when called with local variables will render the template. This allows Express to cache the compiled function in memory during production.</p>344345<pre><code> var fn = engine.compile(str, options);342 fn(locals);343</code></pre>346 fn(locals);</code></pre>347348<h3 id="View-Partial-Lookup">View Partial Lookup</h3>349350<p> Previously partials were loaded relative to the now removed <em>view partials</em> directory setting, or by default <em>views/partials</em>, now they are relative to the view calling them, read more on <a href="guide.html#View-Lookup">view lookup</a>.</p>
1 unmodified line
352<h3 id="Mime-Types">Mime Types</h3>353354<p> Express and Connect now utilize the <em>mime</em> module in npm, so to add more use:</p>355353<pre><code> require('mime').define({ 'foo/bar': ['foo', 'bar'] });354</code></pre>356<pre><code> require('mime').define({ 'foo/bar': ['foo', 'bar'] });</code></pre>357356</div>358<h3 id="static-middleware">static() middleware</h3>359360<p> Previously named <code>staticProvider()</code>, the now <code>static()</code> middleware takes a single directory path, followed by options.</p>361362<pre><code> app.use(express.static(__dirname + '/public', { maxAge: oneYear }));</code></pre>363364<p>Previously when using options the <code>root</code> option would be used for this:</p>365366<pre><code> app.use(express.staticProvider({ root: __dirname + '/public', maxAge: oneYear }));367 </code></pre>368 </div>369 </div>370 </body>371</html>
deleted:docs/screencasts.1-28 removed
1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "SCREENCASTS" "" "March 2011" "" ""5.6.SH "NAME"7\fBscreencasts\fR8.9.SS "Introduction"10This introduction screencast covers the basics of Express, and how to get started with your first application\.11.12.P13.14.SS "View Partials"15In this screencast we work with partials to display a collection of users using the Jade \fIhttp://jade\-lang\.com\fR template engine, and learn about view path resolution\.16.17.P18.19.SS "Route Specific Middleware"20In the screencast below we learn about the benefits of route\-specific middleware\.21.22.P23.24.SS "Route Param Preconditions"25Learn about route parameter (\fI/user/:id\fR) pre\-conditions, providing automated validation, and loading of data via the named route param segments\.26.27.P28
modified:docs/screencasts.html+4 added-11 removed
188 unmodified lines
189 <li><a href="guide.html">Guide</a></li>190 <li><a href="screencasts.html">Screencasts</a></li>191 <li><a href="applications.html">Applications</a></li>192 </ul>193<div class='mp'>194<h2 id="Express">Express</h2>195<p class="man-name">196 <code>screencasts</code>197</p>193<h3 id="Introduction">Introduction</h3>194195<p>This introduction screencast covers the basics of Express, and how to get started with your first application.</p>196202<p><object height="345" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0"><param name="movie" value="http://screenr.com/Content/assets/screenr_1116090935.swf" /><param name="flashvars" value="i=139583" /><param name="allowFullScreen" value="true" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" src="http://screenr.com/Content/assets/screenr_1116090935.swf" height="345" flashvars="i=139583" width="560"></embed></object></p>197<p>&lt;object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0' width='560' height='345'&gt;&lt;param name='movie' value='http://screenr.com/Content/assets/screenr<em>1116090935.swf' /&gt;&lt;param name='flashvars' value='i=139583' /&gt;&lt;param name='allowFullScreen' value='true' /&gt;&lt;embed src='http://screenr.com/Content/assets/screenr</em>1116090935.swf' flashvars='i=139583' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'&gt;&lt;/embed&gt;&lt;/object&gt;</p>198199<h3 id="View-Partials">View Partials</h3>200201<p>In this screencast we work with partials to display a collection of users using the <a href="http://jade-lang.com">Jade</a> template engine, and learn about view path resolution.</p>202208<p><object height="345" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0"><param name="movie" value="http://screenr.com/Content/assets/screenr_1116090935.swf" /><param name="flashvars" value="i=139591" /><param name="allowFullScreen" value="true" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" src="http://screenr.com/Content/assets/screenr_1116090935.swf" height="345" flashvars="i=139591" width="560"></embed></object></p>203<p>&lt;object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0' width='560' height='345'&gt;&lt;param name='movie' value='http://screenr.com/Content/assets/screenr<em>1116090935.swf' /&gt;&lt;param name='flashvars' value='i=139591' /&gt;&lt;param name='allowFullScreen' value='true' /&gt;&lt;embed src='http://screenr.com/Content/assets/screenr</em>1116090935.swf' flashvars='i=139591' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'&gt;&lt;/embed&gt;&lt;/object&gt;</p>204205<h3 id="Route-Specific-Middleware">Route Specific Middleware</h3>206207<p>In the screencast below we learn about the benefits of route-specific middleware.</p>208214<p><object height="345" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0"><param name="movie" value="http://screenr.com/Content/assets/screenr_1116090935.swf" /><param name="flashvars" value="i=140296" /><param name="allowFullScreen" value="true" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" src="http://screenr.com/Content/assets/screenr_1116090935.swf" height="345" flashvars="i=140296" width="560"></embed></object></p>209<p>&lt;object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0' width='560' height='345'&gt;&lt;param name='movie' value='http://screenr.com/Content/assets/screenr<em>1116090935.swf' /&gt;&lt;param name='flashvars' value='i=140296' /&gt;&lt;param name='allowFullScreen' value='true' /&gt;&lt;embed src='http://screenr.com/Content/assets/screenr</em>1116090935.swf' flashvars='i=140296' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'&gt;&lt;/embed&gt;&lt;/object&gt;</p>210211<h3 id="Route-Param-Preconditions">Route Param Preconditions</h3>212213<p>Learn about route parameter (<em>/user/:id</em>) pre-conditions, providing automated validation, and loading of data via the named route param segments.</p>214220<p><object height="345" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0"><param name="movie" value="http://screenr.com/Content/assets/screenr_1116090935.swf" /><param name="flashvars" value="i=140300" /><param name="allowFullScreen" value="true" /><embed pluginspage="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" src="http://screenr.com/Content/assets/screenr_1116090935.swf" height="345" flashvars="i=140300" width="560"></embed></object></p>221222</div>215<p>&lt;object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0' width='560' height='345'&gt;&lt;param name='movie' value='http://screenr.com/Content/assets/screenr<em>1116090935.swf' /&gt;&lt;param name='flashvars' value='i=140300' /&gt;&lt;param name='allowFullScreen' value='true' /&gt;&lt;embed src='http://screenr.com/Content/assets/screenr</em>1116090935.swf' flashvars='i=140300' allowFullScreen='true' width='560' height='345' pluginspage='http://www.macromedia.com/go/getflashplayer'&gt;&lt;/embed&gt;&lt;/object&gt;</p>216 </div>217 </div>218 </body>219</html>
modified:Makefile+1 added-1 removed
20 unmodified lines
21 @./support/toc.js docs/guide.html2223%.html: %.md24 @echo "... $< -> $@"25 @ronn -5 --pipe --fragment $< \25 @ronn --fragment $< \26 | cat docs/layout/head.html - docs/layout/foot.html \27 | sed 's/NAME/Express/g' \28 > $@29
11 unmodified lines