guide.html
This file
Path
docs/guide.html
1,194 lines · 39.3 KiB · HTML
Last changed by
Regenerated guideTj Holowaychukbefore adoptionf179979
History of this fileTake it
1<html>2 <head>3 <title>Express - node web framework</title>4 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>5 <style>6 #tagline {7 margin-left: 75px;8 margin-bottom: 30px;9 color: rgba(255,255,255,0.7); }10 html {11 background: #1c1c1c url(images/bg.tile.jpg); }1213 body {14 margin: 0;15 padding-bottom: 30px;16 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";17 font-size: 14px;18 line-height: 1.5;19 -webkit-font-smoothing: antialiased;20 background: url(images/bg.jpg) 50% 0 no-repeat;21 color: #8b8b8b; }2223 * {24 outline: none; }2526 em {27 color: white; }2829 a img {30 border: none !important; }3132 a {33 font-weight: bold;34 text-decoration: none;35 color: white;36 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;37 -webkit-transition-duration: 0.15s;38 -webkit-transition-timing-function: ease-out; }39 a:hover {40 opacity: 0.8; }4142 h1, h2, h3, h4 {43 margin: 45px 0 0 0;44 color: white;45 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4647 h3 {48 font-size: 18px; }49 h4 {50 margin-left: 10px;51 font-size: 14px;52 }5354 pre {55 margin: 20px 10px;56 padding: 25px 20px;57 background: rgba(0,0,0,0.5);58 border: 1px solid #323232;59 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);60 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);61 -webkit-border-radius: 5px;62 -moz-border-radius: 5px; }6364 code {65 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6667 ul {68 margin: 15px 0;69 padding: 0 0 0 35px; }70 ul li {71 margin: 0;72 padding: 2px 0;73 list-style: square; }74 ul li ul {75 margin: 0;76 padding-left: 12px;77 }7879 .man-name, #Express { display:none; }8081 .sect {82 margin-left: 40px; }8384 #logo {85 display: block;86 margin-left: 30%;87 margin-bottom: 30px;88 width: 194px;89 height: 51px;90 background: url(images/logo.png) 0 0 no-repeat;91 text-indent: -99999px; }92 #logo:hover {93 opacity: 0.7; }94 #logo:active {95 opacity: 0.3; }9697 #ribbon {98 position: fixed;99 top: 0;100 right: 0;101 z-index: 2; }102103 #wrapper {104 width: 100%;105 min-height: 800px;106 background: url(images/top.png) 0 0 repeat-x; }107108 #container {109 margin: 0 auto;110 padding-top: 80px;111 width: 550px; }112113 #toc {114 position: fixed;115 top: 0;116 left: 0;117 margin: 0 0 0 15px;118 padding: 15px;119 height: 100%;120 background: rgba(0,0,0,0.2);121 overflow: auto;122 border-right: 1px solid rgba(255,255,255,0.05);123 }124 #toc li {125 padding: 0;126 list-style: none;127 }128 #toc li a {129 font-size: 11px;130 }131 #menu {132 margin-left: 65px;133 padding: 0;134 padding-bottom: 30px; }135 #menu li {136 display: inline;137 list-style: none; }138 #menu li a {139 display: block;140 float: left;141 margin: 0 2px;142 padding: 3px 15px;143 background: rgba(0,0,0,0.2);144 -webkit-border-radius: 8px;145 -moz-border-radius: 8px;146 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);147 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);148 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;149 -webkit-transition-duration: 0.15s;150 -webkit-transition-timing-function: ease-out; }151 #menu li a:hover,152 #menu li a.active {153 background: rgba(0,0,0,0.5); }154 #menu li a:active {155 background: rgba(0,0,0,0.1);156 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);157 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }158 </style>159 <script>160 $(function(){161 $('.section').hide();162 $('.toggle, a.section-title').toggle(function(){163 $(this).siblings('ul').fadeIn(300);164 return false;165 }, function(){166 $(this).siblings('ul').fadeOut(300);167 return false;168 });169 });170 </script>171 </head>172 <body>173 <a href='http://github.com/visionmedia/express'> 174 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 175 </a>176 <div id="wrapper">177 <div id="container"><ul id="toc">178<li><a href="#Installation">Installation</a></li>179<li><a href="#Creating-An-Application">Creating An Application</a></li>180<li><a href="#Configuration">Configuration</a></li>181<li><a href="#Settings">Settings</a></li>182<li><a href="#Routing">Routing</a></li>183<li><a href="#Passing-Route-Control">Passing Route Control</a></li>184<li><a href="#HTTP-Methods">HTTP Methods</a></li>185<li><a href="#Middleware">Middleware</a></li>186<li><a href="#Error-Handling">Error Handling</a></li>187<li><a href="#View-Rendering">View Rendering</a></li>188<li><a href="#View-Partials">View Partials</a></li>189<li><a href="#Template-Engines">Template Engines</a></li>190<li><a href="#Session-Support">Session Support</a></li>191<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">192<li><a href="#req-header-key-defaultValue-">header()</a></li>193<li><a href="#req-accepts-type-">accepts()</a></li>194<li><a href="#req-param-name-">param()</a></li>195<li><a href="#req-flash-type-msg-">flash()</a></li>196<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>197</ul></li>198<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">199<li><a href="#res-header-key-val-">header()</a></li>200<li><a href="#res-contentType-type-">contentType()</a></li>201<li><a href="#res-attachment-filename-">attachment()</a></li>202<li><a href="#res-sendfile-path-">sendfile()</a></li>203<li><a href="#res-download-file-filename-">download()</a></li>204<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>205<li><a href="#res-redirect-url-status-">redirect()</a></li>206<li><a href="#res-cookie-name-val-options-">cookie()</a></li>207<li><a href="#res-clearCookie-name-">clearCookie()</a></li>208<li><a href="#res-render-view-options-fn-">render()</a></li>209<li><a href="#res-partial-view-options-">partial()</a></li>210</ul></li>211<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">212<li><a href="#app-set-name-val-">set()</a></li>213<li><a href="#app-enable-name-">enable()</a></li>214<li><a href="#app-disable-name-">disable()</a></li>215<li><a href="#app-configure-env-function-function-">configure()</a></li>216<li><a href="#app-redirect-name-val-">redirect()</a></li>217<li><a href="#app-error-function-">error()</a></li>218<li><a href="#app-helpers-obj-">helpers()</a></li>219<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>220<li><a href="#app-mounted-fn-">mounted()</a></li>221<li><a href="#app-register-ext-exports-">register()</a></li>222<li><a href="#app-listen-port-host-">listen()</a></li>223</ul></li>224</ul>225 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 226 <p id="tagline">227 High performance, high class web development for228 <a href="http://nodejs.org">Node.js</a>229 </p>230 <ul id="menu">231 <li><a href="index.html">Home</a></li>232 <li><a href="guide.html">Guide</a></li>233 <li><a href="contrib.html">Contributing</a></li>234 <li><a href="migrate.html">1.x Migration</a></li>235 </ul>236<div class='mp'>237<h2 id="Express">Express</h2>238<p class="man-name">239 <code>guide</code>240</p>241<h3 id="Installation">Installation</h3>242243<p>curl:</p>244245<pre><code>$ curl -# http://expressjs.com/install.sh | sh246</code></pre>247248<p>npm:</p>249250<pre><code>$ npm install express251</code></pre>252253<p>git clone, first update the submodules:</p>254255<pre><code>$ git submodule update --init256$ make install257$ make install-support258</code></pre>259260<h3 id="Creating-An-Application">Creating An Application</h3>261262<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however263follows the same idiom by providing <em>express.createServer()</em> as shown below. This means264that you can utilize Express server's transparently with other libraries.</p>265266<pre><code>var app = require('express').createServer();267268app.get('/', function(req, res){269 res.send('hello world');270});271272app.listen(3000);273</code></pre>274275<h3 id="Configuration">Configuration</h3>276277<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers278can use the <em>configure()</em> method to setup needs required by the current environment. When279<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment280prior to the environment specific callback.</p>281282<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces283in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.284Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,285otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>286287<pre><code>app.configure(function(){288 app.use(express.methodOverride());289 app.use(express.bodyDecoder());290 app.use(app.router);291 app.use(express.staticProvider(__dirname + '/public'));292});293294app.configure('development', function(){295 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));296});297298app.configure('production', function(){299 app.use(express.errorHandler());300});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(){306 app.set('views', __dirname + '/views');307 app.set('views');308 // => "... views directory ..."309310 app.enable('some feature');311 // same as app.set('some feature', true);312313 app.disable('some feature');314 // same as app.set('some feature', false);315});316</code></pre>317318<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>319320<pre><code>$ NODE_ENV=production node app.js321</code></pre>322323<h3 id="Settings">Settings</h3>324325<p>Express supports the following settings out of the box:</p>326327<ul>328<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>329<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>330<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>331<li><em>view engine</em> Default view engine name for views rendered without extensions</li>332<li><em>view options</em> An object specifying global view options</li>333<li><em>partials</em> Root view partials directory defaulting to <em>views</em>/partials.</li>334<li><em>stream threshold</em> Bytesize indicating when a file should be streamed for <em>res.sendfile()</em> using <em>fs.ReadStream()</em> and <em>sys.pump()</em>.</li>335</ul>336337338<h3 id="Routing">Routing</h3>339340<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.341For example we may want to render a user's account for the path <em>/user/12</em>, this342can be done by defining the route below. The values associated to the named placeholders343are available as <code>req.params</code>.</p>344345<pre><code>app.get('/user/:id', function(req, res){346 res.send('user ' + req.params.id);347});348</code></pre>349350<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example351when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>352353<pre><code>\/user\/([^\/]+)\/?354</code></pre>355356<p>Regular expression literals may also be passed for complex uses. Since capture357groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>.</p>358359<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){360 res.send(req.params);361});362</code></pre>363364<p>Curl requests against the previously defined route:</p>365366<pre><code> $ curl http://dev:3000/user367 [null,null]368 $ curl http://dev:3000/users369 [null,null]370 $ curl http://dev:3000/users/1371 ["1",null]372 $ curl http://dev:3000/users/1..15373 ["1","15"]374</code></pre>375376<p>Below are some route examples, and the associated paths that they377may consume:</p>378379<pre><code> "/user/:id"380 /user/12381382 "/users/:id?"383 /users/5384 /users385386 "/files/*"387 /files/jquery.js388 /files/javascripts/jquery.js389390 "/file/*.*"391 /files/jquery.js392 /files/javascripts/jquery.js393394 "/user/:id/:operation?"395 /user/1396 /user/1/edit397398 "/products.:format"399 /products.json400 /products.xml401402 "/products.:format?"403 /products.json404 /products.xml405 /products406</code></pre>407408<h3 id="Passing-Route-Control">Passing Route Control</h3>409410<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,411the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,412and middleware continue to be invoked.</p>413414<pre><code>app.get('/users/:id?', function(req, res, next){415 var id = req.params.id;416 if (id) {417 // do something418 } else {419 next();420 }421});422423app.get('/users', function(req, res){424 // do something else425});426</code></pre>427428<h3 id="HTTP-Methods">HTTP Methods</h3>429430<p>We have seen <em>app.get()</em> a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as <em>app.post()</em>, <em>app.del()</em>, etc.</p>431432<p> A common example for <em>POST</em> usage, is when "submitting" a form. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it.</p>433434<p> <form method="post" action="/" /></p>435436<pre><code> <input type="text" name="user[name]" />437 <input type="text" name="user[email]" />438 <input type="submit" value="Submit" />439</code></pre>440441<p> </p>442443<p>By default Express does not know what to do with this request body, so we should add the <em>bodyDecoder</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>444445<pre><code>app.use(express.bodyDecoder());446</code></pre>447448<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>449450<pre><code>app.post('/', function(req, res){451 console.log(req.body.user);452 res.redirect('back');453});454</code></pre>455456<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>bodyDecoder</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>457458<pre><code>app.use(express.bodyDecoder());459app.use(express.methodOverride());460</code></pre>461462<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>463464<pre><code><form method="post" action="/">465 <input type="hidden" name="_method" value="put" />466 <input type="text" name="user[name]" />467 <input type="text" name="user[email]" />468 <input type="submit" value="Submit" /> 469</form>470471app.put('/', function(){472 console.log(req.body.user);473 res.redirect('back');474});475</code></pre>476477<h3 id="Middleware">Middleware</h3>478479<p>Middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be480passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>481482<pre><code> var express = require('express');483484var app = express.createServer(485 express.logger(),486 express.bodyDecoder()487 );488</code></pre>489490<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>491492<pre><code>app.use(express.logger({ format: ':method :uri' }));493</code></pre>494495<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>496497<pre><code>var connect = require('connect');498app.use(connect.logger());499</code></pre>500501<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>502503<pre><code>app.use(express.logger());504</code></pre>505506<h3 id="Error-Handling">Error Handling</h3>507508<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,509or passed to <em>next(err)</em>. Below is an example which serves different pages based on our510ad-hoc <em>NotFound</em> exception:</p>511512<pre><code>function NotFound(msg){513 this.name = 'NotFound';514 Error.call(this, msg);515 Error.captureStackTrace(this, arguments.callee);516}517518sys.inherits(NotFound, Error);519520app.get('/404', function(req, res){521 throw new NotFound;522});523524app.get('/500', function(req, res){525 throw new Error('keyboard cat!');526});527</code></pre>528529<p>We can call <em>app.error()</em> several times as shown below.530Here we check for an instanceof <em>NotFound</em> and show the531404 page, or we pass on to the next error handler.</p>532533<p>Note that these handlers can be defined anywhere, as they534will be placed below the route handlers on <em>listen()</em>. This535allows for definition within <em>configure()</em> blocks so we can536handle exceptions in different ways based on the environment.</p>537538<pre><code>app.error(function(err, req, res, next){539 if (err instanceof NotFound) {540 res.render('404.jade');541 } else {542 next(err);543 }544});545</code></pre>546547<p>Here we assume all errors as 500 for the simplicity of548this demo, however you can choose whatever you like</p>549550<pre><code>app.error(function(err, req, res){551 res.render('500.jade', {552 locals: {553 error: err554 } 555 });556});557</code></pre>558559<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware560to report on exceptions. For example if we wish to output exceptions561in "development" mode to <em>stderr</em> we can use:</p>562563<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));564</code></pre>565566<p>Also during development we may want fancy html pages to show exceptions567that are passed or thrown, so we can set <em>showStack</em> to true:</p>568569<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));570</code></pre>571572<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>573is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>574575<h3 id="View-Rendering">View Rendering</h3>576577<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name578of the module that will be required. For example the view <em>layout.ejs</em> will579tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.render(str, options)</em> to comply with Express, however580<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.</p>581582<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,583and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as584the <em>body</em> local variable in <em>layout.haml</em>.</p>585586<pre><code>app.get('/', function(req, res){587 res.render('index.haml', {588 locals: { title: 'My Site' }589 });590});591</code></pre>592593<p>The new <em>view engine</em> setting allows us to specify our default template engine,594so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>595596<pre><code>app.set('view engine', 'jade');597</code></pre>598599<p>Allowing us to render with:</p>600601<pre><code>res.render('index');602</code></pre>603604<p>vs:</p>605606<pre><code>res.render('index.jade');607</code></pre>608609<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still610mix and match template engines:</p>611612<pre><code>res.render('another-page.ejs');613</code></pre>614615<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>616617<pre><code>app.set('view options', {618 layout: false619});620</code></pre>621622<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>623624<pre><code>res.render('myview.ejs', { layout: true });625</code></pre>626627<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>628629<pre><code>res.render('page', { layout: 'mylayout' });630</code></pre>631632<p>Otherwise we must specify the extension:</p>633634<pre><code>res.render('page', { layout: 'mylayout.jade' });635</code></pre>636637<p>These paths may also be absolute:</p>638639<pre><code>res.render('page', { layout: __dirname + '/../../mylayout.jade' });640</code></pre>641642<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>643644<pre><code>app.set('view options', {645 open: '{{',646 close: '}}'647});648</code></pre>649650<h3 id="View-Partials">View Partials</h3>651652<p>The Express view system has built-in support for partials and collections, which are653sort of "mini" views representing a document fragment. For example rather than iterating654in a view to display comments, we would use a partial with collection support:</p>655656<pre><code>partial('comment.haml', { collection: comments });657</code></pre>658659<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,660however if we wished we could use an ejs partial, within a haml view for example.</p>661662<pre><code>partial('comment', { collection: comments });663</code></pre>664665<p>And once again even further, when rendering a collection we can simply pass666an array, if no other options are desired:</p>667668<pre><code>partial('comments', comments);669</code></pre>670671<p>When using the partial collection support a few "magic" variables are provided672for free:</p>673674<ul>675<li><em>firstInCollection</em> True if this is the first object</li>676<li><em>indexInCollection</em> Index of the object in the collection</li>677<li><em>lastInCollection</em> True if this is the last object</li>678</ul>679680681<h3 id="Template-Engines">Template Engines</h3>682683<p>Below are a few template engines commonly used with Express:</p>684685<ul>686<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>687<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>688<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>689</ul>690691692<h3 id="Session-Support">Session Support</h3>693694<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieDecoder</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>695696<pre><code>app.use(express.cookieDecoder());697app.use(express.session());698</code></pre>699700<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>701702<pre><code>var RedisStore = require('connect-redis');703app.use(express.cookieDecoder());704app.use(express.session({ store: new RedisStore }));705</code></pre>706707<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>708709<pre><code>var RedisStore = require('connect-redis');710app.use(express.cookieDecoder());711app.use(express.session({ store: new RedisStore }));712app.use(express.bodyDecoder());713714app.post('/add-to-cart', function(req, res){715 // Perhaps we posted several items with a form716 // (use the bodyDecoder() middleware for this)717 var items = req.body.items;718 req.session.items = items;719 res.redirect('back');720});721722app.get('/add-to-cart', function(req, res){723 // When redirected back to GET /add-to-cart724 // we could check req.session.items && req.session.items.length725 // to print out a message726 if (req.session.items && req.session.items.length) {727 req.flash('info', 'You have %s items in your cart', req.session.items.length);728 }729 res.render('shopping-cart');730});731</code></pre>732733<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/session.html">Connect Session</a> documentation.</p>734735<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>736737<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>738739<pre><code>req.header('Host');740req.header('host');741req.header('Accept', '*/*');742</code></pre>743744<h3 id="req-accepts-type-">req.accepts(type)</h3>745746<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>747748<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise749the given <em>type</em> is matched by an exact match, and then subtypes. You750may pass the subtype such as "html" which is then converted internally751to "text/html" using the mime lookup table.</p>752753<pre><code>// Accept: text/html754req.accepts('html');755// => true756757// Accept: text/*; application/json758req.accepts('html');759req.accepts('text/html');760req.accepts('text/plain');761req.accepts('application/json');762// => true763764req.accepts('image/png');765req.accepts('png');766// => false767</code></pre>768769<h3 id="req-param-name-">req.param(name)</h3>770771<p>Return the value of param <em>name</em> when present.</p>772773<ul>774<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>775<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>776<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>777</ul>778779780<p>To utilize urlencoded request bodies, <em>req.body</em>781should be an object. This can be done by using782the <em>express.bodyDecoder</em> middleware.</p>783784<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>785786<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>787788<pre><code>req.flash('info', 'email sent');789req.flash('error', 'email delivery failed');790req.flash('info', 'email re-sent');791// => 2792793req.flash('info');794// => ['email sent', 'email re-sent']795796req.flash('info');797// => []798799req.flash();800// => { error: ['email delivery failed'], info: [] }801</code></pre>802803<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>804805<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);806</code></pre>807808<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>809810<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header811to see if it was issued by an <em>XMLHttpRequest</em>:</p>812813<pre><code>req.xhr814req.isXMLHttpRequest815</code></pre>816817<h3 id="res-header-key-val-">res.header(key[, val])</h3>818819<p>Get or set the response header <em>key</em>.</p>820821<pre><code>res.header('Content-Length');822// => undefined823824res.header('Content-Length', 123);825// => 123826827res.header('Content-Length');828// => 123829</code></pre>830831<h3 id="res-contentType-type-">res.contentType(type)</h3>832833<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>834835<pre><code> var filename = 'path/to/image.png';836 res.contentType(filename);837 // res.headers['Content-Type'] is now "image/png"838</code></pre>839840<h3 id="res-attachment-filename-">res.attachment([filename])</h3>841842<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>843844<pre><code> res.attachment('path/to/my/image.png');845</code></pre>846847<h3 id="res-sendfile-path-">res.sendfile(path)</h3>848849<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>850851<pre><code>res.sendfile('path/to/my.file');852</code></pre>853854<p>This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has <strong>not</strong> been streamed, <em>next(err)</em> will be called on an exception.</p>855856<pre><code>res.sendfile(path, function(err, path){857 if (err) {858 // handle the error859 } else {860 console.log('transferred %s', path);861 }862});863</code></pre>864865<p>When the filesize exceeds the <em>stream threshold</em> (defaulting to 32k), the file will be streamed using <em>fs.ReadStream</em> and <em>sys.pump()</em>.</p>866867<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>868869<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>870871<pre><code>res.download('path/to/image.png');872res.download('path/to/image.png', 'foo.png');873</code></pre>874875<p>This is equivalent to:</p>876877<pre><code>res.attachment(file);878res.sendfile(file);879</code></pre>880881<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>882883<p>The <code>res.send()</code> method is a high level response utility allowing you to pass884objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status885code based responses. The following are all valid uses:</p>886887<pre><code> res.send(); // 204888 res.send(new Buffer('wahoo'));889 res.send({ some: 'json' });890 res.send('<p>some html</p>');891 res.send('Sorry, cant find that', 404);892 res.send('text', { 'Content-Type': 'text/plain' }, 201);893 res.send(404);894</code></pre>895896<p>By default the <em>Content-Type</em> response header is set, however if explicitly897assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>898it will not be set again.</p>899900<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>901902<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>903904<pre><code>res.redirect('/', 301);905res.redirect('/account');906res.redirect('http://google.com');907res.redirect('home');908res.redirect('back');909</code></pre>910911<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.912The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes913the "home" setting and defaults to "/".</p>914915<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>916917<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>918919<pre><code>// "Remember me" for 15 minutes 920res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });921</code></pre>922923<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>924925<pre><code>app.use(express.cookieDecoder());926927app.get('/', function(req, res){928 // use req.cookies.rememberme929});930</code></pre>931932<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>933934<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>935936<pre><code>res.clearCookie('rememberme');937</code></pre>938939<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>940941<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.942When a callback function is given a response will <em>not</em> be made943automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>944945<p> Most engines accept one or more of the following options,946 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>947948<ul>949<li><em>scope</em> Template evaluation context (value of <em>this</em>)</li>950<li><em>locals</em> Object containing local variables</li>951<li><em>debug</em> Output debugging information</li>952<li><em>status</em> Response status code, defaults to 200</li>953<li><em>headers</em> Response headers object</li>954</ul>955956957<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>958959<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available960to the view as a local variable.</p>961962<ul>963<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>964965<ul>966<li>as: 'something' will add the <em>something</em> local variable</li>967<li>as: this will use the collection value as the template context</li>968<li>as: global will merge the collection value's properties with <em>locals</em></li>969</ul>970</li>971<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.972For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>973</ul>974975976<p>The following are equivalent, and the name of collection value when passed977to the partial will be <em>movie</em> as derived from the name.</p>978979<pre><code>partial('movie.jade', { collection: movies });980partial('movie.jade', movies);981partial('movie', movies);982// In view: movie.director983</code></pre>984985<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>986987<pre><code>partial('movie', { collection: movies, as: 'video' });988// In view: video.director989</code></pre>990991<p>Also we can make our movie the value of <em>this</em> within our view so that instead992of <em>movie.director</em> we could use <em>this.director</em>.</p>993994<pre><code>partial('movie', { collection: movies, as: this });995// In view: this.director996</code></pre>997998<p>Another alternative is to "explode" the properties of the collection item into999pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>10001001<pre><code>partials('movie', { collection: movies, as: global });1002// In view: director1003</code></pre>10041005<h3 id="app-set-name-val-">app.set(name[, val])</h3>10061007<p>Apply an application level setting <em>name</em> to <em>val</em>, or1008get the value of <em>name</em> when <em>val</em> is not present:</p>10091010<pre><code>app.set('views', __dirname + '/views');1011app.set('views');1012// => ...path...1013</code></pre>10141015<h3 id="app-enable-name-">app.enable(name)</h3>10161017<p>Enable the given setting <em>name</em>:</p>10181019<pre><code>app.enable('some arbitrary setting');1020app.set('some arbitrary setting');1021// => true1022</code></pre>10231024<h3 id="app-disable-name-">app.disable(name)</h3>10251026<p>Disable the given setting <em>name</em>:</p>10271028<pre><code>app.disable('some setting');1029app.set('some setting');1030// => false1031</code></pre>10321033<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>10341035<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>10361037<pre><code>app.configure(function(){1038 // executed for each env1039});10401041app.configure('development', function(){1042 // executed for 'development' only1043});1044</code></pre>10451046<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>10471048<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>10491050<pre><code>app.redirect('google', 'http://google.com');1051</code></pre>10521053<p>Now in a route we may call:</p>10541055<p> res.redirect('google');</p>10561057<p>We may also map dynamic redirects:</p>10581059<pre><code>app.redirect('comments', function(req, res){1060 return '/post/' + req.params.id + '/comments';1061});1062</code></pre>10631064<p>So now we may do the following, and the redirect will dynamically adjust to1065the context of the request. If we called this route with <em>GET /post/12</em> our1066redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>10671068<pre><code>app.get('/post/:id', function(req, res){1069 res.redirect('comments');1070});1071</code></pre>10721073<h3 id="app-error-function-">app.error(function)</h3>10741075<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1076Note that we may set several error handlers by making several calls to this method, however the handler1077should call <em>next(err)</em> if it does not wish to deal with the exception:</p>10781079<pre><code>app.error(function(err, req, res, next){1080 res.send(err.message, 500);1081});1082</code></pre>10831084<h3 id="app-helpers-obj-">app.helpers(obj)</h3>10851086<p>Registers static view helpers.</p>10871088<pre><code>app.helpers({1089 name: function(first, last){ return first + ', ' + last },1090 firstName: 'tj',1091 lastName: 'holowaychuk'1092});1093</code></pre>10941095<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1096as well as the <em>name()</em> function exposed.</p>10971098<pre><code><%= name(firstName, lastName) %>1099</code></pre>11001101<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>11021103<p>Registers dynamic view helpers. Dynamic view helpers1104are simply functions which accept <em>req</em>, <em>res</em>, and are1105evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1106becomes the local variable it is associated with.</p>11071108<pre><code>app.dynamicHelpers({1109 session: function(req, res){1110 return req.session;1111 }1112});1113</code></pre>11141115<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>11161117<pre><code><%= session.name %>1118</code></pre>11191120<h3 id="app-mounted-fn-">app.mounted(fn)</h3>11211122<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>11231124<pre><code>var app = express.createServer(),1125 blog = express.createServer();11261127blog.mounted(function(parent){1128 // parent is app1129 // "this" is blog1130});11311132app.use(blog);1133</code></pre>11341135<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>11361137<p>Register the given template engine <em>exports</em>1138as <em>ext</em>. For example we may wish to map ".html"1139files to jade:</p>11401141<pre><code> app.register('.html', require('jade'));1142</code></pre>11431144<p>This is also useful for libraries that may not1145match extensions correctly. For example my haml.js1146library is installed from npm as "hamljs" so instead1147of layout.hamljs, we can register the engine as ".haml":</p>11481149<pre><code> app.register('.haml', require('haml-js'));1150</code></pre>11511152<p>For engines that do not comply with the Express1153specification, we can also wrap their api this way.</p>11541155<pre><code> app.register('.foo', {1156 render: function(str, options) {1157 // perhaps their api is1158 // foo.toHTML(str, options);1159 }1160 });1161</code></pre>11621163<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>11641165<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1166connections will be accepted via <em>INADDR_ANY</em>.</p>11671168<pre><code>app.listen();1169app.listen(3000);1170app.listen(3000, 'n.n.n.n');1171</code></pre>11721173<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>11741175<pre><code>app.listen('/tmp/express.sock');1176</code></pre>11771178<p>Then try it out:</p>11791180<pre><code>$ telnet /tmp/express.sock1181GET / HTTP/1.111821183HTTP/1.1 200 OK1184Content-Type: text/plain1185Content-Length: 1111861187Hello World1188</code></pre>11891190</div>1191 </div>1192 </div>1193 </body>1194</html>