Skip to content
Myr

guide.html

This file

Path

docs/guide.html

806 lines · 24.8 KiB · HTML

Last changed by

More view docsTj Holowaychukbefore adoption1c8ff48

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: 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="#Error-Handling">Error Handling</a></li>177<li><a href="#View-Rendering">View Rendering</a></li>178<li><a href="#View-Partials">View Partials</a></li>179<li><a href="#Template-Engines">Template Engines</a></li>180<li><a href="#req-header-key-defaultValue-">req.header()</a></li>181<li><a href="#req-accepts-type-">req.accepts()</a></li>182<li><a href="#req-param-name-">req.param()</a></li>183<li><a href="#req-flash-type-msg-">req.flash()</a></li>184<li><a href="#req-isXMLHttpRequest">req.isXMLHttpRequest</a></li>185<li><a href="#res-header-key-val-">res.header()</a></li>186<li><a href="#res-contentType-type-">res.contentType()</a></li>187<li><a href="#res-attachment-filename-">res.attachment()</a></li>188<li><a href="#res-sendfile-path-">res.sendfile()</a></li>189<li><a href="#res-download-file-filename-">res.download()</a></li>190<li><a href="#res-send-body-status-headers-status-status-">res.send()</a></li>191<li><a href="#res-redirect-url-status-">res.redirect()</a></li>192<li><a href="#res-render-view-options-fn-">res.render()</a></li>193<li><a href="#app-set-name-val-">app.set()</a></li>194<li><a href="#app-enable-name-">app.enable()</a></li>195<li><a href="#app-disable-name-">app.disable()</a></li>196<li><a href="#app-configure-env-function-function-">app.configure()</a></li>197<li><a href="#app-redirect-name-val-">app.redirect()</a></li>198<li><a href="#app-error-function-">app.error()</a></li>199<li><a href="#app-listen-port-host-">app.listen()</a></li>200</ul>201				<a href='http://github.com/visionmedia/express' id='logo'>Express</a> 202				<p id="tagline">203				   High performance, high class web development for204				  <a href="http://nodejs.org">Node.js</a>205				</p>206				<ul id="menu">207					<li><a href="index.html">Home</a></li>208					<li><a href="guide.html">Guide</a></li>209					<li><a href="contrib.html">Contributing</a></li>210					<li><a href="migrate.html">1.x Migration</a></li>211				</ul>212<div class='mp'>213<h3 id="Installation">Installation</h3>214215<p>npm:</p>216217<pre><code>$ npm install connect218$ npm install express219</code></pre>220221<p>curl (or similar):</p>222223<pre><code>$ curl -# http://github.com/visionmedia/express/raw/master/install.sh | sh224</code></pre>225226<p>git clone, first update the submodules:</p>227228<pre><code>$ git submodule update --init229$ make install230$ make install-support231</code></pre>232233<h3 id="Creating-An-Application">Creating An Application</h3>234235<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however236follows the same idiom by providing <em>express.createServer()</em> as shown below. This means237that you can utilize Express server's transparently with other libraries.</p>238239<pre><code>var app = require('express').createServer();240241app.get('/', function(req, res){242    res.send('hello world');243});244245app.listen(3000);246</code></pre>247248<h3 id="Configuration">Configuration</h3>249250<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers251can use the <em>configure()</em> method to setup needs required by the current environment. When252<em>configure()</em> is called without an environment name it will be run in <em>every</em> environment253prior to the environment specific callback.</p>254255<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces256in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.</p>257258<pre><code>app.configure(function(){259    app.use('/', connect.methodOverride());260    app.use('/', connect.bodyDecoder());261});262263app.configure('development', function(){264    app.use('/', connect.errorHandler({ dumpExceptions: true, showStack: true }));265});266267app.configure('production', function(){268    app.use('/', connect.errorHandler());269});270</code></pre>271272<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>273274<pre><code>app.configure(function(){275    app.set('views', __dirname + '/views');276    app.set('views');277    // =&gt; "... views directory ..."278279    app.enable('some feature');280    // same as app.set('some feature', true);281282    app.disable('some feature');283    // same as app.set('some feature', false);284});285</code></pre>286287<p>To alter the environment we can set the <em>CONNECT_ENV</em> environment variable,288or more specifically <em>EXPRESS_ENV</em>, for example:</p>289290<pre><code>$ EXPRESS_ENV=production node app.js291</code></pre>292293<h3 id="Settings">Settings</h3>294295<p>Express supports the following settings out of the box:</p>296297<ul>298<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> to utilize</li>299<li><em>home</em> Application base path used with <em>res.redirect()</em></li>300<li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>301<li><em>view engine</em> Default view engine name for views rendered without extensions</li>302<li><em>reload views</em> Reloads altered views, by default watches for <em>mtime</em> changes with303  with a 5 minute interval. Example: <em>app.set('reload views', 60000);</em></li>304</ul>305306307<h3 id="Routing">Routing</h3>308309<p>Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.310For example we may want to render a user's account for the path <em>/user/12</em>, this311can be done by defining the route below. The values associated to the named placeholders,312are passed as the <em>third</em> argument, which here we name <em>params</em>.</p>313314<pre><code>app.get('/user/:id', function(req, res, params){315    res.send('user ' + params.id);316});317</code></pre>318319<p>A route is simple a string which is compiled to a <em>RegExp</em> internally. For example320when <em>/user/:id</em> is compiled, a simplified version of the regexp may look similar to:</p>321322<pre><code>\/user\/([^\/]+)\/?323</code></pre>324325<p>Literal regular expressions may also be passed for complex uses:</p>326327<pre><code>app.get(/^\/foo(bar)?$/, function(){});328</code></pre>329330<p>Below are some route examples, and the associated paths that they331may consume:</p>332333<pre><code> "/user/:id"334 /user/12335336 "/users/:id?"337 /users/5338 /users339340 "/files/*"341 /files/jquery.js342 /files/javascripts/jquery.js343344 "/file/*.*"345 /files/jquery.js346 /files/javascripts/jquery.js347348 "/user/:id/:operation?"349 /user/1350 /user/1/edit351352 "/products.:format"353 /products.json354 /products.xml355356 "/products.:format?"357 /products.json358 /products.xml359 /products360</code></pre>361362<h3 id="Passing-Route-Control">Passing Route Control</h3>363364<p>We may pass control to the next <em>matching</em> route, by calling the <em>fourth</em> parameter,365the <em>next()</em> function. When a match cannot be made, control is passed back to Connect.</p>366367<pre><code>app.get('/users/:id?', function(req, res, params){368    if (params.id) {369        // do something370    } else {371        next();372    }373});374375app.get('/users', function(req, res, params){376    // do something else377});378</code></pre>379380<h3 id="Middleware">Middleware</h3>381382<p>The Express <em>Plugin</em> is no more! middleware via <a href="http://github.com/extjs/Connect">Connect</a> can be383passed to <em>express.createServer()</em> as you would with a regular Connect server. For example:</p>384385<pre><code>var connect = require('connect'),386    express = require('express');387388var app = express.createServer(389    connect.logger(),390    connect.bodyDecoder()391);392</code></pre>393394<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>395396<pre><code>app.use('/', connect.logger({ format: ':method :uri' }));397</code></pre>398399<h3 id="Error-Handling">Error Handling</h3>400401<p>Express provides the <em>app.error()</em> method which receives exceptions thrown within a route,402or passed to <em>next(err)</em>. Below is an example which serves different pages based on our403ad-hoc <em>NotFound</em> exception:</p>404405<pre><code>function NotFound(msg){406    this.name = 'NotFound';407    Error.call(this, msg);408    Error.captureStackTrace(this, arguments.callee);409}410411sys.inherits(NotFound, Error);412413app.get('/404', function(req, res){414    throw new NotFound;415});416417app.get('/500', function(req, res){418    throw new Error('keyboard cat!');419});420</code></pre>421422<p>We can call <em>app.error()</em> several times as shown below.423Here we check for an instanceof <em>NotFound</em> and show the424404 page, or we pass on to the next error handler.</p>425426<pre><code>app.error(function(err, req, res, next){427    if (err instanceof NotFound) {428        res.render('404.jade');429    } else {430        next(err);431    }432});433</code></pre>434435<p>Here we assume all errors as 500 for the simplicity of436this demo, however you can choose whatever you like</p>437438<pre><code>app.error(function(err, req, res){439    res.render('500.jade', {440       locals: {441           error: err442       } 443    });444});445</code></pre>446447<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware448to report on exceptions. For example if we wish to output exceptions449in "development" mode to <em>stderr</em> we can use:</p>450451<pre><code>app.use('/', connect.errorHandler({ dumpExceptions: true }));452</code></pre>453454<p>Also during development we may want fancy html pages to show exceptions455that are passed or thrown, so we can set <em>showStack</em> to true:</p>456457<pre><code>app.use('/', connect.errorHandler({ showStack: true, dumpExceptions: true }));458</code></pre>459460<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>461is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>462463<h3 id="View-Rendering">View Rendering</h3>464465<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name466of the module that will be required. For example the view <em>layout.ejs</em> will467tell the view system to <em>require('ejs')</em>, the module being loaded must (currently)468export the method <em>exports.render(str, options)</em> to comply with Express, however469with will likely be extensible in the future.</p>470471<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,472and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as473the <em>body</em> local variable in <em>layout.haml</em>.</p>474475<pre><code>app.get('/', function(req, res){476    res.render('index.haml', {477        locals: { title: 'My Site' }478    });479});480</code></pre>481482<h3 id="View-Partials">View Partials</h3>483484<p>The Express view system has built-in support for partials and collections, which are485sort of "mini" views representing a document fragment. For example rather than iterating486in a view to display comments, we would use a partial with collection support:</p>487488<pre><code>partial('comment.haml', { collection: comments });489</code></pre>490491<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,492however if we wished we could use an ejs partial, within a haml view for example.</p>493494<pre><code>partial('comment', { collection: comments });495</code></pre>496497<p>And once again even further, when rendering a collection we can simply pass498an array, if no other options are desired:</p>499500<pre><code>partial('comments', comments);501</code></pre>502503<h3 id="Template-Engines">Template Engines</h3>504505<p>Below are a few template engines commonly used with Express:</p>506507<ul>508<li><a href="http://github.com/visionmedia/jade">Jade</a> haml.js successor</li>509<li><a href="http://github.com/visionmedia/haml.js">Haml</a> indented templates</li>510<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>511</ul>512513514<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>515516<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>517518<pre><code>req.header('Host');519req.header('host');520req.header('Accept', '*/*');521</code></pre>522523<h3 id="req-accepts-type-">req.accepts(type)</h3>524525<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>526527<p>When the <em>Accept</em> header is not present <em>true</em> is returned. Otherwise528the given <em>type</em> is matched by an exact match, and then subtypes. You529may pass the subtype such as "html" which is then converted internally530to "text/html" using the mime lookup table.</p>531532<pre><code>// Accept: text/html533req.accepts('html');534// =&gt; true535536// Accept: text/*; application/json537req.accepts('html');538req.accepts('text/html');539req.accepts('text/plain');540req.accepts('application/json');541// =&gt; true542543req.accepts('image/png');544req.accepts('png');545// =&gt; false546</code></pre>547548<h3 id="req-param-name-">req.param(name)</h3>549550<p>Return the value of param <em>name</em> when present.</p>551552<ul>553<li>Checks route placeholders, ex: /user/:id</li>554<li>Checks query string params, ex: ?id=12</li>555<li>Checks urlencoded body params, ex: id=12</li>556</ul>557558559<p>To utilize urlencoded request bodies, <em>req.body</em>560should be an object. This can be done by using561the <em>connect.bodyDecoder</em> middleware.</p>562563<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>564565<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>566567<pre><code>req.flash('info', 'email sent');568req.flash('error', 'email delivery failed');569req.flash('info', 'email re-sent');570// =&gt; 2571572req.flash('info');573// =&gt; ['email sent', 'email re-sent']574575req.flash('info');576// =&gt; []577578req.flash();579// =&gt; { error: ['email delivery failed'], info: [] }580</code></pre>581582<h3 id="req-isXMLHttpRequest">req.isXMLHttpRequest</h3>583584<p>Also aliased as <em>req.xhr</em>, this getter checks the <em>X-Requested-With</em> header585to see if it was issued by an <em>XMLHttpRequest</em>:</p>586587<pre><code>req.xhr588req.isXMLHttpRequest589</code></pre>590591<h3 id="res-header-key-val-">res.header(key[, val])</h3>592593<p>Get or set the response header <em>key</em>.</p>594595<pre><code>res.header('Content-Length');596// =&gt; undefined597598res.header('Content-Length', 123);599// =&gt; 123600601res.header('Content-Length');602// =&gt; 123603</code></pre>604605<h3 id="res-contentType-type-">res.contentType(type)</h3>606607<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>608609<pre><code>  var filename = 'path/to/image.png';610  res.contentType(filename);611  // res.headers['Content-Type'] is now "image/png"612</code></pre>613614<h3 id="res-attachment-filename-">res.attachment([filename])</h3>615616<p>Sets the <em>Content-Disposition</em> response header to "attachment", with optional <em>filename</em>.</p>617618<pre><code>  res.attachment('path/to/my/image.png');619</code></pre>620621<h3 id="res-sendfile-path-">res.sendfile(path)</h3>622623<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>624625<pre><code>res.sendfile('path/to/my.file');626</code></pre>627628<p><strong>NOTE</strong>: this is <em>not</em> a replacement for Connect's <em>staticProvider</em> middleware,629nor does it perform any security checks, use with caution when using in a dynamic manner.</p>630631<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>632633<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>634635<pre><code>res.download('path/to/image.png');636res.download('path/to/image.png', 'foo.png');637</code></pre>638639<p>This is equivalent to:</p>640641<pre><code>res.attachment(file);642res.sendfile(file);643</code></pre>644645<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>646647<p>The <code>res.send()</code> method is a high level response utility allowing you to pass648objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status649code based responses. The following are all valid uses:</p>650651<pre><code> res.send(new Buffer('wahoo'));652 res.send({ some: 'json' });653 res.send('&lt;p&gt;some html&lt;/p&gt;');654 res.send('Sorry, cant find that', 404);655 res.send('text', { 'Content-Type': 'text/plain' }, 201);656 res.send(404);657</code></pre>658659<p>By default the <em>Content-Type</em> response header is set, however if explicitly660assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>661it will not be set again.</p>662663<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>664665<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>666667<pre><code>res.redirect('/', 301);668res.redirect('/account');669res.redirect('http://google.com');670res.redirect('home');671res.redirect('back');672</code></pre>673674<p>Express supports "redirect mapping", which by default provides <em>home</em>, and <em>back</em>.675The <em>back</em> map checks the <em>Referrer</em> and <em>Referer</em> headers, while <em>home</em> utilizes676the "home" setting and defaults to "/".</p>677678<h3 id="res-render-view-options-fn-">res.render(view[, options[, fn]])</h3>679680<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.681When a callback function is given a response will <em>not</em> be made682automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>683684<p> Most engines accept one or more of the following options,685 both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>686687<ul>688<li><em>context|scope</em>   Template evaluation context (<em>this</em>)</li>689<li><em>locals</em>          Object containing local variables</li>690<li><em>filename</em>        Filename used for the <em>cache</em> option</li>691<li><em>cache</em>           Cache intermediate JavaScript in memory</li>692<li><em>debug</em>           Output debugging information</li>693</ul>694695696<h3 id="app-set-name-val-">app.set(name[, val])</h3>697698<p>Apply an application level setting <em>name</em> to <em>val</em>, or699get the value of <em>name</em> when <em>val</em> is not present:</p>700701<pre><code>app.set('reload views', 200);702app.set('reload views');703// =&gt; 200704</code></pre>705706<h3 id="app-enable-name-">app.enable(name)</h3>707708<p>Enable the given setting <em>name</em>:</p>709710<pre><code>app.enable('some arbitrary setting');711app.set('some arbitrary setting');712// =&gt; true713</code></pre>714715<h3 id="app-disable-name-">app.disable(name)</h3>716717<p>Disable the given setting <em>name</em>:</p>718719<pre><code>app.disable('some setting');720app.set('some setting');721// =&gt; false722</code></pre>723724<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>725726<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>727728<pre><code>app.configure(function(){729    // executed for each env730});731732app.configure('development', function(){733    // executed for 'development' only734});735</code></pre>736737<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>738739<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>740741<pre><code>app.redirect('google', 'http://google.com');742</code></pre>743744<p>Now in a route we may call:</p>745746<p>   res.redirect('google');</p>747748<p>We may also map dynamic redirects:</p>749750<pre><code>app.redirect('comments', function(req, res, params){751    return '/post/' + params.id + '/comments';752});753</code></pre>754755<p>So now we may do the following, and the redirect will dynamically adjust to756the context of the request. If we called this route with <em>GET /post/12</em> our757redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>758759<pre><code>app.get('/post/:id', function(req, res){760    res.redirect('comments');761});762</code></pre>763764<h3 id="app-error-function-">app.error(function)</h3>765766<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.767Note that we may set several error handlers by making several calls to this method, however the handler768should call <em>next(err)</em> if it does not wish to deal with the exception:</p>769770<pre><code>app.error(function(err, req, res, next){771    res.send(err.message, 500);772});773</code></pre>774775<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>776777<p>Bind the app server to the given <em>port</em>, which defaults to 3000. When <em>host</em> is omitted all778connections will be accepted via <em>INADDR_ANY</em>.</p>779780<pre><code>app.listen();781app.listen(3000);782app.listen(3000, 'n.n.n.n');783</code></pre>784785<p>The <em>port</em> argument may also be a string representing the path to a unix domain socket:</p>786787<pre><code>app.listen('/tmp/express.sock');788</code></pre>789790<p>Then try it out:</p>791792<pre><code>$ telnet /tmp/express.sock793GET / HTTP/1.1794795HTTP/1.1 200 OK796Content-Type: text/plain797Content-Length: 11798799Hello World800</code></pre>801802</div>803			</div>804		</div>805	</body>806</html>