guide.html
This file
Path
docs/guide.html
566 lines · 16.7 KiB · HTML
Last changed by
Misc stylingTj Holowaychukbefore adoption7b55867
History of this fileTake it
1<html>2 <head>3 <title>Express - node web framework</title>4 <style>5 #header {6 position: absolute;7 top: 10px;8 left: 0;9 padding: 12px 0;10 text-indent: 40px;11 width: 100%;12 border-top: 1px solid rgba(0,0,0,0.7);13 border-bottom: 1px solid rgba(0,0,0,0.7);14 background: rgba(255,255,255,0.1) url(http://www.sencha.com/favicon.ico) no-repeat 15px 50%;15 text-align: left;16 color: #fff;17 }18 #tagline {19 margin-left: 75px;20 margin-bottom: 30px;21 color: rgba(255,255,255,0.7); }22 html {23 background: #1c1c1c url(images/bg.tile.jpg); }2425 body {26 margin: 0;27 padding-bottom: 30px;28 font: 14px/1.4 "Helvetica Neue", "Lucida Grande", "Arial";29 font-size: 14px;30 line-height: 1.5;31 -webkit-text-stroke: 1px rgba(0, 0, 0, 0.1);32 -moz-text-stroke: 1px rgba(0, 0, 0, 0.1);33 background: url(images/bg.jpg) 50% 0 no-repeat;34 color: #8b8b8b; }3536 * {37 outline: none; }3839 em {40 color: white; }4142 a img {43 border: none !important; }4445 a {46 font-weight: bold;47 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 #toc {116 position: fixed;117 top: 60px;118 left: 0;119 margin: 0 0 0 15px;120 padding: 15px;121 height: 100%;122 background: rgba(0,0,0,0.2);123 border-right: 1px solid rgba(255,255,255,0.05);124 }125 #toc li {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 </head>160 <body>161 <a href='http://github.com/visionmedia/express'> 162 <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 163 </a>164 <div id="header"><strong>Sencha</strong> labs</div>165 <div id="wrapper">166 <div id="container"><ul id="toc">167<li><a href="#Installation">Installation</a></li>168<li><a href="#Creating-An-Application">Creating An Application</a></li>169<li><a href="#Configuration">Configuration</a></li>170<li><a href="#Settings">Settings</a></li>171<li><a href="#Routing">Routing</a></li>172<li><a href="#Passing-Route-Control">Passing Route Control</a></li>173<li><a href="#Middleware">Middleware</a></li>174<li><a href="#Request-header-key-defaultValue-">Request#header</a></li>175<li><a href="#Request-accepts-type-">Request#accepts</a></li>176<li><a href="#Request-param-name-">Request#param</a></li>177<li><a href="#Request-flash-type-msg-">Request#flash</a></li>178<li><a href="#Request-isXMLHttpRequest">Request#isXMLHttpRequest</a></li>179<li><a href="#Response-header-key-val-">Response#header</a></li>180<li><a href="#Response-contentType-type-">Response#contentType</a></li>181<li><a href="#Response-attachment-filename-">Response#attachment</a></li>182<li><a href="#Response-sendfile-path-">Response#sendfile</a></li>183<li><a href="#Response-download-file-filename-">Response#download</a></li>184<li><a href="#Response-send-body-status-headers-status-status-">Response#send</a></li>185<li><a href="#Response-redirect-url-status-">Response#redirect</a></li>186<li><a href="#Server-redirect-name-val-">Server#redirect</a></li>187</ul>188 <a href='http://github.com/visionmedia/express' id='logo'>Express</a> 189 <p id="tagline">190 High performance, high class web development for191 <a href="http://nodejs.org">Node.js</a>192 </p>193 <ul id="menu">194 <li><a href="index.html">Home</a></li>195 <li><a href="guide.html">Guide</a></li>196 <li><a href="contrib.html">Contributing</a></li>197 <li><a href="migrate.html">1.x Migration</a></li>198 </ul>199<div class='mp'>200<h3 id="Installation">Installation</h3>201202<p>npm:</p>203204<pre><code>$ npm install express205</code></pre>206207<p>curl (or similar):</p>208209<pre><code>$ curl -# http://github.com/extjs/Connect/raw/master/install.sh | sh210</code></pre>211212<p>git clone or tarball for <strong>HEAD</strong>:</p>213214<pre><code>$ make install215</code></pre>216217<h3 id="Creating-An-Application">Creating An Application</h3>218219<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however220follows the same idiom by providing <em>express.createServer()</em> as shown below. This means221that you can utilize Express server's transparently with other libraries.</p>222223<pre><code>var app = require('express').createServer();224225app.get('/', function(req, res){226 res.send('hello world');227});228229app.listen(3000);230</code></pre>231232<h3 id="Configuration">Configuration</h3>233234<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers235can use the <em>configure()</em> method to setup needs required by the current environment. When236<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment237prior to the environment specific callback.</p>238239<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces240in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.</p>241242<pre><code>app.configure(function(){243 app.use('/', connect.methodOverride());244 app.use('/', connect.bodyDecoder());245});246247app.configure('development', function(){248 app.use('/', connect.errorHandler({ dumpExceptions: true, showStack: true }));249});250251app.configure('production', function(){252 app.use('/', connect.errorHandler());253});254</code></pre>255256<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>257258<pre><code>app.configure(function(){259 app.set('views', __dirname + '/views');260 app.set('views');261 // => "... views directory ..."262263 app.enable('some feature');264 // same as app.set('some feature', true);265266 app.disable('some feature');267 // same as app.set('some feature', false);268});269</code></pre>270271<h3 id="Settings">Settings</h3>272273<p>Express supports the following settings out of the box:</p>274275<ul>276<li><em>home</em> Application base path used with <em>res.redirect()</em></li>277<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>278<li><em>view engine</em> Default view engine name for views rendered without extensions</li>279<li><em>reload views</em> Reloads altered views, by default watches for <em>mtime</em> changes with280 with a 5 minute interval. Example: <code>app.set('reload views', { interval: 60000 });</code></li>281</ul>282283284<h3 id="Routing">Routing</h3>285286<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.287For example we may want to render a user's account for the path <em>/user/12</em>, this288can be done by defining the route below. The values associated to the named placeholders,289are passed as the <em>third</em> argument, which here we name <em>params</em>.</p>290291<pre><code>app.get('/user/:id', function(req, res, params){292 res.send('user ' + params.id);293});294</code></pre>295296<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example297when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>298299<pre><code>\/user\/([^\/]+)\/?300</code></pre>301302<p>Literal regular expressions may also be passed for complex uses:</p>303304<pre><code>app.get(/^\/foo(bar)?$/, function(){});305</code></pre>306307<p>Below are some route examples, and the associated paths that they308may consume:</p>309310<pre><code> "/user/:id"311 /user/12312313 "/users/:id?"314 /users/5315 /users316317 "/files/*"318 /files/jquery.js319 /files/javascripts/jquery.js320321 "/file/*.*"322 /files/jquery.js323 /files/javascripts/jquery.js324325 "/user/:id/:operation?"326 /user/1327 /user/1/edit328329 "/products.:format"330 /products.json331 /products.xml332333 "/products.:format?"334 /products.json335 /products.xml336 /products337</code></pre>338339<h3 id="Passing-Route-Control">Passing Route Control</h3>340341<p>We may pass control to the next <em>matching</em> route, by calling the <em>fourth</em> parameter,342the <em>next()</em> function. When a match cannot be made, control is passed back to Connect.</p>343344<pre><code>app.get('/users/:id?', function(req, res, params){345 if (params.id) {346 // do something347 } else {348 next();349 }350});351352app.get('/users', function(req, res, params){353 // do something else354});355</code></pre>356357<h3 id="Middleware">Middleware</h3>358359<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/extjs/Connect">Connect</a> can be360passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>361362<pre><code>var connect = require('connect'),363 express = require('express');364365var app = express.createServer(366 connect.logger(),367 connect.bodyDecoder()368);369</code></pre>370371<h3 id="Request-header-key-defaultValue-">Request#header(key[, defaultValue])</h3>372373<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>374375<pre><code>req.header('Host');376req.header('host');377req.header('Accept', '*/*');378</code></pre>379380<h3 id="Request-accepts-type-">Request#accepts(type)</h3>381382<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>383384<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise385the given <em>type</em> is matched by an exact match, and then subtypes. You386may pass the subtype such as "html" which is then converted internally387to "text/html" using the mime lookup table.</p>388389<pre><code>// Accept: text/html390req.accepts('html');391// => true392393// Accept: text/*; application/json394req.accepts('html');395req.accepts('text/html');396req.accepts('text/plain');397req.accepts('application/json');398// => true399400req.accepts('image/png');401req.accepts('png');402// => false403</code></pre>404405<h3 id="Request-param-name-">Request#param(name)</h3>406407<p>Return the value of param <em>name</em> when present.</p>408409<ul>410<li>Checks route placeholders, ex: /user/:id</li>411<li>Checks query string params, ex: ?id=12</li>412<li>Checks urlencoded body params, ex: id=12</li>413</ul>414415416<p>To utilize urlencoded request bodies, <em>req.body</em>417should be an object. This can be done by using418the <em>connect.bodyDecoder</em> middleware.</p>419420<h3 id="Request-flash-type-msg-">Request#flash(type[, msg])</h3>421422<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>423424<pre><code>req.flash('info', 'email sent');425req.flash('error', 'email delivery failed');426req.flash('info', 'email re-sent');427// => 2428429req.flash('info');430// => ['email sent', 'email re-sent']431432req.flash('info');433// => []434435req.flash();436// => { error: ['email delivery failed'], info: [] }437</code></pre>438439<h3 id="Request-isXMLHttpRequest">Request#isXMLHttpRequest</h3>440441<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header442to see if it was issued by an <em>XMLHttpRequest</em>:</p>443444<pre><code>req.xhr445req.isXMLHttpRequest446</code></pre>447448<h3 id="Response-header-key-val-">Response#header(key[, val])</h3>449450<p>Get or set the response header <em>key</em>.</p>451452<pre><code>res.header('Content-Length');453// => undefined454455res.header('Content-Length', 123);456// => 123457458res.header('Content-Length');459// => 123460</code></pre>461462<h3 id="Response-contentType-type-">Response#contentType(type)</h3>463464<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>465466<pre><code> var filename = 'path/to/image.png';467 res.contentType(filename);468 // res.headers['Content-Type'] is now "image/png"469</code></pre>470471<h3 id="Response-attachment-filename-">Response#attachment([filename])</h3>472473<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>474475<pre><code> res.attachment('path/to/my/image.png');476</code></pre>477478<h3 id="Response-sendfile-path-">Response#sendfile(path)</h3>479480<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>481482<pre><code>res.sendfile('path/to/my.file');483</code></pre>484485<p><strong>NOTE</strong>: this is <em>not</em> a replacement for Connect's <em>staticProvider</em> middleware,486nor does it perform any security checks, use with caution when using in a dynamic manor.</p>487488<h3 id="Response-download-file-filename-">Response#download(file[, filename])</h3>489490<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>491492<pre><code>res.download('path/to/image.png');493res.download('path/to/image.png', 'foo.png');494</code></pre>495496<p>This is equivalent to:</p>497498<pre><code>res.attachment(file);499res.sendfile(file);500</code></pre>501502<h3 id="Response-send-body-status-headers-status-status-">Response#send(body|status[, headers|status[, status]])</h3>503504<p>The <code>res.send()</code> method is a high level response utility allowing you to pass505objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status506code based responses. The following are all valid uses:</p>507508<pre><code> res.send(new Buffer('wahoo'));509 res.send({ some: 'json' });510 res.send('<p>some html</p>');511 res.send('Sorry, cant find that', 404);512 res.send('text', { 'Content-Type': 'text/plain' }, 201);513 res.send(404);514</code></pre>515516<p>By default the <em>Content-Type</em> response header is set, however if explicitly517assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>518it will not be set again.</p>519520<h3 id="Response-redirect-url-status-">Response#redirect(url[, status])</h3>521522<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>523524<pre><code>res.redirect('/', 301);525res.redirect('/account');526res.redirect('http://google.com');527res.redirect('home');528res.redirect('back');529</code></pre>530531<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.532The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes533the "home" setting and defaults to "/".</p>534535<h3 id="Server-redirect-name-val-">Server#redirect(name, val)</h3>536537<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>538539<pre><code>app.redirect('google', 'http://google.com');540</code></pre>541542<p>Now in a route we may call:</p>543544<p> res.redirect('google');</p>545546<p>We may also map dynamic redirects:</p>547548<pre><code>app.redirect('comments', function(req, res, params){549 return '/post/' + params.id + '/comments';550});551</code></pre>552553<p>So now we may do the following, and the redirect will dynamically adjust to554the context of the request. If we called this route with <em>GET /post/12</em> our555redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>556557<pre><code>app.get('/post/:id', function(req, res){558 res.redirect('comments');559});560</code></pre>561562</div>563 </div>564 </div>565 </body>566</html>