guide.html
This file
Path
docs/guide.html
1,074 lines · 33.6 KiB · HTML
Last changed by
Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809
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-text-stroke: 1px rgba(0, 0, 0, 0.1);20 -moz-text-stroke: 1px rgba(0, 0, 0, 0.1);21 background: url(images/bg.jpg) 50% 0 no-repeat;22 color: #8b8b8b; }2324 * {25 outline: none; }2627 em {28 color: white; }2930 a img {31 border: none !important; }3233 a {34 font-weight: bold;35 text-decoration: none;36 color: white;37 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;38 -webkit-transition-duration: 0.15s;39 -webkit-transition-timing-function: ease-out; }40 a:hover {41 opacity: 0.8; }4243 h1, h2, h3 {44 margin: 45px 0 0 0;45 color: white;46 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }4748 h3 {49 font-size: 18px; }5051 pre {52 margin: 20px 10px;53 padding: 25px 20px;54 background: rgba(0,0,0,0.5);55 border: 1px solid #323232;56 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);57 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);58 -webkit-border-radius: 5px;59 -moz-border-radius: 5px; }6061 code {62 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }6364 ul {65 margin: 15px 0;66 padding: 0 0 0 35px; }67 ul li {68 margin: 0;69 padding: 2px 0;70 list-style: square; }71 ul li ul {72 margin: 0;73 padding-left: 12px;74 }7576 .man-name, #Express { display:none; }7778 .sect {79 margin-left: 40px; }8081 #logo {82 display: block;83 margin-left: 30%;84 margin-bottom: 30px;85 width: 194px;86 height: 51px;87 background: url(images/logo.png) 0 0 no-repeat;88 text-indent: -99999px; }89 #logo:hover {90 opacity: 0.7; }91 #logo:active {92 opacity: 0.3; }9394 #ribbon {95 position: fixed;96 top: 0;97 right: 0;98 z-index: 2; }99100 #wrapper {101 width: 100%;102 min-height: 800px;103 background: url(images/top.png) 0 0 repeat-x; }104105 #container {106 margin: 0 auto;107 padding-top: 80px;108 width: 550px; }109110 #toc {111 position: fixed;112 top: 0;113 left: 0;114 margin: 0 0 0 15px;115 padding: 15px;116 height: 100%;117 background: rgba(0,0,0,0.2);118 overflow: auto;119 border-right: 1px solid rgba(255,255,255,0.05);120 }121 #toc li {122 padding: 0;123 list-style: none;124 }125 #toc li a {126 font-size: 11px;127 }128 #menu {129 margin-left: 65px;130 padding: 0;131 padding-bottom: 30px; }132 #menu li {133 display: inline;134 list-style: none; }135 #menu li a {136 display: block;137 float: left;138 margin: 0 2px;139 padding: 3px 15px;140 background: rgba(0,0,0,0.2);141 -webkit-border-radius: 8px;142 -moz-border-radius: 8px;143 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);144 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);145 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;146 -webkit-transition-duration: 0.15s;147 -webkit-transition-timing-function: ease-out; }148 #menu li a:hover,149 #menu li a.active {150 background: rgba(0,0,0,0.5); }151 #menu li a:active {152 background: rgba(0,0,0,0.1);153 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);154 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }155 </style>156 <script>157 $(function(){158 $('.section').hide();159 $('.toggle, a.section-title').toggle(function(){160 $(this).siblings('ul').fadeIn(300);161 return false;162 }, function(){163 $(this).siblings('ul').fadeOut(300);164 return false;165 });166 });167 </script>168 </head>169 <body>170 <a href='http://github.com/visionmedia/express'> 171 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 172 </a>173 <div id="wrapper">174 <div id="container"><ul id="toc">175<li><a href="#Installation">Installation</a></li>176<li><a href="#Creating-An-Application">Creating An Application</a></li>177<li><a href="#Configuration">Configuration</a></li>178<li><a href="#Settings">Settings</a></li>179<li><a href="#Routing">Routing</a></li>180<li><a href="#Passing-Route-Control">Passing Route Control</a></li>181<li><a href="#Middleware">Middleware</a></li>182<li><a href="#Error-Handling">Error Handling</a></li>183<li><a href="#View-Rendering">View Rendering</a></li>184<li><a href="#View-Partials">View Partials</a></li>185<li><a href="#Template-Engines">Template Engines</a></li>186<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">187<li><a href="#req-header-key-defaultValue-">header()</a></li>188<li><a href="#req-accepts-type-">accepts()</a></li>189<li><a href="#req-param-name-">param()</a></li>190<li><a href="#req-flash-type-msg-">flash()</a></li>191<li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>192</ul></li>193<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">194<li><a href="#res-header-key-val-">header()</a></li>195<li><a href="#res-contentType-type-">contentType()</a></li>196<li><a href="#res-attachment-filename-">attachment()</a></li>197<li><a href="#res-sendfile-path-">sendfile()</a></li>198<li><a href="#res-download-file-filename-">download()</a></li>199<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>200<li><a href="#res-redirect-url-status-">redirect()</a></li>201<li><a href="#res-cookie-name-val-options-">cookie()</a></li>202<li><a href="#res-clearCookie-name-">clearCookie()</a></li>203<li><a href="#res-render-view-options-fn-">render()</a></li>204<li><a href="#res-partial-view-options-">partial()</a></li>205</ul></li>206<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">207<li><a href="#app-set-name-val-">set()</a></li>208<li><a href="#app-enable-name-">enable()</a></li>209<li><a href="#app-disable-name-">disable()</a></li>210<li><a href="#app-configure-env-function-function-">configure()</a></li>211<li><a href="#app-redirect-name-val-">redirect()</a></li>212<li><a href="#app-error-function-">error()</a></li>213<li><a href="#app-helpers-obj-">helpers()</a></li>214<li><a href="#app-dynamicHelpers-obj-">dynamicHelpers()</a></li>215<li><a href="#app-mounted-fn-">mounted()</a></li>216<li><a href="#app-register-ext-exports-">register()</a></li>217<li><a href="#app-listen-port-host-">listen()</a></li>218</ul></li>219</ul>220 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 221 <p id="tagline">222 High performance, high class web development for223 <a href="http://nodejs.org">Node.js</a>224 </p>225 <ul id="menu">226 <li><a href="index.html">Home</a></li>227 <li><a href="guide.html">Guide</a></li>228 <li><a href="contrib.html">Contributing</a></li>229 <li><a href="migrate.html">1.x Migration</a></li>230 </ul>231<div class='mp'>232<h2 id="Express">Express</h2>233<p class="man-name">234 <code>guide</code>235</p>236<h3 id="Installation">Installation</h3>237238<p>curl:</p>239240<pre><code>$ curl -# http://expressjs.com/install.sh | sh241</code></pre>242243<p>npm:</p>244245<pre><code>$ npm install express246</code></pre>247248<p>git clone, first update the submodules:</p>249250<pre><code>$ git submodule update --init251$ make install252$ make install-support253</code></pre>254255<h3 id="Creating-An-Application">Creating An Application</h3>256257<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however258follows the same idiom by providing <em>express.createServer()</em> as shown below. This means259that you can utilize Express server's transparently with other libraries.</p>260261<pre><code>var app = require('express').createServer();262263app.get('/', function(req, res){264 res.send('hello world');265});266267app.listen(3000);268</code></pre>269270<h3 id="Configuration">Configuration</h3>271272<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers273can use the <em>configure()</em> method to setup needs required by the current environment. When274<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment275prior to the environment specific callback.</p>276277<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces278in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.279Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,280otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>281282<pre><code>app.configure(function(){283 app.use(express.methodOverride());284 app.use(express.bodyDecoder());285 app.use(app.router);286 app.use(express.staticProvider(__dirname + '/public'));287});288289app.configure('development', function(){290 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));291});292293app.configure('production', function(){294 app.use(express.errorHandler());295});296</code></pre>297298<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>299300<pre><code>app.configure(function(){301 app.set('views', __dirname + '/views');302 app.set('views');303 // => "... views directory ..."304305 app.enable('some feature');306 // same as app.set('some feature', true);307308 app.disable('some feature');309 // same as app.set('some feature', false);310});311</code></pre>312313<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,314or more specifically <em>EXPRESS_ENV</em>, for example:</p>315316<pre><code>$ EXPRESS_ENV=production node app.js317</code></pre>318319<h3 id="Settings">Settings</h3>320321<p>Express supports the following settings out of the box:</p>322323<ul>324<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>325<li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>326<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>327<li><em>view engine</em> Default view engine name for views rendered without extensions</li>328<li><em>view options</em> An object specifying global view options</li>329<li><em>partials</em> Root view partials directory defaulting to <em>views</em>/partials.</li>330</ul>331332333<h3 id="Routing">Routing</h3>334335<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.336For example we may want to render a user's account for the path <em>/user/12</em>, this337can be done by defining the route below. The values associated to the named placeholders338are available as <code>req.params</code>.</p>339340<pre><code>app.get('/user/:id', function(req, res){341 res.send('user ' + req.params.id);342});343</code></pre>344345<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example346when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>347348<pre><code>\/user\/([^\/]+)\/?349</code></pre>350351<p>Regular expression literals may also be passed for complex uses. Since capture352groups with literal <em>RegExp</em>'s are anonymous we can access them directly <code>req.params</code>.</p>353354<pre><code>app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){355 res.send(req.params);356});357</code></pre>358359<p>Curl requests against the previously defined route:</p>360361<pre><code> $ curl http://dev:3000/user362 [null,null]363 $ curl http://dev:3000/users364 [null,null]365 $ curl http://dev:3000/users/1366 ["1",null]367 $ curl http://dev:3000/users/1..15368 ["1","15"]369</code></pre>370371<p>Below are some route examples, and the associated paths that they372may consume:</p>373374<pre><code> "/user/:id"375 /user/12376377 "/users/:id?"378 /users/5379 /users380381 "/files/*"382 /files/jquery.js383 /files/javascripts/jquery.js384385 "/file/*.*"386 /files/jquery.js387 /files/javascripts/jquery.js388389 "/user/:id/:operation?"390 /user/1391 /user/1/edit392393 "/products.:format"394 /products.json395 /products.xml396397 "/products.:format?"398 /products.json399 /products.xml400 /products401</code></pre>402403<h3 id="Passing-Route-Control">Passing Route Control</h3>404405<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,406the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,407and middleware continue to be invoked.</p>408409<pre><code>app.get('/users/:id?', function(req, res, next){410 var id = req.params.id;411 if (id) {412 // do something413 } else {414 next();415 }416});417418app.get('/users', function(req, res){419 // do something else420});421</code></pre>422423<h3 id="Middleware">Middleware</h3>424425<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/senchalabs/connect">Connect</a> can be426passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>427428<pre><code>var express = require('express');429430var app = express.createServer(431 express.logger(),432 express.bodyDecoder()433);434</code></pre>435436<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>437438<pre><code>app.use(express.logger({ format: ':method :uri' }));439</code></pre>440441<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>442443<pre><code>var connect = require('connect');444app.use(connect.logger());445</code></pre>446447<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>448449<pre><code>app.use(express.logger());450</code></pre>451452<h3 id="Error-Handling">Error Handling</h3>453454<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,455or passed to <em>next(err)</em>. Below is an example which serves different pages based on our456ad-hoc <em>NotFound</em> exception:</p>457458<pre><code>function NotFound(msg){459 this.name = 'NotFound';460 Error.call(this, msg);461 Error.captureStackTrace(this, arguments.callee);462}463464sys.inherits(NotFound, Error);465466app.get('/404', function(req, res){467 throw new NotFound;468});469470app.get('/500', function(req, res){471 throw new Error('keyboard cat!');472});473</code></pre>474475<p>We can call <em>app.error()</em> several times as shown below.476Here we check for an instanceof <em>NotFound</em> and show the477404 page, or we pass on to the next error handler.</p>478479<p>Note that these handlers can be defined anywhere, as they480will be placed below the route handlers on <em>listen()</em>. This481allows for definition within <em>configure()</em> blocks so we can482handle exceptions in different ways based on the environment.</p>483484<pre><code>app.error(function(err, req, res, next){485 if (err instanceof NotFound) {486 res.render('404.jade');487 } else {488 next(err);489 }490});491</code></pre>492493<p>Here we assume all errors as 500 for the simplicity of494this demo, however you can choose whatever you like</p>495496<pre><code>app.error(function(err, req, res){497 res.render('500.jade', {498 locals: {499 error: err500 } 501 });502});503</code></pre>504505<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware506to report on exceptions. For example if we wish to output exceptions507in "development" mode to <em>stderr</em> we can use:</p>508509<pre><code>app.use(express.errorHandler({ dumpExceptions: true }));510</code></pre>511512<p>Also during development we may want fancy html pages to show exceptions513that are passed or thrown, so we can set <em>showStack</em> to true:</p>514515<pre><code>app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));516</code></pre>517518<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>519is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>520521<h3 id="View-Rendering">View Rendering</h3>522523<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name524of the module that will be required. For example the view <em>layout.ejs</em> will525tell 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, however526<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>527528<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,529and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as530the <em>body</em> local variable in <em>layout.haml</em>.</p>531532<pre><code>app.get('/', function(req, res){533 res.render('index.haml', {534 locals: { title: 'My Site' }535 });536});537</code></pre>538539<p>The new <em>view engine</em> setting allows us to specify our default template engine,540so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>541542<pre><code>app.set('view engine', 'jade');543</code></pre>544545<p>Allowing us to render with:</p>546547<pre><code>res.render('index');548</code></pre>549550<p>vs:</p>551552<pre><code>res.render('index.jade');553</code></pre>554555<p>When <em>view engine</em> is set, extensions are entirely optional, however we can still556mix and match template engines:</p>557558<pre><code>res.render('another-page.ejs');559</code></pre>560561<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>562563<pre><code>app.set('view options', {564 layout: false565});566</code></pre>567568<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>569570<pre><code>res.render('myview.ejs', { layout: true });571</code></pre>572573<p>A good example of this is specifying custom <em>ejs</em> opening and closing tags:</p>574575<pre><code>app.set('view options', {576 open: '{{',577 close: '}}'578});579</code></pre>580581<h3 id="View-Partials">View Partials</h3>582583<p>The Express view system has built-in support for partials and collections, which are584sort of "mini" views representing a document fragment. For example rather than iterating585in a view to display comments, we would use a partial with collection support:</p>586587<pre><code>partial('comment.haml', { collection: comments });588</code></pre>589590<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,591however if we wished we could use an ejs partial, within a haml view for example.</p>592593<pre><code>partial('comment', { collection: comments });594</code></pre>595596<p>And once again even further, when rendering a collection we can simply pass597an array, if no other options are desired:</p>598599<pre><code>partial('comments', comments);600</code></pre>601602<p>When using the partial collection support a few "magic" variables are provided603for free:</p>604605<ul>606<li><em>firstInCollection</em> True if this is the first object</li>607<li><em>indexInCollection</em> Index of the object in the collection</li>608<li><em>lastInCollection</em> True if this is the last object</li>609</ul>610611612<h3 id="Template-Engines">Template Engines</h3>613614<p>Below are a few template engines commonly used with Express:</p>615616<ul>617<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>618<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>619<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>620</ul>621622623<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>624625<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>626627<pre><code>req.header('Host');628req.header('host');629req.header('Accept', '*/*');630</code></pre>631632<h3 id="req-accepts-type-">req.accepts(type)</h3>633634<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>635636<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise637the given <em>type</em> is matched by an exact match, and then subtypes. You638may pass the subtype such as "html" which is then converted internally639to "text/html" using the mime lookup table.</p>640641<pre><code>// Accept: text/html642req.accepts('html');643// => true644645// Accept: text/*; application/json646req.accepts('html');647req.accepts('text/html');648req.accepts('text/plain');649req.accepts('application/json');650// => true651652req.accepts('image/png');653req.accepts('png');654// => false655</code></pre>656657<h3 id="req-param-name-">req.param(name)</h3>658659<p>Return the value of param <em>name</em> when present.</p>660661<ul>662<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>663<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>664<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>665</ul>666667668<p>To utilize urlencoded request bodies, <em>req.body</em>669should be an object. This can be done by using670the <em>express.bodyDecoder</em> middleware.</p>671672<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>673674<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>675676<pre><code>req.flash('info', 'email sent');677req.flash('error', 'email delivery failed');678req.flash('info', 'email re-sent');679// => 2680681req.flash('info');682// => ['email sent', 'email re-sent']683684req.flash('info');685// => []686687req.flash();688// => { error: ['email delivery failed'], info: [] }689</code></pre>690691<p>Flash notification message may also utilize formatters, by default only the %s string formatter is available:</p>692693<pre><code>req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);694</code></pre>695696<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>697698<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header699to see if it was issued by an <em>XMLHttpRequest</em>:</p>700701<pre><code>req.xhr702req.isXMLHttpRequest703</code></pre>704705<h3 id="res-header-key-val-">res.header(key[, val])</h3>706707<p>Get or set the response header <em>key</em>.</p>708709<pre><code>res.header('Content-Length');710// => undefined711712res.header('Content-Length', 123);713// => 123714715res.header('Content-Length');716// => 123717</code></pre>718719<h3 id="res-contentType-type-">res.contentType(type)</h3>720721<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>722723<pre><code> var filename = 'path/to/image.png';724 res.contentType(filename);725 // res.headers['Content-Type'] is now "image/png"726</code></pre>727728<h3 id="res-attachment-filename-">res.attachment([filename])</h3>729730<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>731732<pre><code> res.attachment('path/to/my/image.png');733</code></pre>734735<h3 id="res-sendfile-path-">res.sendfile(path)</h3>736737<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>738739<pre><code>res.sendfile('path/to/my.file');740</code></pre>741742<p>This is <em>not</em> a substitution for Connect's <em>staticProvider</em> middleware, it does not743support HTTP caching, and does not perform any security checks. This method is utilized744by <em>res.download()</em> to transfer static files, and allows you do to so from outside of745the public directory, so suitable security checks should be applied.</p>746747<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>748749<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>750751<pre><code>res.download('path/to/image.png');752res.download('path/to/image.png', 'foo.png');753</code></pre>754755<p>This is equivalent to:</p>756757<pre><code>res.attachment(file);758res.sendfile(file);759</code></pre>760761<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>762763<p>The <code>res.send()</code> method is a high level response utility allowing you to pass764objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status765code based responses. The following are all valid uses:</p>766767<pre><code> res.send(); // 204768 res.send(new Buffer('wahoo'));769 res.send({ some: 'json' });770 res.send('<p>some html</p>');771 res.send('Sorry, cant find that', 404);772 res.send('text', { 'Content-Type': 'text/plain' }, 201);773 res.send(404);774</code></pre>775776<p>By default the <em>Content-Type</em> response header is set, however if explicitly777assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>778it will not be set again.</p>779780<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>781782<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>783784<pre><code>res.redirect('/', 301);785res.redirect('/account');786res.redirect('http://google.com');787res.redirect('home');788res.redirect('back');789</code></pre>790791<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.792The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes793the "home" setting and defaults to "/".</p>794795<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>796797<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>798799<pre><code>// "Remember me" for 15 minutes 800res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });801</code></pre>802803<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>804805<pre><code>app.use(express.cookieDecoder());806807app.get('/', function(req, res){808 // use req.cookies.rememberme809});810</code></pre>811812<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>813814<p>Clear cookie <em>name</em> by setting "expires" far in the past.</p>815816<pre><code>res.clearCookie('rememberme');817</code></pre>818819<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>820821<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.822When a callback function is given a response will <em>not</em> be made823automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>824825<p> Most engines accept one or more of the following options,826 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>827828<ul>829<li><em>context|scope</em> Template evaluation context (<em>this</em>)</li>830<li><em>locals</em> Object containing local variables</li>831<li><em>debug</em> Output debugging information</li>832<li><em>status</em> Response status code, defaults to 200</li>833<li><em>headers</em> Response headers object</li>834</ul>835836837<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>838839<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available840to the view as a local variable.</p>841842<ul>843<li><p><em>as</em> Variable name for each <em>collection</em> value, defaults to the view name.</p>844845<ul>846<li>as: 'something' will add the <em>something</em> local variable</li>847<li>as: this will use the collection value as the template context</li>848<li>as: global will merge the collection value's properties with <em>locals</em></li>849</ul>850</li>851<li><p><em>collection</em> Array of objects, the name is derived from the view name itself.852For example <em>video.html</em> will have a object <em>video</em> available to it.</p></li>853</ul>854855856<p>The following are equivalent, and the name of collection value when passed857to the partial will be <em>movie</em> as derived from the name.</p>858859<pre><code>partial('movie.jade', { collection: movies });860partial('movie.jade', movies);861partial('movie', movies);862// In view: movie.director863</code></pre>864865<p>To change the local from <em>movie</em> to <em>video</em> we can use the "as" option:</p>866867<pre><code>partial('movie', { collection: movies, as: 'video' });868// In view: video.director869</code></pre>870871<p>Also we can make our movie the value of <em>this</em> within our view so that instead872of <em>movie.director</em> we could use <em>this.director</em>.</p>873874<pre><code>partial('movie', { collection: movies, as: this });875// In view: this.director876</code></pre>877878<p>Another alternative is to "explode" the properties of the collection item into879pseudo globals (local variables) by using <em>as: global</em>, which again is syntactic sugar:</p>880881<pre><code>partials('movie', { collection: movies, as: global });882// In view: director883</code></pre>884885<h3 id="app-set-name-val-">app.set(name[, val])</h3>886887<p>Apply an application level setting <em>name</em> to <em>val</em>, or888get the value of <em>name</em> when <em>val</em> is not present:</p>889890<pre><code>app.set('views', __dirname + '/views');891app.set('views');892// => ...path...893</code></pre>894895<h3 id="app-enable-name-">app.enable(name)</h3>896897<p>Enable the given setting <em>name</em>:</p>898899<pre><code>app.enable('some arbitrary setting');900app.set('some arbitrary setting');901// => true902</code></pre>903904<h3 id="app-disable-name-">app.disable(name)</h3>905906<p>Disable the given setting <em>name</em>:</p>907908<pre><code>app.disable('some setting');909app.set('some setting');910// => false911</code></pre>912913<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>914915<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>916917<pre><code>app.configure(function(){918 // executed for each env919});920921app.configure('development', function(){922 // executed for 'development' only923});924</code></pre>925926<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>927928<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>929930<pre><code>app.redirect('google', 'http://google.com');931</code></pre>932933<p>Now in a route we may call:</p>934935<p> res.redirect('google');</p>936937<p>We may also map dynamic redirects:</p>938939<pre><code>app.redirect('comments', function(req, res){940 return '/post/' + req.params.id + '/comments';941});942</code></pre>943944<p>So now we may do the following, and the redirect will dynamically adjust to945the context of the request. If we called this route with <em>GET /post/12</em> our946redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>947948<pre><code>app.get('/post/:id', function(req, res){949 res.redirect('comments');950});951</code></pre>952953<h3 id="app-error-function-">app.error(function)</h3>954955<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.956Note that we may set several error handlers by making several calls to this method, however the handler957should call <em>next(err)</em> if it does not wish to deal with the exception:</p>958959<pre><code>app.error(function(err, req, res, next){960 res.send(err.message, 500);961});962</code></pre>963964<h3 id="app-helpers-obj-">app.helpers(obj)</h3>965966<p>Registers static view helpers.</p>967968<pre><code>app.helpers({969 name: function(first, last){ return first + ', ' + last },970 firstName: 'tj',971 lastName: 'holowaychuk'972});973</code></pre>974975<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,976as well as the <em>name()</em> function exposed.</p>977978<pre><code><%= name(firstName, lastName) %>979</code></pre>980981<h3 id="app-dynamicHelpers-obj-">app.dynamicHelpers(obj)</h3>982983<p>Registers dynamic view helpers. Dynamic view helpers984are simply functions which accept <em>req</em>, <em>res</em>, and are985evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function986becomes the local variable it is associated with.</p>987988<pre><code>app.dynamicHelpers({989 session: function(req, res){990 return req.session;991 }992});993</code></pre>994995<p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>996997<pre><code><%= session.name %>998</code></pre>9991000<h3 id="app-mounted-fn-">app.mounted(fn)</h3>10011002<p>Assign a callback <em>fn</em> which is called when this <em>Server</em> is passed to <em>Server#use()</em>.</p>10031004<pre><code>var app = express.createServer(),1005 blog = express.createServer();10061007blog.mounted(function(parent){1008 // parent is app1009 // "this" is blog1010});10111012app.use(blog);1013</code></pre>10141015<h3 id="app-register-ext-exports-">app.register(ext, exports)</h3>10161017<p>Register the given template engine <em>exports</em>1018as <em>ext</em>. For example we may wish to map ".html"1019files to jade:</p>10201021<pre><code> app.register('.html', require('jade'));1022</code></pre>10231024<p>This is also useful for libraries that may not1025match extensions correctly. For example my haml.js1026library is installed from npm as "hamljs" so instead1027of layout.hamljs, we can register the engine as ".haml":</p>10281029<pre><code> app.register('.haml', require('haml-js'));1030</code></pre>10311032<p>For engines that do not comply with the Express1033specification, we can also wrap their api this way.</p>10341035<pre><code> app.register('.foo', {1036 render: function(str, options) {1037 // perhaps their api is1038 // foo.toHTML(str, options);1039 }1040 });1041</code></pre>10421043<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>10441045<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all1046connections will be accepted via <em>INADDR_ANY</em>.</p>10471048<pre><code>app.listen();1049app.listen(3000);1050app.listen(3000, 'n.n.n.n');1051</code></pre>10521053<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>10541055<pre><code>app.listen('/tmp/express.sock');1056</code></pre>10571058<p>Then try it out:</p>10591060<pre><code>$ telnet /tmp/express.sock1061GET / HTTP/1.110621063HTTP/1.1 200 OK1064Content-Type: text/plain1065Content-Length: 1110661067Hello World1068</code></pre>10691070</div>1071 </div>1072 </div>1073 </body>1074</html>