Skip to content
Myr

guide.html

This file

Path

docs/guide.html

620 lines · 18.1 KiB · HTML

Last changed by

More docsTj Holowaychukbefore adoptionde81ee7

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			  text-decoration: none;48			  color: white;49			  -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;50			  -webkit-transition-duration: 0.15s;51			  -webkit-transition-timing-function: ease-out; }52			  a:hover {53			    opacity: 0.8; }5455			h1, h2, h3 {56			  margin: 45px 0 0 0;57			  color: white;58			  text-shadow: 1px 2px 2px rgba(0,0,0,0.6); }5960			h3 {61			  font-size: 18px; }6263			pre {64			  margin: 20px 10px;65			  padding: 25px 20px;66			  background: rgba(0,0,0,0.5);67			  border: 1px solid #323232;68			  -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);69			  -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);70			  -webkit-border-radius: 5px;71			  -moz-border-radius: 5px; }7273			code {74			  font-family: "Helvetica Neue", "Lucida Grande", "Arial"; }7576			ul {77			  margin: 15px 0;78			  padding: 0 0 0 35px; }79			  ul li {80			    margin: 0;81			    padding: 2px 0;82			    list-style: square; }8384			.sect {85			  margin-left: 40px; }8687			#logo {88			  display: block;89			  margin-left: 30%;90			  margin-bottom: 30px;91			  width: 194px;92			  height: 51px;93			  background: url(images/logo.png) 0 0 no-repeat;94			  text-indent: -99999px; }95			  #logo:hover {96			    opacity: 0.7; }97			  #logo:active {98			    opacity: 0.3; }99100			#ribbon {101			  position: fixed;102			  top: 0;103			  right: 0;104			  z-index: 2; }105106			#wrapper {107			  width: 100%;108			  min-height: 800px;109			  background: url(images/top.png) 0 0 repeat-x; }110111			#container {112			  margin: 0 auto;113			  padding-top: 110px;114			  width: 550px; }115116			#toc {117				position: fixed;118				top: 60px;119				left: 0;120				margin: 0 0 0 15px;121				padding: 15px;122				height: 100%;123				background: rgba(0,0,0,0.2);124				border-right: 1px solid rgba(255,255,255,0.05);125			}126			#toc li {127				padding: 1px 0;128				list-style: none;129			}130			#toc li a {131				font-size: 11px;132			}133			#menu {134			  margin-left: 65px;135			  padding: 0;136			  padding-bottom: 30px; }137			  #menu li {138			    display: inline;139			    list-style: none; }140			    #menu li a {141			      display: block;142			      float: left;143			      margin: 0 2px;144			      padding: 3px 15px;145			      background: rgba(0,0,0,0.2);146			      -webkit-border-radius: 8px;147			      -moz-border-radius: 8px;148			      -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);149			      -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);150			      -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;151			      -webkit-transition-duration: 0.15s;152			      -webkit-transition-timing-function: ease-out; }153			      #menu li a:hover,154			      #menu li a.active {155			        background: rgba(0,0,0,0.5); }156			      #menu li a:active {157			        background: rgba(0,0,0,0.1);158			        -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);159			        -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }160		</style>161	</head>162	<body>163		<a href='http://github.com/visionmedia/express'> 164		  <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 165		</a>166		<div id="header"><strong>Sencha</strong> labs</div>167		<div id="wrapper">168			<div id="container"><ul id="toc">169<li><a href="#Installation">Installation</a></li>170<li><a href="#Creating-An-Application">Creating An Application</a></li>171<li><a href="#Configuration">Configuration</a></li>172<li><a href="#Settings">Settings</a></li>173<li><a href="#Routing">Routing</a></li>174<li><a href="#Passing-Route-Control">Passing Route Control</a></li>175<li><a href="#Middleware">Middleware</a></li>176<li><a href="#req-header-key-defaultValue-">req.header()</a></li>177<li><a href="#req-accepts-type-">req.accepts()</a></li>178<li><a href="#req-param-name-">req.param()</a></li>179<li><a href="#req-flash-type-msg-">req.flash()</a></li>180<li><a href="#req-isXMLHttpRequest">req.isXMLHttpRequest</a></li>181<li><a href="#res-header-key-val-">res.header()</a></li>182<li><a href="#res-contentType-type-">res.contentType()</a></li>183<li><a href="#res-attachment-filename-">res.attachment()</a></li>184<li><a href="#res-sendfile-path-">res.sendfile()</a></li>185<li><a href="#res-download-file-filename-">res.download()</a></li>186<li><a href="#res-send-body-status-headers-status-status-">res.send()</a></li>187<li><a href="#res-redirect-url-status-">res.redirect()</a></li>188<li><a href="#app-set-name-val-">app.set()</a></li>189<li><a href="#app-enable-name-">app.enable()</a></li>190<li><a href="#app-disable-name-">app.disable()</a></li>191<li><a href="#app-configure-env-function-function-">app.configure()</a></li>192<li><a href="#app-redirect-name-val-">app.redirect()</a></li>193</ul>194				<a href='http://github.com/visionmedia/express' id='logo'>Express</a> 195				<p id="tagline">196				   High performance, high class web development for197				  <a href="http://nodejs.org">Node.js</a>198				</p>199				<ul id="menu">200					<li><a href="index.html">Home</a></li>201					<li><a href="guide.html">Guide</a></li>202					<li><a href="contrib.html">Contributing</a></li>203					<li><a href="migrate.html">1.x Migration</a></li>204				</ul>205<div class='mp'>206<h3 id="Installation">Installation</h3>207208<p>npm:</p>209210<pre><code>$ npm install express211</code></pre>212213<p>curl (or similar):</p>214215<pre><code>$ curl -# http://github.com/extjs/Connect/raw/master/install.sh | sh216</code></pre>217218<p>git clone or tarball for <strong>HEAD</strong>:</p>219220<pre><code>$ make install221</code></pre>222223<h3 id="Creating-An-Application">Creating An Application</h3>224225<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however226follows the same idiom by providing <em>express.createServer()</em> as shown below. This means227that you can utilize Express server's transparently with other libraries.</p>228229<pre><code>var app = require('express').createServer();230231app.get('/', function(req, res){232    res.send('hello world');233});234235app.listen(3000);236</code></pre>237238<h3 id="Configuration">Configuration</h3>239240<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers241can use the <em>configure()</em> method to setup needs required by the current environment. When242<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment243prior to the environment specific callback.</p>244245<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces246in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.</p>247248<pre><code>app.configure(function(){249    app.use('/', connect.methodOverride());250    app.use('/', connect.bodyDecoder());251});252253app.configure('development', function(){254    app.use('/', connect.errorHandler({ dumpExceptions: true, showStack: true }));255});256257app.configure('production', function(){258    app.use('/', connect.errorHandler());259});260</code></pre>261262<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>263264<pre><code>app.configure(function(){265    app.set('views', __dirname + '/views');266    app.set('views');267    // =&gt; "... views directory ..."268269    app.enable('some feature');270    // same as app.set('some feature', true);271272    app.disable('some feature');273    // same as app.set('some feature', false);274});275</code></pre>276277<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,278or more specifically <em>EXPRESS_ENV</em>, for example:</p>279280<pre><code>$ EXPRESS_ENV=production node app.js281</code></pre>282283<h3 id="Settings">Settings</h3>284285<p>Express supports the following settings out of the box:</p>286287<ul>288<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> to utilize</li>289<li><em>home</em> Application base path used with <em>res.redirect()</em></li>290<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>291<li><em>view engine</em> Default view engine name for views rendered without extensions</li>292<li><em>reload views</em> Reloads altered views, by default watches for <em>mtime</em> changes with293  with a 5 minute interval. Example: <em>app.set('reload views', 60000);</em></li>294</ul>295296297<h3 id="Routing">Routing</h3>298299<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.300For example we may want to render a user's account for the path <em>/user/12</em>, this301can be done by defining the route below. The values associated to the named placeholders,302are passed as the <em>third</em> argument, which here we name <em>params</em>.</p>303304<pre><code>app.get('/user/:id', function(req, res, params){305    res.send('user ' + params.id);306});307</code></pre>308309<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example310when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>311312<pre><code>\/user\/([^\/]+)\/?313</code></pre>314315<p>Literal regular expressions may also be passed for complex uses:</p>316317<pre><code>app.get(/^\/foo(bar)?$/, function(){});318</code></pre>319320<p>Below are some route examples, and the associated paths that they321may consume:</p>322323<pre><code> "/user/:id"324 /user/12325326 "/users/:id?"327 /users/5328 /users329330 "/files/*"331 /files/jquery.js332 /files/javascripts/jquery.js333334 "/file/*.*"335 /files/jquery.js336 /files/javascripts/jquery.js337338 "/user/:id/:operation?"339 /user/1340 /user/1/edit341342 "/products.:format"343 /products.json344 /products.xml345346 "/products.:format?"347 /products.json348 /products.xml349 /products350</code></pre>351352<h3 id="Passing-Route-Control">Passing Route Control</h3>353354<p>We may pass control to the next <em>matching</em> route, by calling the <em>fourth</em> parameter,355the <em>next()</em> function. When a match cannot be made, control is passed back to Connect.</p>356357<pre><code>app.get('/users/:id?', function(req, res, params){358    if (params.id) {359        // do something360    } else {361        next();362    }363});364365app.get('/users', function(req, res, params){366    // do something else367});368</code></pre>369370<h3 id="Middleware">Middleware</h3>371372<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/extjs/Connect">Connect</a> can be373passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>374375<pre><code>var connect = require('connect'),376    express = require('express');377378var app = express.createServer(379    connect.logger(),380    connect.bodyDecoder()381);382</code></pre>383384<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>385386<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>387388<pre><code>req.header('Host');389req.header('host');390req.header('Accept', '*/*');391</code></pre>392393<h3 id="req-accepts-type-">req.accepts(type)</h3>394395<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>396397<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise398the given <em>type</em> is matched by an exact match, and then subtypes. You399may pass the subtype such as "html" which is then converted internally400to "text/html" using the mime lookup table.</p>401402<pre><code>// Accept: text/html403req.accepts('html');404// =&gt; true405406// Accept: text/*; application/json407req.accepts('html');408req.accepts('text/html');409req.accepts('text/plain');410req.accepts('application/json');411// =&gt; true412413req.accepts('image/png');414req.accepts('png');415// =&gt; false416</code></pre>417418<h3 id="req-param-name-">req.param(name)</h3>419420<p>Return the value of param <em>name</em> when present.</p>421422<ul>423<li>Checks route placeholders, ex: /user/:id</li>424<li>Checks query string params, ex: ?id=12</li>425<li>Checks urlencoded body params, ex: id=12</li>426</ul>427428429<p>To utilize urlencoded request bodies, <em>req.body</em>430should be an object. This can be done by using431the <em>connect.bodyDecoder</em> middleware.</p>432433<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>434435<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>436437<pre><code>req.flash('info', 'email sent');438req.flash('error', 'email delivery failed');439req.flash('info', 'email re-sent');440// =&gt; 2441442req.flash('info');443// =&gt; ['email sent', 'email re-sent']444445req.flash('info');446// =&gt; []447448req.flash();449// =&gt; { error: ['email delivery failed'], info: [] }450</code></pre>451452<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>453454<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header455to see if it was issued by an <em>XMLHttpRequest</em>:</p>456457<pre><code>req.xhr458req.isXMLHttpRequest459</code></pre>460461<h3 id="res-header-key-val-">res.header(key[, val])</h3>462463<p>Get or set the response header <em>key</em>.</p>464465<pre><code>res.header('Content-Length');466// =&gt; undefined467468res.header('Content-Length', 123);469// =&gt; 123470471res.header('Content-Length');472// =&gt; 123473</code></pre>474475<h3 id="res-contentType-type-">res.contentType(type)</h3>476477<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>478479<pre><code>  var filename = 'path/to/image.png';480  res.contentType(filename);481  // res.headers['Content-Type'] is now "image/png"482</code></pre>483484<h3 id="res-attachment-filename-">res.attachment([filename])</h3>485486<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>487488<pre><code>  res.attachment('path/to/my/image.png');489</code></pre>490491<h3 id="res-sendfile-path-">res.sendfile(path)</h3>492493<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>494495<pre><code>res.sendfile('path/to/my.file');496</code></pre>497498<p><strong>NOTE</strong>: this is <em>not</em> a replacement for Connect's <em>staticProvider</em> middleware,499nor does it perform any security checks, use with caution when using in a dynamic manor.</p>500501<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>502503<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>504505<pre><code>res.download('path/to/image.png');506res.download('path/to/image.png', 'foo.png');507</code></pre>508509<p>This is equivalent to:</p>510511<pre><code>res.attachment(file);512res.sendfile(file);513</code></pre>514515<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>516517<p>The <code>res.send()</code> method is a high level response utility allowing you to pass518objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status519code based responses. The following are all valid uses:</p>520521<pre><code> res.send(new Buffer('wahoo'));522 res.send({ some: 'json' });523 res.send('&lt;p&gt;some html&lt;/p&gt;');524 res.send('Sorry, cant find that', 404);525 res.send('text', { 'Content-Type': 'text/plain' }, 201);526 res.send(404);527</code></pre>528529<p>By default the <em>Content-Type</em> response header is set, however if explicitly530assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>531it will not be set again.</p>532533<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>534535<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>536537<pre><code>res.redirect('/', 301);538res.redirect('/account');539res.redirect('http://google.com');540res.redirect('home');541res.redirect('back');542</code></pre>543544<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.545The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes546the "home" setting and defaults to "/".</p>547548<h3 id="app-set-name-val-">app.set(name[, val])</h3>549550<p>Apply an application level setting <em>name</em> to <em>val</em>, or551get the value of <em>name</em> when <em>val</em> is not present:</p>552553<pre><code>app.set('reload views', 200);554app.set('reload views');555// =&gt; 200556</code></pre>557558<h3 id="app-enable-name-">app.enable(name)</h3>559560<p>Enable the given setting <em>name</em>:</p>561562<pre><code>app.enable('some arbitrary setting');563app.set('some arbitrary setting');564// =&gt; true565</code></pre>566567<h3 id="app-disable-name-">app.disable(name)</h3>568569<p>Disable the given setting <em>name</em>:</p>570571<pre><code>app.disable('some setting');572app.set('some setting');573// =&gt; false574</code></pre>575576<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>577578<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>579580<pre><code>app.configure(function(){581    // executed for each env582});583584app.configure('development', function(){585    // executed for 'development' only586});587</code></pre>588589<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>590591<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>592593<pre><code>app.redirect('google', 'http://google.com');594</code></pre>595596<p>Now in a route we may call:</p>597598<p>   res.redirect('google');</p>599600<p>We may also map dynamic redirects:</p>601602<pre><code>app.redirect('comments', function(req, res, params){603    return '/post/' + params.id + '/comments';604});605</code></pre>606607<p>So now we may do the following, and the redirect will dynamically adjust to608the context of the request. If we called this route with <em>GET /post/12</em> our609redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>610611<pre><code>app.get('/post/:id', function(req, res){612    res.redirect('comments');613});614</code></pre>615616</div>617			</div>618		</div>619	</body>620</html>