guide.html
This file
Path
docs/guide.html
550 lines · 16.9 KiB · HTML
Last changed by
Generating TOCTj Holowaychukbefore adoption0cdc836
History of this fileTake it
Started guideTj Holowaychukbefore adoption9e3a0c6
lines 1–115why, one step back1<html>2 <head>3 <title>Express - node web framework</title>4 <style>5 #header {6 position: absolute;7 top: 10px;8 left: 0;9 padding: 12px 0;10 text-indent: 40px;11 width: 100%;12 border-top: 1px solid rgba(0,0,0,0.7);13 border-bottom: 1px solid rgba(0,0,0,0.7);14 background: rgba(255,255,255,0.1) url(http://www.sencha.com/favicon.ico) no-repeat 15px 50%;15 text-align: left;16 color: #fff;17 }18 #tagline {19 margin-left: 75px;20 margin-bottom: 30px;21 color: rgba(255,255,255,0.7); }22 html {23 background: #1c1c1c url(images/bg.tile.jpg); }2425 body {26 margin: 0;27 padding-bottom: 30px;28 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";29 font-size: 14px;30 line-height: 1.5;31 -webkit-text-stroke: 1px rgba(0, 0, 0, 0.1);32 -moz-text-stroke: 1px rgba(0, 0, 0, 0.1);33 background: url(images/bg.jpg) 50% 0 no-repeat;34 color: #8b8b8b; }3536 * {37 outline: none; }3839 em {40 color: white; }4142 a img {43 border: none !important; }4445 a {46 font-weight: bold;47 color: white;48 -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;49 -webkit-transition-duration: 0.15s;50 -webkit-transition-timing-function: ease-out; }51 a:hover {52 opacity: 0.8; }5354 h1, h2, h3 {55 margin: 45px 0 0 0;56 color: white;57 text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }5859 h3 {60 font-size: 18px; }6162 pre {63 margin: 20px 10px;64 padding: 25px 20px;65 background: rgba(0,0,0,0.5);66 border: 1px solid #323232;67 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);68 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);69 -webkit-border-radius: 5px;70 -moz-border-radius: 5px; }7172 code {73 font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }7475 ul {76 margin: 15px 0;77 padding: 0 0 0 35px; }78 ul li {79 margin: 0;80 padding: 2px 0;81 list-style: square; }8283 .sect {84 margin-left: 40px; }8586 #logo {87 display: block;88 margin-left: 30%;89 margin-bottom: 30px;90 width: 194px;91 height: 51px;92 background: url(images/logo.png) 0 0 no-repeat;93 text-indent: -99999px; }94 #logo:hover {95 opacity: 0.7; }96 #logo:active {97 opacity: 0.3; }9899 #ribbon {100 position: fixed;101 top: 0;102 right: 0;103 z-index: 2; }104105 #wrapper {106 width: 100%;107 min-height: 800px;108 background: url(images/top.png) 0 0 repeat-x; }109110 #container {111 margin: 0 auto;112 padding-top: 110px;113 width: 550px; }114115 #menu {Added contrib docsTj Holowaychukbefore adoptionf0ba57b
line 116why, one step back116 margin-left: 65px;Started guideTj Holowaychukbefore adoption9e3a0c6
lines 117–131why, one step back117 padding: 0;118 padding-bottom: 30px; }119 #menu li {120 display: inline;121 list-style: none; }122 #menu li a {123 display: block;124 float: left;125 margin: 0 2px;126 padding: 3px 15px;127 background: rgba(0,0,0,0.2);128 -webkit-border-radius: 8px;129 -moz-border-radius: 8px;130 -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);131 -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);Removed annoying padding transitionTj Holowaychukbefore adoption346b2a2
line 132why, one step back132 -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;Started guideTj Holowaychukbefore adoption9e3a0c6
lines 133–149why, one step back133 -webkit-transition-duration: 0.15s;134 -webkit-transition-timing-function: ease-out; }135 #menu li a:hover,136 #menu li a.active {137 background: rgba(0,0,0,0.5); }138 #menu li a:active {139 background: rgba(0,0,0,0.1);140 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);141 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }142 </style>143 </head>144 <body>145 <a href='http://github.com/visionmedia/express'> 146 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 147 </a>148 <div id="header"><strong>Sencha</strong> labs</div>149 <div id="wrapper">Generating TOCTj Holowaychukbefore adoption0cdc836
lines 150–171why, one step back150 <div id="container"><ul id="toc">151<li><a href="#Installation">Installation</a></li>152<li><a href="#Creating-An-Application">Creating An Application</a></li>153<li><a href="#Configuration">Configuration</a></li>154<li><a href="#Settings">Settings</a></li>155<li><a href="#Routing">Routing</a></li>156<li><a href="#Passing-Route-Control">Passing Route Control</a></li>157<li><a href="#Middleware">Middleware</a></li>158<li><a href="#ServerRequest-header-key-defaultValue-">ServerRequest#header(key[, defaultValue])</a></li>159<li><a href="#ServerRequest-accepts-type-">ServerRequest#accepts(type)</a></li>160<li><a href="#ServerRequest-param-name-">ServerRequest#param(name)</a></li>161<li><a href="#ServerRequest-flash-type-msg-">ServerRequest#flash(type[, msg])</a></li>162<li><a href="#ServerRequest-isXMLHttpRequest">ServerRequest#isXMLHttpRequest</a></li>163<li><a href="#ServerResponse-header-key-val-">ServerResponse#header(key[, val])</a></li>164<li><a href="#ServerResponse-contentType-type-">ServerResponse#contentType(type)</a></li>165<li><a href="#ServerResponse-attachment-filename-">ServerResponse#attachment([filename])</a></li>166<li><a href="#ServerResponse-sendfile-path-">ServerResponse#sendfile(path)</a></li>167<li><a href="#ServerResponse-download-file-filename-">ServerResponse#download(file[, filename])</a></li>168<li><a href="#ServerRequest-send-body-status-headers-status-status-">ServerRequest#send(body|status[, headers|status[, status]])</a></li>169<li><a href="#ServerResponse-redirect-url-status-">ServerResponse#redirect(url[, status])</a></li>170<li><a href="#Server-redirect-name-val-">Server#redirect(name, val)</a></li>171</ul>Started guideTj Holowaychukbefore adoption9e3a0c6
lines 172–179why, one step back172 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 173 <p id="tagline">174 High performance, high class web development for175 <a href="http://nodejs.org">Node.js</a>176 </p>177 <ul id="menu">178 <li><a href="index.html">Home</a></li>179 <li><a href="guide.html">Guide</a></li>Added contrib docsTj Holowaychukbefore adoptionf0ba57b
line 180why, one step back180 <li><a href="contrib.html">Contributing</a></li>Started guideTj Holowaychukbefore adoption9e3a0c6
lines 181–183why, one step back181 <li><a href="migrate.html">1.x Migration</a></li>182 </ul>183<div class='mp'>Install docsTj Holowaychukbefore adoption63d02f1
lines 184–200why, one step back184<h3 id="Installation">Installation</h3>185186<p>npm:</p>187188<pre><code>$ npm install express189</code></pre>190191<p>curl (or similar):</p>192193<pre><code>$ curl -# http://github.com/extjs/Connect/raw/master/install.sh | sh194</code></pre>195196<p>git clone or tarball for <strong>HEAD</strong>:</p>197198<pre><code>$ make install199</code></pre>200Removed annoying padding transitionTj Holowaychukbefore adoption346b2a2
line 201why, one step back201<h3 id="Creating-An-Application">Creating An Application</h3>Added configuration sectionTj Holowaychukbefore adoption83d2555
lines 202–203why, one step back202203<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, howeverMoved config docs upTj Holowaychukbefore adoption6e8413f
lines 204–205why, one step back204follows the same idiom by providing <em>express.createServer()</em> as shown below. This means205that you can utilize Express server's transparently with other libraries.</p>Added configuration sectionTj Holowaychukbefore adoption83d2555
lines 206–215why, one step back206207<pre><code>var app = require('express').createServer();208209app.get('/', function(req, res){210 res.send('hello world');211});212213app.listen(3000);214</code></pre>215Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 216–259why, one step back216<h3 id="Configuration">Configuration</h3>217218<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers219can use the <em>configure()</em> method to setup needs required by the current environment. When220<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment221prior to the environment specific callback.</p>222223<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces224in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.</p>225226<pre><code>app.configure(function(){227 app.use('/', connect.methodOverride());228 app.use('/', connect.bodyDecoder());229});230231app.configure('development', function(){232 app.use('/', connect.errorHandler({ dumpExceptions: true, showStack: true }));233});234235app.configure('production', function(){236 app.use('/', connect.errorHandler());237});238</code></pre>239240<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>241242<pre><code>app.configure(function(){243 app.set('views', __dirname + '/views');244 app.set('views');245 // => "... views directory ..."246247 app.enable('some feature');248 // same as app.set('some feature', true);249250 app.disable('some feature');251 // same as app.set('some feature', false);252});253</code></pre>254255<h3 id="Settings">Settings</h3>256257<p>Express supports the following settings out of the box:</p>258259<ul>Install docsTj Holowaychukbefore adoption63d02f1
line 260why, one step back260<li><em>home</em> Application base path used with <em>res.redirect()</em></li>Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 261–262why, one step back261<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>262<li><em>view engine</em> Default view engine name for views rendered without extensions</li>Added more setting docsTj Holowaychukbefore adoption38281e6
lines 263–264why, one step back263<li><em>reload views</em> Reloads altered views, by default watches for <em>mtime</em> changes with264 with a 5 minute interval. Example: <code>app.set('reload views', { interval: 60000 });</code></li>Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 265–267why, one step back265</ul>266267Started guideTj Holowaychukbefore adoption9e3a0c6
lines 268–271why, one step back268<h3 id="Routing">Routing</h3>269270<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.271For example we may want to render a user's account for the path <em>/user/12</em>, thisRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 272–273why, one step back272can be done by defining the route below. The values associated to the named placeholders,273are passed as the <em>third</em> argument, which here we name <em>params</em>.</p>Started guideTj Holowaychukbefore adoption9e3a0c6
lines 274–320why, one step back274275<pre><code>app.get('/user/:id', function(req, res, params){276 res.send('user ' + params.id);277});278</code></pre>279280<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example281when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>282283<pre><code>\/user\/([^\/]+)\/?284</code></pre>285286<p>Literal regular expressions may also be passed for complex uses:</p>287288<pre><code>app.get(/^\/foo(bar)?$/, function(){});289</code></pre>290291<p>Below are some route examples, and the associated paths that they292may consume:</p>293294<pre><code> "/user/:id"295 /user/12296297 "/users/:id?"298 /users/5299 /users300301 "/files/*"302 /files/jquery.js303 /files/javascripts/jquery.js304305 "/file/*.*"306 /files/jquery.js307 /files/javascripts/jquery.js308309 "/user/:id/:operation?"310 /user/1311 /user/1/edit312313 "/products.:format"314 /products.json315 /products.xml316317 "/products.:format?"318 /products.json319 /products.xml320 /productsRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 321–337why, one step back321</code></pre>322323<h3 id="Passing-Route-Control">Passing Route Control</h3>324325<p>We may pass control to the next <em>matching</em> route, by calling the <em>fourth</em> parameter,326the <em>next()</em> function. When a match cannot be made, control is passed back to Connect.</p>327328<pre><code>app.get('/users/:id?', function(req, res, params){329 if (params.id) {330 // do something331 } else {332 next();333 }334});335336app.get('/users', function(req, res, params){337 // do something elseAdded configuration sectionTj Holowaychukbefore adoption83d2555
lines 338–352why, one step back338});339</code></pre>340341<h3 id="Middleware">Middleware</h3>342343<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/extjs/Connect">Connect</a> can be344passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>345346<pre><code>var connect = require('connect'),347 express = require('express');348349var app = express.createServer(350 connect.logger(),351 connect.bodyDecoder()352);More docsTj Holowaychukbefore adoptionbedff32
lines 353–354why, one step back353</code></pre>354More docsTj Holowaychukbefore adoptiondfecbe5
lines 355–431why, one step back355<h3 id="ServerRequest-header-key-defaultValue-">ServerRequest#header(key[, defaultValue])</h3>356357<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>358359<pre><code>req.header('Host');360req.header('host');361req.header('Accept', '*/*');362</code></pre>363364<h3 id="ServerRequest-accepts-type-">ServerRequest#accepts(type)</h3>365366<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>367368<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise369the given <em>type</em> is matched by an exact match, and then subtypes. You370may pass the subtype such as "html" which is then converted internally371to "text/html" using the mime lookup table.</p>372373<pre><code>// Accept: text/html374req.accepts('html');375// => true376377// Accept: text/*; application/json378req.accepts('html');379req.accepts('text/html');380req.accepts('text/plain');381req.accepts('application/json');382// => true383384req.accepts('image/png');385req.accepts('png');386// => false387</code></pre>388389<h3 id="ServerRequest-param-name-">ServerRequest#param(name)</h3>390391<p>Return the value of param <em>name</em> when present.</p>392393<ul>394<li>Checks route placeholders, ex: /user/:id</li>395<li>Checks query string params, ex: ?id=12</li>396<li>Checks urlencoded body params, ex: id=12</li>397</ul>398399400<p>To utilize urlencoded request bodies, <em>req.body</em>401should be an object. This can be done by using402the <em>connect.bodyDecoder</em> middleware.</p>403404<h3 id="ServerRequest-flash-type-msg-">ServerRequest#flash(type[, msg])</h3>405406<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>407408<pre><code>req.flash('info', 'email sent');409req.flash('error', 'email delivery failed');410req.flash('info', 'email re-sent');411// => 2412413req.flash('info');414// => ['email sent', 'email re-sent']415416req.flash('info');417// => []418419req.flash();420// => { error: ['email delivery failed'], info: [] }421</code></pre>422423<h3 id="ServerRequest-isXMLHttpRequest">ServerRequest#isXMLHttpRequest</h3>424425<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header426to see if it was issued by an <em>XMLHttpRequest</em>:</p>427428<pre><code>req.xhr429req.isXMLHttpRequest430</code></pre>431More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 432–454why, one step back432<h3 id="ServerResponse-header-key-val-">ServerResponse#header(key[, val])</h3>433434<p>Get or set the response header <em>key</em>.</p>435436<pre><code>res.header('Content-Length');437// => undefined438439res.header('Content-Length', 123);440// => 123441442res.header('Content-Length');443// => 123444</code></pre>445446<h3 id="ServerResponse-contentType-type-">ServerResponse#contentType(type)</h3>447448<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>449450<pre><code> var filename = 'path/to/image.png';451 res.contentType(filename);452 // res.headers['Content-Type'] is now "image/png"453</code></pre>454Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
lines 455–461why, one step back455<h3 id="ServerResponse-attachment-filename-">ServerResponse#attachment([filename])</h3>456457<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>458459<pre><code> res.attachment('path/to/my/image.png');460</code></pre>461Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 462–485why, one step back462<h3 id="ServerResponse-sendfile-path-">ServerResponse#sendfile(path)</h3>463464<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>465466<pre><code>res.sendfile('path/to/my.file');467</code></pre>468469<p><strong>NOTE</strong>: this is <em>not</em> a replacement for Connect's <em>staticProvider</em> middleware,470nor does it perform any security checks, use with caution when using in a dynamic manor.</p>471472<h3 id="ServerResponse-download-file-filename-">ServerResponse#download(file[, filename])</h3>473474<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>475476<pre><code>res.download('path/to/image.png');477res.download('path/to/image.png', 'foo.png');478</code></pre>479480<p>This is equivalent to:</p>481482<pre><code>res.attachment(file);483res.sendfile(file);484</code></pre>485Docs for res.send()Tj Holowaychukbefore adoption5a48248
lines 486–503why, one step back486<h3 id="ServerRequest-send-body-status-headers-status-status-">ServerRequest#send(body|status[, headers|status[, status]])</h3>487488<p>The <code>res.send()</code> method is a high level response utility allowing you to pass489objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status490code based responses. The following are all valid uses:</p>491492<pre><code> res.send(new Buffer('wahoo'));493 res.send({ some: 'json' });494 res.send('<p>some html</p>');495 res.send('Sorry, cant find that', 404);496 res.send('text', { 'Content-Type': 'text/plain' }, 201);497 res.send(404);498</code></pre>499500<p>By default the <em>Content-Type</em> response header is set, however if explicitly501assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>502it will not be set again.</p>503More docsTj Holowaychukbefore adoptionbedff32
lines 504–543why, one step back504<h3 id="ServerResponse-redirect-url-status-">ServerResponse#redirect(url[, status])</h3>505506<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>507508<pre><code>res.redirect('/', 301);509res.redirect('/account');510res.redirect('http://google.com');511res.redirect('home');512res.redirect('back');513</code></pre>514515<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.516The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes517the "home" setting and defaults to "/".</p>518519<h3 id="Server-redirect-name-val-">Server#redirect(name, val)</h3>520521<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>522523<pre><code>app.redirect('google', 'http://google.com');524</code></pre>525526<p>Now in a route we may call:</p>527528<p> res.redirect('google');</p>529530<p>We may also map dynamic redirects:</p>531532<pre><code>app.redirect('comments', function(req, res, params){533 return '/post/' + params.id + '/comments';534});535</code></pre>536537<p>So now we may do the following, and the redirect will dynamically adjust to538the context of the request. If we called this route with <em>GET /post/12</em> our539redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>540541<pre><code>app.get('/post/:id', function(req, res){542 res.redirect('comments');543});Added configuration sectionTj Holowaychukbefore adoption83d2555
line 544why, one step back544</code></pre>Configuration docsTj Holowaychukbefore adoptioncb04364
line 545why, one step back545Started guideTj Holowaychukbefore adoption9e3a0c6
lines 546–550why, one step back546</div>547 </div>548 </div>549 </body>550</html>