Skip to content
Myr

guide.html

This file

Path

docs/guide.html

529 lines · 15.3 KiB · HTML

Last changed by

Install docsTj Holowaychukbefore adoption63d02f1

History of this file

Take 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			#menu {116			  margin-left: 65px;117			  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);132			      -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;133			      -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">150			<div id="container">151				<a href='http://github.com/visionmedia/express' id='logo'>Express</a> 152				<p id="tagline">153				   High performance, high class web development for154				  <a href="http://nodejs.org">Node.js</a>155				</p>156				<ul id="menu">157					<li><a href="index.html">Home</a></li>158					<li><a href="guide.html">Guide</a></li>159					<li><a href="contrib.html">Contributing</a></li>160					<li><a href="migrate.html">1.x Migration</a></li>161				</ul>162<div class='mp'>163<h3 id="Installation">Installation</h3>164165<p>npm:</p>166167<pre><code>$ npm install express168</code></pre>169170<p>curl (or similar):</p>171172<pre><code>$ curl -# http://github.com/extjs/Connect/raw/master/install.sh | sh173</code></pre>174175<p>git clone or tarball for <strong>HEAD</strong>:</p>176177<pre><code>$ make install178</code></pre>179180<h3 id="Creating-An-Application">Creating An Application</h3>181182<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however183follows the same idiom by providing <em>express.createServer()</em> as shown below. This means184that you can utilize Express server's transparently with other libraries.</p>185186<pre><code>var app = require('express').createServer();187188app.get('/', function(req, res){189    res.send('hello world');190});191192app.listen(3000);193</code></pre>194195<h3 id="Configuration">Configuration</h3>196197<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers198can use the <em>configure()</em> method to setup needs required by the current environment. When199<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment200prior to the environment specific callback.</p>201202<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces203in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.</p>204205<pre><code>app.configure(function(){206    app.use('/', connect.methodOverride());207    app.use('/', connect.bodyDecoder());208});209210app.configure('development', function(){211    app.use('/', connect.errorHandler({ dumpExceptions: true, showStack: true }));212});213214app.configure('production', function(){215    app.use('/', connect.errorHandler());216});217</code></pre>218219<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>220221<pre><code>app.configure(function(){222    app.set('views', __dirname + '/views');223    app.set('views');224    // =&gt; "... views directory ..."225226    app.enable('some feature');227    // same as app.set('some feature', true);228229    app.disable('some feature');230    // same as app.set('some feature', false);231});232</code></pre>233234<h3 id="Settings">Settings</h3>235236<p>Express supports the following settings out of the box:</p>237238<ul>239<li><em>home</em> Application base path used with <em>res.redirect()</em></li>240<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>241<li><em>view engine</em> Default view engine name for views rendered without extensions</li>242<li><em>reload views</em> Reloads altered views, by default watches for <em>mtime</em> changes with243  with a 5 minute interval. Example: <code>app.set('reload views', { interval: 60000 });</code></li>244</ul>245246247<h3 id="Routing">Routing</h3>248249<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.250For example we may want to render a user's account for the path <em>/user/12</em>, this251can be done by defining the route below. The values associated to the named placeholders,252are passed as the <em>third</em> argument, which here we name <em>params</em>.</p>253254<pre><code>app.get('/user/:id', function(req, res, params){255    res.send('user ' + params.id);256});257</code></pre>258259<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example260when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>261262<pre><code>\/user\/([^\/]+)\/?263</code></pre>264265<p>Literal regular expressions may also be passed for complex uses:</p>266267<pre><code>app.get(/^\/foo(bar)?$/, function(){});268</code></pre>269270<p>Below are some route examples, and the associated paths that they271may consume:</p>272273<pre><code> "/user/:id"274 /user/12275276 "/users/:id?"277 /users/5278 /users279280 "/files/*"281 /files/jquery.js282 /files/javascripts/jquery.js283284 "/file/*.*"285 /files/jquery.js286 /files/javascripts/jquery.js287288 "/user/:id/:operation?"289 /user/1290 /user/1/edit291292 "/products.:format"293 /products.json294 /products.xml295296 "/products.:format?"297 /products.json298 /products.xml299 /products300</code></pre>301302<h3 id="Passing-Route-Control">Passing Route Control</h3>303304<p>We may pass control to the next <em>matching</em> route, by calling the <em>fourth</em> parameter,305the <em>next()</em> function. When a match cannot be made, control is passed back to Connect.</p>306307<pre><code>app.get('/users/:id?', function(req, res, params){308    if (params.id) {309        // do something310    } else {311        next();312    }313});314315app.get('/users', function(req, res, params){316    // do something else317});318</code></pre>319320<h3 id="Middleware">Middleware</h3>321322<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/extjs/Connect">Connect</a> can be323passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>324325<pre><code>var connect = require('connect'),326    express = require('express');327328var app = express.createServer(329    connect.logger(),330    connect.bodyDecoder()331);332</code></pre>333334<h3 id="ServerRequest-header-key-defaultValue-">ServerRequest#header(key[, defaultValue])</h3>335336<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>337338<pre><code>req.header('Host');339req.header('host');340req.header('Accept', '*/*');341</code></pre>342343<h3 id="ServerRequest-accepts-type-">ServerRequest#accepts(type)</h3>344345<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>346347<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise348the given <em>type</em> is matched by an exact match, and then subtypes. You349may pass the subtype such as "html" which is then converted internally350to "text/html" using the mime lookup table.</p>351352<pre><code>// Accept: text/html353req.accepts('html');354// =&gt; true355356// Accept: text/*; application/json357req.accepts('html');358req.accepts('text/html');359req.accepts('text/plain');360req.accepts('application/json');361// =&gt; true362363req.accepts('image/png');364req.accepts('png');365// =&gt; false366</code></pre>367368<h3 id="ServerRequest-param-name-">ServerRequest#param(name)</h3>369370<p>Return the value of param <em>name</em> when present.</p>371372<ul>373<li>Checks route placeholders, ex: /user/:id</li>374<li>Checks query string params, ex: ?id=12</li>375<li>Checks urlencoded body params, ex: id=12</li>376</ul>377378379<p>To utilize urlencoded request bodies, <em>req.body</em>380should be an object. This can be done by using381the <em>connect.bodyDecoder</em> middleware.</p>382383<h3 id="ServerRequest-flash-type-msg-">ServerRequest#flash(type[, msg])</h3>384385<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>386387<pre><code>req.flash('info', 'email sent');388req.flash('error', 'email delivery failed');389req.flash('info', 'email re-sent');390// =&gt; 2391392req.flash('info');393// =&gt; ['email sent', 'email re-sent']394395req.flash('info');396// =&gt; []397398req.flash();399// =&gt; { error: ['email delivery failed'], info: [] }400</code></pre>401402<h3 id="ServerRequest-isXMLHttpRequest">ServerRequest#isXMLHttpRequest</h3>403404<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header405to see if it was issued by an <em>XMLHttpRequest</em>:</p>406407<pre><code>req.xhr408req.isXMLHttpRequest409</code></pre>410411<h3 id="ServerResponse-header-key-val-">ServerResponse#header(key[, val])</h3>412413<p>Get or set the response header <em>key</em>.</p>414415<pre><code>res.header('Content-Length');416// =&gt; undefined417418res.header('Content-Length', 123);419// =&gt; 123420421res.header('Content-Length');422// =&gt; 123423</code></pre>424425<h3 id="ServerResponse-contentType-type-">ServerResponse#contentType(type)</h3>426427<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>428429<pre><code>  var filename = 'path/to/image.png';430  res.contentType(filename);431  // res.headers['Content-Type'] is now "image/png"432</code></pre>433434<h3 id="ServerResponse-attachment-filename-">ServerResponse#attachment([filename])</h3>435436<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>437438<pre><code>  res.attachment('path/to/my/image.png');439</code></pre>440441<h3 id="ServerResponse-sendfile-path-">ServerResponse#sendfile(path)</h3>442443<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>444445<pre><code>res.sendfile('path/to/my.file');446</code></pre>447448<p><strong>NOTE</strong>: this is <em>not</em> a replacement for Connect's <em>staticProvider</em> middleware,449nor does it perform any security checks, use with caution when using in a dynamic manor.</p>450451<h3 id="ServerResponse-download-file-filename-">ServerResponse#download(file[, filename])</h3>452453<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>454455<pre><code>res.download('path/to/image.png');456res.download('path/to/image.png', 'foo.png');457</code></pre>458459<p>This is equivalent to:</p>460461<pre><code>res.attachment(file);462res.sendfile(file);463</code></pre>464465<h3 id="ServerRequest-send-body-status-headers-status-status-">ServerRequest#send(body|status[, headers|status[, status]])</h3>466467<p>The <code>res.send()</code> method is a high level response utility allowing you to pass468objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status469code based responses. The following are all valid uses:</p>470471<pre><code> res.send(new Buffer('wahoo'));472 res.send({ some: 'json' });473 res.send('&lt;p&gt;some html&lt;/p&gt;');474 res.send('Sorry, cant find that', 404);475 res.send('text', { 'Content-Type': 'text/plain' }, 201);476 res.send(404);477</code></pre>478479<p>By default the <em>Content-Type</em> response header is set, however if explicitly480assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>481it will not be set again.</p>482483<h3 id="ServerResponse-redirect-url-status-">ServerResponse#redirect(url[, status])</h3>484485<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>486487<pre><code>res.redirect('/', 301);488res.redirect('/account');489res.redirect('http://google.com');490res.redirect('home');491res.redirect('back');492</code></pre>493494<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.495The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes496the "home" setting and defaults to "/".</p>497498<h3 id="Server-redirect-name-val-">Server#redirect(name, val)</h3>499500<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>501502<pre><code>app.redirect('google', 'http://google.com');503</code></pre>504505<p>Now in a route we may call:</p>506507<p>   res.redirect('google');</p>508509<p>We may also map dynamic redirects:</p>510511<pre><code>app.redirect('comments', function(req, res, params){512    return '/post/' + params.id + '/comments';513});514</code></pre>515516<p>So now we may do the following, and the redirect will dynamically adjust to517the context of the request. If we called this route with <em>GET /post/12</em> our518redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>519520<pre><code>app.get('/post/:id', function(req, res){521    res.redirect('comments');522});523</code></pre>524525</div>526			</div>527		</div>528	</body>529</html>