Skip to content
Myr

guide.html

This file

Path

docs/guide.html

567 lines · 16.7 KiB · HTML

Last changed by

Fixed reload views exampleTj Holowaychukbefore adoption5fcf971

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				list-style: none;128			}129			#toc li a {130				font-size: 11px;131			}132			#menu {133			  margin-left: 65px;134			  padding: 0;135			  padding-bottom: 30px; }136			  #menu li {137			    display: inline;138			    list-style: none; }139			    #menu li a {140			      display: block;141			      float: left;142			      margin: 0 2px;143			      padding: 3px 15px;144			      background: rgba(0,0,0,0.2);145			      -webkit-border-radius: 8px;146			      -moz-border-radius: 8px;147			      -webkit-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);148			      -moz-box-shadow: 1px 2px 2px rgba(0,0,0,0.6);149			      -webkit-transition-property: opacity, -webkit-transform, color, background-color, -webkit-box-shadow;150			      -webkit-transition-duration: 0.15s;151			      -webkit-transition-timing-function: ease-out; }152			      #menu li a:hover,153			      #menu li a.active {154			        background: rgba(0,0,0,0.5); }155			      #menu li a:active {156			        background: rgba(0,0,0,0.1);157			        -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.4);158			        -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.4); }159		</style>160	</head>161	<body>162		<a href='http://github.com/visionmedia/express'> 163		  <img alt='Fork me on GitHub' id='ribbon' src='http://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png' /> 164		</a>165		<div id="header"><strong>Sencha</strong> labs</div>166		<div id="wrapper">167			<div id="container"><ul id="toc">168<li><a href="#Installation">Installation</a></li>169<li><a href="#Creating-An-Application">Creating An Application</a></li>170<li><a href="#Configuration">Configuration</a></li>171<li><a href="#Settings">Settings</a></li>172<li><a href="#Routing">Routing</a></li>173<li><a href="#Passing-Route-Control">Passing Route Control</a></li>174<li><a href="#Middleware">Middleware</a></li>175<li><a href="#Request-header-key-defaultValue-">Request#header</a></li>176<li><a href="#Request-accepts-type-">Request#accepts</a></li>177<li><a href="#Request-param-name-">Request#param</a></li>178<li><a href="#Request-flash-type-msg-">Request#flash</a></li>179<li><a href="#Request-isXMLHttpRequest">Request#isXMLHttpRequest</a></li>180<li><a href="#Response-header-key-val-">Response#header</a></li>181<li><a href="#Response-contentType-type-">Response#contentType</a></li>182<li><a href="#Response-attachment-filename-">Response#attachment</a></li>183<li><a href="#Response-sendfile-path-">Response#sendfile</a></li>184<li><a href="#Response-download-file-filename-">Response#download</a></li>185<li><a href="#Response-send-body-status-headers-status-status-">Response#send</a></li>186<li><a href="#Response-redirect-url-status-">Response#redirect</a></li>187<li><a href="#Server-redirect-name-val-">Server#redirect</a></li>188</ul>189				<a href='http://github.com/visionmedia/express' id='logo'>Express</a> 190				<p id="tagline">191				   High performance, high class web development for192				  <a href="http://nodejs.org">Node.js</a>193				</p>194				<ul id="menu">195					<li><a href="index.html">Home</a></li>196					<li><a href="guide.html">Guide</a></li>197					<li><a href="contrib.html">Contributing</a></li>198					<li><a href="migrate.html">1.x Migration</a></li>199				</ul>200<div class='mp'>201<h3 id="Installation">Installation</h3>202203<p>npm:</p>204205<pre><code>$ npm install express206</code></pre>207208<p>curl (or similar):</p>209210<pre><code>$ curl -# http://github.com/extjs/Connect/raw/master/install.sh | sh211</code></pre>212213<p>git clone or tarball for <strong>HEAD</strong>:</p>214215<pre><code>$ make install216</code></pre>217218<h3 id="Creating-An-Application">Creating An Application</h3>219220<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however221follows the same idiom by providing <em>express.createServer()</em> as shown below. This means222that you can utilize Express server's transparently with other libraries.</p>223224<pre><code>var app = require('express').createServer();225226app.get('/', function(req, res){227    res.send('hello world');228});229230app.listen(3000);231</code></pre>232233<h3 id="Configuration">Configuration</h3>234235<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers236can use the <em>configure()</em> method to setup needs required by the current environment. When237<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment238prior to the environment specific callback.</p>239240<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces241in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.</p>242243<pre><code>app.configure(function(){244    app.use('/', connect.methodOverride());245    app.use('/', connect.bodyDecoder());246});247248app.configure('development', function(){249    app.use('/', connect.errorHandler({ dumpExceptions: true, showStack: true }));250});251252app.configure('production', function(){253    app.use('/', connect.errorHandler());254});255</code></pre>256257<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>258259<pre><code>app.configure(function(){260    app.set('views', __dirname + '/views');261    app.set('views');262    // =&gt; "... views directory ..."263264    app.enable('some feature');265    // same as app.set('some feature', true);266267    app.disable('some feature');268    // same as app.set('some feature', false);269});270</code></pre>271272<h3 id="Settings">Settings</h3>273274<p>Express supports the following settings out of the box:</p>275276<ul>277<li><em>home</em> Application base path used with <em>res.redirect()</em></li>278<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>279<li><em>view engine</em> Default view engine name for views rendered without extensions</li>280<li><em>reload views</em> Reloads altered views, by default watches for <em>mtime</em> changes with281  with a 5 minute interval. Example: <em>app.set('reload views', 60000);</em></li>282</ul>283284285<h3 id="Routing">Routing</h3>286287<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.288For example we may want to render a user's account for the path <em>/user/12</em>, this289can be done by defining the route below. The values associated to the named placeholders,290are passed as the <em>third</em> argument, which here we name <em>params</em>.</p>291292<pre><code>app.get('/user/:id', function(req, res, params){293    res.send('user ' + params.id);294});295</code></pre>296297<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example298when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>299300<pre><code>\/user\/([^\/]+)\/?301</code></pre>302303<p>Literal regular expressions may also be passed for complex uses:</p>304305<pre><code>app.get(/^\/foo(bar)?$/, function(){});306</code></pre>307308<p>Below are some route examples, and the associated paths that they309may consume:</p>310311<pre><code> "/user/:id"312 /user/12313314 "/users/:id?"315 /users/5316 /users317318 "/files/*"319 /files/jquery.js320 /files/javascripts/jquery.js321322 "/file/*.*"323 /files/jquery.js324 /files/javascripts/jquery.js325326 "/user/:id/:operation?"327 /user/1328 /user/1/edit329330 "/products.:format"331 /products.json332 /products.xml333334 "/products.:format?"335 /products.json336 /products.xml337 /products338</code></pre>339340<h3 id="Passing-Route-Control">Passing Route Control</h3>341342<p>We may pass control to the next <em>matching</em> route, by calling the <em>fourth</em> parameter,343the <em>next()</em> function. When a match cannot be made, control is passed back to Connect.</p>344345<pre><code>app.get('/users/:id?', function(req, res, params){346    if (params.id) {347        // do something348    } else {349        next();350    }351});352353app.get('/users', function(req, res, params){354    // do something else355});356</code></pre>357358<h3 id="Middleware">Middleware</h3>359360<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/extjs/Connect">Connect</a> can be361passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>362363<pre><code>var connect = require('connect'),364    express = require('express');365366var app = express.createServer(367    connect.logger(),368    connect.bodyDecoder()369);370</code></pre>371372<h3 id="Request-header-key-defaultValue-">Request#header(key[, defaultValue])</h3>373374<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>375376<pre><code>req.header('Host');377req.header('host');378req.header('Accept', '*/*');379</code></pre>380381<h3 id="Request-accepts-type-">Request#accepts(type)</h3>382383<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>384385<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise386the given <em>type</em> is matched by an exact match, and then subtypes. You387may pass the subtype such as "html" which is then converted internally388to "text/html" using the mime lookup table.</p>389390<pre><code>// Accept: text/html391req.accepts('html');392// =&gt; true393394// Accept: text/*; application/json395req.accepts('html');396req.accepts('text/html');397req.accepts('text/plain');398req.accepts('application/json');399// =&gt; true400401req.accepts('image/png');402req.accepts('png');403// =&gt; false404</code></pre>405406<h3 id="Request-param-name-">Request#param(name)</h3>407408<p>Return the value of param <em>name</em> when present.</p>409410<ul>411<li>Checks route placeholders, ex: /user/:id</li>412<li>Checks query string params, ex: ?id=12</li>413<li>Checks urlencoded body params, ex: id=12</li>414</ul>415416417<p>To utilize urlencoded request bodies, <em>req.body</em>418should be an object. This can be done by using419the <em>connect.bodyDecoder</em> middleware.</p>420421<h3 id="Request-flash-type-msg-">Request#flash(type[, msg])</h3>422423<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>424425<pre><code>req.flash('info', 'email sent');426req.flash('error', 'email delivery failed');427req.flash('info', 'email re-sent');428// =&gt; 2429430req.flash('info');431// =&gt; ['email sent', 'email re-sent']432433req.flash('info');434// =&gt; []435436req.flash();437// =&gt; { error: ['email delivery failed'], info: [] }438</code></pre>439440<h3 id="Request-isXMLHttpRequest">Request#isXMLHttpRequest</h3>441442<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header443to see if it was issued by an <em>XMLHttpRequest</em>:</p>444445<pre><code>req.xhr446req.isXMLHttpRequest447</code></pre>448449<h3 id="Response-header-key-val-">Response#header(key[, val])</h3>450451<p>Get or set the response header <em>key</em>.</p>452453<pre><code>res.header('Content-Length');454// =&gt; undefined455456res.header('Content-Length', 123);457// =&gt; 123458459res.header('Content-Length');460// =&gt; 123461</code></pre>462463<h3 id="Response-contentType-type-">Response#contentType(type)</h3>464465<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>466467<pre><code>  var filename = 'path/to/image.png';468  res.contentType(filename);469  // res.headers['Content-Type'] is now "image/png"470</code></pre>471472<h3 id="Response-attachment-filename-">Response#attachment([filename])</h3>473474<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>475476<pre><code>  res.attachment('path/to/my/image.png');477</code></pre>478479<h3 id="Response-sendfile-path-">Response#sendfile(path)</h3>480481<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>482483<pre><code>res.sendfile('path/to/my.file');484</code></pre>485486<p><strong>NOTE</strong>: this is <em>not</em> a replacement for Connect's <em>staticProvider</em> middleware,487nor does it perform any security checks, use with caution when using in a dynamic manor.</p>488489<h3 id="Response-download-file-filename-">Response#download(file[, filename])</h3>490491<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>492493<pre><code>res.download('path/to/image.png');494res.download('path/to/image.png', 'foo.png');495</code></pre>496497<p>This is equivalent to:</p>498499<pre><code>res.attachment(file);500res.sendfile(file);501</code></pre>502503<h3 id="Response-send-body-status-headers-status-status-">Response#send(body|status[, headers|status[, status]])</h3>504505<p>The <code>res.send()</code> method is a high level response utility allowing you to pass506objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status507code based responses. The following are all valid uses:</p>508509<pre><code> res.send(new Buffer('wahoo'));510 res.send({ some: 'json' });511 res.send('&lt;p&gt;some html&lt;/p&gt;');512 res.send('Sorry, cant find that', 404);513 res.send('text', { 'Content-Type': 'text/plain' }, 201);514 res.send(404);515</code></pre>516517<p>By default the <em>Content-Type</em> response header is set, however if explicitly518assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>519it will not be set again.</p>520521<h3 id="Response-redirect-url-status-">Response#redirect(url[, status])</h3>522523<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>524525<pre><code>res.redirect('/', 301);526res.redirect('/account');527res.redirect('http://google.com');528res.redirect('home');529res.redirect('back');530</code></pre>531532<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.533The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes534the "home" setting and defaults to "/".</p>535536<h3 id="Server-redirect-name-val-">Server#redirect(name, val)</h3>537538<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>539540<pre><code>app.redirect('google', 'http://google.com');541</code></pre>542543<p>Now in a route we may call:</p>544545<p>   res.redirect('google');</p>546547<p>We may also map dynamic redirects:</p>548549<pre><code>app.redirect('comments', function(req, res, params){550    return '/post/' + params.id + '/comments';551});552</code></pre>553554<p>So now we may do the following, and the redirect will dynamically adjust to555the context of the request. If we called this route with <em>GET /post/12</em> our556redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>557558<pre><code>app.get('/post/:id', function(req, res){559    res.redirect('comments');560});561</code></pre>562563</div>564			</div>565		</div>566	</body>567</html>