Skip to content
Myr

guide.md

This file

Path

docs/guide.md

676 lines · 19.6 KiB · Markdown

Last changed by

Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c

History of this file

Take it

The walk stopped after 200 commits: lines older than df7582b point at it.

TasksTj Holowaychukbefore adoptiondf7582b

line 1why, one step back
1

Install docsTj Holowaychukbefore adoption63d02f1

lines 2–3why, one step back
2### Installation
3

No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9

line 4why, one step back
4curl:

Updated curl install docsTj Holowaychukbefore adoption3ceb0de

lines 5–7why, one step back
5
6 $ curl -# http://expressjs.com/install.sh | sh7

Install docsTj Holowaychukbefore adoption63d02f1

lines 8–11why, one step back
8npm:
910 $ npm install express11

Updated install docsTj Holowaychukbefore adoption193c4a9

line 12why, one step back
12git clone, first update the submodules:

Install docsTj Holowaychukbefore adoption63d02f1

line 13why, one step back
13

Updated install docsTj Holowaychukbefore adoption193c4a9

line 14why, one step back
14 $ git submodule update --init

Install docsTj Holowaychukbefore adoption63d02f1

line 15why, one step back
15 $ make install

Updated install docsTj Holowaychukbefore adoption193c4a9

line 16why, one step back
16 $ make install-support

Install docsTj Holowaychukbefore adoption63d02f1

line 17why, one step back
17

TasksTj Holowaychukbefore adoptiondf7582b

lines 18–40why, one step back
18### Creating An Application
1920The _express.Server_ now inherits from _http.Server_, however21follows the same idiom by providing _express.createServer()_ as shown below. This means22that you can utilize Express server's transparently with other libraries.2324 var app = require('express').createServer();25 26 app.get('/', function(req, res){27 res.send('hello world');28 });29 30 app.listen(3000);3132### Configuration3334Express supports arbitrary environments, such as _production_ and _development_. Developers35can use the _configure()_ method to setup needs required by the current environment. When36_configure()_ is called without an environment name it will be run in _every_ environment 37prior to the environment specific callback.3839In the example below we only _dumpExceptions_, and respond with exception stack traces40in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

lines 41–42why, one step back
41Note the use of _app.router_, which can (optionally) be used to mount the application routes,
42otherwise the first call to _app.{get,put,del,post}()_ will mount the routes.

TasksTj Holowaychukbefore adoptiondf7582b

lines 43–44why, one step back
43
44 app.configure(function(){

Updated docsTj Holowaychukbefore adoptioncacada8

lines 45–46why, one step back
45 app.use(connect.methodOverride());
46 app.use(connect.bodyDecoder());

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

lines 47–48why, one step back
47 app.use(app.router);
48 app.use(connect.staticProvider(__dirname + '/public'));

TasksTj Holowaychukbefore adoptiondf7582b

lines 49–51why, one step back
49 });
50 51 app.configure('development', function(){

Updated docsTj Holowaychukbefore adoptioncacada8

line 52why, one step back
52 app.use(connect.errorHandler({ dumpExceptions: true, showStack: true }));

TasksTj Holowaychukbefore adoptiondf7582b

lines 53–55why, one step back
53 });
54 55 app.configure('production', function(){

Updated docsTj Holowaychukbefore adoptioncacada8

line 56why, one step back
56 app.use(connect.errorHandler());

TasksTj Holowaychukbefore adoptiondf7582b

lines 57–72why, one step back
57 });
5859For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:6061 app.configure(function(){62 app.set('views', __dirname + '/views');63 app.set('views');64 // => "... views directory ..."65 66 app.enable('some feature');67 // same as app.set('some feature', true);68 69 app.disable('some feature');70 // same as app.set('some feature', false);71 });72

More docsTj Holowaychukbefore adoptionde81ee7

lines 73–77why, one step back
73To alter the environment we can set the _CONNECT_ENV_ environment variable,
74or more specifically _EXPRESS_ENV_, for example:7576 $ EXPRESS_ENV=production node app.js77

TasksTj Holowaychukbefore adoptiondf7582b

lines 78–81why, one step back
78### Settings
7980Express supports the following settings out of the box:81

Updated docsTj Holowaychukbefore adoption4d32762

line 82why, one step back
82 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_

New "home" docsTj Holowaychukbefore adoption1e7a12f

line 83why, one step back
83 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.

TasksTj Holowaychukbefore adoptiondf7582b

lines 84–85why, one step back
84 * _views_ Root views directory defaulting to **CWD/views**
85 * _view engine_ Default view engine name for views rendered without extensions

Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c

line 86why, one step back
86 * _view options_ An object specifying global view options

Merge branch 'integration'Tj Holowaychukbefore adoption3fae10d

line 87why, one step back
87 * _partials_ Root view partials directory defaulting to _views_/partials.

TasksTj Holowaychukbefore adoptiondf7582b

lines 88–92why, one step back
88
89### Routing9091Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.92For example we may want to render a user's account for the path _/user/12_, this

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 93–94why, one step back
93can be done by defining the route below. The values associated to the named placeholders
94are available as `req.params`.

TasksTj Holowaychukbefore adoptiondf7582b

line 95why, one step back
95

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 96–97why, one step back
96 app.get('/user/:id', function(req, res){
97 res.send('user ' + req.params.id);

TasksTj Holowaychukbefore adoptiondf7582b

lines 98–104why, one step back
98 });
99100A route is simple a string which is compiled to a _RegExp_ internally. For example101when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:102103 \/user\/([^\/]+)\/?104

Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b

line 105why, one step back
105Regular expression literals may also be passed for complex uses. Since capture

Updated docsTj Holowaychukbefore adoptiond691ecb

line 106why, one step back
106groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.

TasksTj Holowaychukbefore adoptiondf7582b

line 107why, one step back
107

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 108–109why, one step back
108 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){
109 res.send(req.params);

Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b

lines 110–121why, one step back
110 });
111112Curl requests against the previously defined route:113114 $ curl http://dev:3000/user115 [null,null]116 $ curl http://dev:3000/users117 [null,null]118 $ curl http://dev:3000/users/1119 ["1",null]120 $ curl http://dev:3000/users/1..15121 ["1","15"]

TasksTj Holowaychukbefore adoptiondf7582b

lines 122–155why, one step back
122
123Below are some route examples, and the associated paths that they124may consume:125126 "/user/:id"127 /user/12128129 "/users/:id?"130 /users/5131 /users132133 "/files/*"134 /files/jquery.js135 /files/javascripts/jquery.js136137 "/file/*.*"138 /files/jquery.js139 /files/javascripts/jquery.js140 141 "/user/:id/:operation?"142 /user/1143 /user/1/edit144 145 "/products.:format"146 /products.json147 /products.xml148149 "/products.:format?"150 /products.json151 /products.xml152 /products153154### Passing Route Control155

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 156–158why, one step back
156We may pass control to the next _matching_ route, by calling the _third_ argument,
157the _next()_ function. When a match cannot be made, control is passed back to Connect,158and middleware continue to be invoked.

TasksTj Holowaychukbefore adoptiondf7582b

line 159why, one step back
159

Fixed doc typoTj Holowaychukbefore adoption47ff7d9

line 160why, one step back
160 app.get('/users/:id?', function(req, res, next){

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 161–162why, one step back
161 var id = req.params.id;
162 if (id) {

TasksTj Holowaychukbefore adoptiondf7582b

lines 163–168why, one step back
163 // do something
164 } else {165 next();166 }167 });168

Updated docsTj Holowaychukbefore adoptiond691ecb

line 169why, one step back
169 app.get('/users', function(req, res){

TasksTj Holowaychukbefore adoptiondf7582b

lines 170–185why, one step back
170 // do something else
171 });172173### Middleware174175The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be176passed to _express.createServer()_ as you would with a regular Connect server. For example:177178 var connect = require('connect'),179 express = require('express');180181 var app = express.createServer(182 connect.logger(),183 connect.bodyDecoder()184 );185

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 186–187why, one step back
186Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:
187

Updated docsTj Holowaychukbefore adoptioncacada8

line 188why, one step back
188 app.use(connect.logger({ format: ':method :uri' }));

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 189–234why, one step back
189
190### Error Handling191192Express provides the _app.error()_ method which receives exceptions thrown within a route,193or passed to _next(err)_. Below is an example which serves different pages based on our194ad-hoc _NotFound_ exception:195196 function NotFound(msg){197 this.name = 'NotFound';198 Error.call(this, msg);199 Error.captureStackTrace(this, arguments.callee);200 }201202 sys.inherits(NotFound, Error);203204 app.get('/404', function(req, res){205 throw new NotFound;206 });207208 app.get('/500', function(req, res){209 throw new Error('keyboard cat!');210 });211212We can call _app.error()_ several times as shown below.213Here we check for an instanceof _NotFound_ and show the214404 page, or we pass on to the next error handler.215216 app.error(function(err, req, res, next){217 if (err instanceof NotFound) {218 res.render('404.jade');219 } else {220 next(err);221 }222 });223224Here we assume all errors as 500 for the simplicity of225this demo, however you can choose whatever you like226227 app.error(function(err, req, res){228 res.render('500.jade', {229 locals: {230 error: err231 } 232 });233 });234

More error handling docsTj Holowaychukbefore adoptioncea401c

lines 235–238why, one step back
235Our apps could also utilize the Connect _errorHandler_ middleware
236to report on exceptions. For example if we wish to output exceptions 237in "development" mode to _stderr_ we can use:238

Updated docsTj Holowaychukbefore adoptioncacada8

line 239why, one step back
239 app.use(connect.errorHandler({ dumpExceptions: true }));

More error handling docsTj Holowaychukbefore adoptioncea401c

lines 240–243why, one step back
240
241Also during development we may want fancy html pages to show exceptions242that are passed or thrown, so we can set _showStack_ to true:243

Updated docsTj Holowaychukbefore adoptioncacada8

line 244why, one step back
244 app.use(connect.errorHandler({ showStack: true, dumpExceptions: true }));

More error handling docsTj Holowaychukbefore adoptioncea401c

lines 245–248why, one step back
245
246The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_247is present, which is useful for developing apps that rely heavily on client-side JavaScript.248

Added more view docsTj Holowaychukbefore adoption2f96506

lines 249–266why, one step back
249### View Rendering
250251View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name252of the module that will be required. For example the view _layout.ejs_ will253tell the view system to _require('ejs')_, the module being loaded must (currently)254export the method _exports.render(str, options)_ to comply with Express, however 255with will likely be extensible in the future.256257Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,258and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 259the _body_ local variable in _layout.haml_.260261 app.get('/', function(req, res){262 res.render('index.haml', {263 locals: { title: 'My Site' }264 });265 });266

Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b

lines 267–283why, one step back
267The new _view engine_ setting allows us to specify our default template engine,
268so for example when using [Jade](http://github.com/visionmedia/jade) we could set:269270 app.set('view engine', 'jade');271272Allowing us to render with:273274 res.render('index');275276vs:277278 res.render('index.jade');279280When _view engine_ is set, extensions are entirely optional, however we can still281mix and match template engines:282283 res.render('another-page.ejs');

Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c

lines 284–300why, one step back
284
285Express also provides the _view options_ setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:286287 app.set('view options', {288 layout: false289 });290291Which can then be overridden within the `res.render()` call if need be:292293 res.render('myview.ejs', { layout: true });294295A good example of this is specifying custom _ejs_ opening and closing tags:296297 app.set('view options', {298 open: '{{',299 close: '}}'300 });

Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b

line 301why, one step back
301

Added more view docsTj Holowaychukbefore adoption2f96506

lines 302–319why, one step back
302### View Partials
303304The Express view system has built-in support for partials and collections, which are305sort of "mini" views representing a document fragment. For example rather than iterating306in a view to display comments, we would use a partial with collection support:307308 partial('comment.haml', { collection: comments });309310To make things even less verbose we can assume the extension as _.haml_ when omitted,311however if we wished we could use an ejs partial, within a haml view for example.312313 partial('comment', { collection: comments });314315And once again even further, when rendering a collection we can simply pass316an array, if no other options are desired:317318 partial('comments', comments);319

Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701

lines 320–326why, one step back
320When using the partial collection support a few "magic" variables are provided
321for free:322323 * _firstInCollection_ True if this is the first object324 * _indexInCollection_ Index of the object in the collection325 * _lastInCollection _ True if this is the last object326

Added more view docsTj Holowaychukbefore adoption2f96506

lines 327–334why, one step back
327### Template Engines
328329Below are a few template engines commonly used with Express:330331 * [Jade](http://github.com/visionmedia/jade) haml.js successor332 * [Haml](http://github.com/visionmedia/haml.js) indented templates333 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript334

More docsTj Holowaychukbefore adoptionde81ee7

line 335why, one step back
335### req.header(key[, defaultValue])

More docsTj Holowaychukbefore adoptiondfecbe5

lines 336–342why, one step back
336
337Get the case-insensitive request header _key_, with optional _defaultValue_:338339 req.header('Host');340 req.header('host');341 req.header('Accept', '*/*');342

More docsTj Holowaychukbefore adoptionde81ee7

line 343why, one step back
343### req.accepts(type)

More docsTj Holowaychukbefore adoptiondfecbe5

lines 344–366why, one step back
344
345Check if the _Accept_ header is present, and includes the given _type_.346347When the _Accept_ header is not present _true_ is returned. Otherwise348the given _type_ 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.351352 // Accept: text/html353 req.accepts('html');354 // => true355356 // Accept: text/*; application/json357 req.accepts('html');358 req.accepts('text/html');359 req.accepts('text/plain');360 req.accepts('application/json');361 // => true362363 req.accepts('image/png');364 req.accepts('png');365 // => false366

More docsTj Holowaychukbefore adoptionde81ee7

line 367why, one step back
367### req.param(name)

More docsTj Holowaychukbefore adoptiondfecbe5

lines 368–370why, one step back
368
369Return the value of param _name_ when present.370

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 371–373why, one step back
371 - Checks route placeholders (_req.params_), ex: /user/:id
372 - Checks query string params (_req.query_), ex: ?id=12373 - Checks urlencoded body params (_req.body_), ex: id=12

More docsTj Holowaychukbefore adoptiondfecbe5

lines 374–378why, one step back
374
375To utilize urlencoded request bodies, _req.body_376should be an object. This can be done by using377the _connect.bodyDecoder_ middleware.378

More docsTj Holowaychukbefore adoptionde81ee7

line 379why, one step back
379### req.flash(type[, msg])

More docsTj Holowaychukbefore adoptiondfecbe5

lines 380–396why, one step back
380
381Queue flash _msg_ of the given _type_.382383 req.flash('info', 'email sent');384 req.flash('error', 'email delivery failed');385 req.flash('info', 'email re-sent');386 // => 2387388 req.flash('info');389 // => ['email sent', 'email re-sent']390391 req.flash('info');392 // => []393394 req.flash();395 // => { error: ['email delivery failed'], info: [] }396

More docsTj Holowaychukbefore adoptionde81ee7

line 397why, one step back
397### req.isXMLHttpRequest

More docsTj Holowaychukbefore adoptiondfecbe5

lines 398–404why, one step back
398
399Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header400to see if it was issued by an _XMLHttpRequest_:401402 req.xhr403 req.isXMLHttpRequest404

More docsTj Holowaychukbefore adoptionde81ee7

line 405why, one step back
405### res.header(key[, val])

TasksTj Holowaychukbefore adoptiondf7582b

lines 406–417why, one step back
406
407Get or set the response header _key_.408409 res.header('Content-Length');410 // => undefined411412 res.header('Content-Length', 123);413 // => 123414415 res.header('Content-Length');416 // => 123417

More docsTj Holowaychukbefore adoptionde81ee7

line 418why, one step back
418### res.contentType(type)

TasksTj Holowaychukbefore adoptiondf7582b

lines 419–425why, one step back
419
420Sets the _Content-Type_ response header to the given _type_.421422 var filename = 'path/to/image.png';423 res.contentType(filename);424 // res.headers['Content-Type'] is now "image/png"425

More docsTj Holowaychukbefore adoptionde81ee7

line 426why, one step back
426### res.attachment([filename])

TasksTj Holowaychukbefore adoptiondf7582b

lines 427–431why, one step back
427
428Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.429430 res.attachment('path/to/my/image.png');431

More docsTj Holowaychukbefore adoptionde81ee7

line 432why, one step back
432### res.sendfile(path)

TasksTj Holowaychukbefore adoptiondf7582b

lines 433–437why, one step back
433
434Used by `res.download()` to transfer an arbitrary file. 435436 res.sendfile('path/to/my.file');437

Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1

lines 438–441why, one step back
438This is _not_ a substitution for Connect's _staticProvider_ middleware, it does not
439support HTTP caching, and does not perform any security checks. This method is utilized440by _res.download()_ to transfer static files, and allows you do to so from outside of441the public directory, so suitable security checks should be applied.

TasksTj Holowaychukbefore adoptiondf7582b

line 442why, one step back
442

More docsTj Holowaychukbefore adoptionde81ee7

line 443why, one step back
443### res.download(file[, filename])

TasksTj Holowaychukbefore adoptiondf7582b

lines 444–454why, one step back
444
445Transfer the given _file_ as an attachment with optional alternative _filename_.446447 res.download('path/to/image.png');448 res.download('path/to/image.png', 'foo.png');449450This is equivalent to:451452 res.attachment(file);453 res.sendfile(file);454

More docsTj Holowaychukbefore adoptionde81ee7

line 455why, one step back
455### res.send(body|status[, headers|status[, status]])

TasksTj Holowaychukbefore adoptiondf7582b

lines 456–471why, one step back
456
457The `res.send()` method is a high level response utility allowing you to pass458objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status459code based responses. The following are all valid uses:460461 res.send(new Buffer('wahoo'));462 res.send({ some: 'json' });463 res.send('<p>some html</p>');464 res.send('Sorry, cant find that', 404);465 res.send('text', { 'Content-Type': 'text/plain' }, 201);466 res.send(404);467468By default the _Content-Type_ response header is set, however if explicitly469assigned through `res.send()` or previously with `res.header()` or `res.contentType()`470it will not be set again.471

More docsTj Holowaychukbefore adoptionde81ee7

line 472why, one step back
472### res.redirect(url[, status])

TasksTj Holowaychukbefore adoptiondf7582b

lines 473–485why, one step back
473
474Redirect to the given _url_ with a default response _status_ of 302.475476 res.redirect('/', 301);477 res.redirect('/account');478 res.redirect('http://google.com');479 res.redirect('home');480 res.redirect('back');481482Express supports "redirect mapping", which by default provides _home_, and _back_.483The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes484the "home" setting and defaults to "/".485

More view docsTj Holowaychukbefore adoption1c8ff48

lines 486–498why, one step back
486### res.render(view[, options[, fn]])
487488Render _view_ with the given _options_ and optional callback _fn_.489When a callback function is given a response will _not_ be made490automatically, however otherwise a response of _200_ and _text/html_ is given.491492 Most engines accept one or more of the following options,493 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:494495 - _context|scope_ Template evaluation context (_this_)496 - _locals_ Object containing local variables497 - _debug_ Output debugging information498

In depth partial docsTj Holowaychukbefore adoption793943f

lines 499–536why, one step back
499### res.partial(view[, options])
500501Render _view_ partial with the given _options_. This method is always available502to the view as a local variable.503504- _as_ Variable name for each _collection_ value, defaults to the view name.505 * as: 'something' will add the _something_ local variable506 * as: this will use the collection value as the template context507 * as: global will merge the collection value's properties with _locals_508509- _collection_ Array of objects, the name is derived from the view name itself. 510 For example _video.html_ will have a object _video_ available to it.511512The following are equivalent, and the name of collection value when passed513to the partial will be _movie_ as derived from the name.514515 partial('movie.jade', { collection: movies });516 partial('movie.jade', movies);517 partial('movie', movies);518 // In view: movie.director519520To change the local from _movie_ to _video_ we can use the "as" option:521522 partial('movie', { collection: movies, as: 'video' });523 // In view: video.director524525Also we can make our movie the value of _this_ within our view so that instead526of _movie.director_ we could use _this.director_.527528 partial('movie', { collection: movies, as: this });529 // In view: this.director530531Another alternative is to "explode" the properties of the collection item into532pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:533534 partials('movie', { collection: movies, as: global });535 // In view: director536

More docsTj Holowaychukbefore adoptionde81ee7

lines 537–541why, one step back
537### app.set(name[, val])
538539Apply an application level setting _name_ to _val_, or540get the value of _name_ when _val_ is not present:541

Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110

lines 542–544why, one step back
542 app.set('views', __dirname + '/views');
543 app.set('views');544 // => ...path...

More docsTj Holowaychukbefore adoptionde81ee7

lines 545–574why, one step back
545
546### app.enable(name)547548Enable the given setting _name_:549550 app.enable('some arbitrary setting');551 app.set('some arbitrary setting');552 // => true553554### app.disable(name)555556Disable the given setting _name_:557558 app.disable('some setting');559 app.set('some setting');560 // => false561562### app.configure(env|function[, function])563564Define a callback function for the given _env_ (or all environments) with callback _function_:565566 app.configure(function(){567 // executed for each env568 });569570 app.configure('development', function(){571 // executed for 'development' only572 });573574### app.redirect(name, val)

TasksTj Holowaychukbefore adoptiondf7582b

lines 575–585why, one step back
575
576For use with `res.redirect()` we can map redirects at the application level as shown below:577578 app.redirect('google', 'http://google.com');579580Now in a route we may call:581582 res.redirect('google');583584We may also map dynamic redirects:585

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 586–587why, one step back
586 app.redirect('comments', function(req, res){
587 return '/post/' + req.params.id + '/comments';

TasksTj Holowaychukbefore adoptiondf7582b

lines 588–596why, one step back
588 });
589590So now we may do the following, and the redirect will dynamically adjust to591the context of the request. If we called this route with _GET /post/12_ our592redirect _Location_ would be _/post/12/comments_.593594 app.get('/post/:id', function(req, res){595 res.redirect('comments');596 });

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 597–599why, one step back
597
598### app.error(function)599

More error docsTj Holowaychukbefore adoption6227f5c

lines 600–602why, one step back
600Adds an error handler _function_ which will receive the exception as the first parameter as shown below.
601Note that we may set several error handlers by making several calls to this method, however the handler602should call _next(err)_ if it does not wish to deal with the exception:

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 603–606why, one step back
603
604 app.error(function(err, req, res, next){605 res.send(err.message, 500);606 });

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 607–609why, one step back
607
608### app.helpers(obj)609

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

lines 610–625why, one step back
610Registers static view helpers.
611612 app.helpers({613 name: function(first, last){ return first + ', ' + last },614 firstName: 'tj',615 lastName: 'holowaychuk'616 });617618Our view could now utilize the _firstName_ and _lastName_ variables,619as well as the _name()_ function exposed.620621 <%= name(firstName, lastName) %>622623### app.dynamicHelpers(obj)624625Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

line 626why, one step back
626are simply functions which accept _req_, _res_, and are

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

line 627why, one step back
627evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 628–629why, one step back
628becomes the local variable it is associated with.
629

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

line 630why, one step back
630 app.dynamicHelpers({

Updated docsTj Holowaychukbefore adoptiond691ecb

line 631why, one step back
631 session: function(req, res){

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 632–635why, one step back
632 return req.session;
633 }634 });635

Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1

lines 636–638why, one step back
636All views would now have _session_ available so that session data can be accessed via _session.name_ etc:
637638 <%= session.name %>

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 639–652why, one step back
639
640### app.mounted(fn)641642Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.643644 var app = express.createServer(),645 blog = express.createServer();646 647 blog.mounted(function(parent){648 // parent is app649 // "this" is blog650 });651 652 app.use(blog);

Server#listen() docsTj Holowaychukbefore adoptionf3803c4

lines 653–661why, one step back
653
654### app.listen([port[, host]])655656Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all657connections will be accepted via _INADDR_ANY_.658659 app.listen();660 app.listen(3000);661 app.listen(3000, 'n.n.n.n');

Unix domain socket docsTj Holowaychukbefore adoption2fa7907

lines 662–676why, one step back
662
663The _port_ argument may also be a string representing the path to a unix domain socket:664665 app.listen('/tmp/express.sock');666667Then try it out:668669 $ telnet /tmp/express.sock670 GET / HTTP/1.1671672 HTTP/1.1 200 OK673 Content-Type: text/plain674 Content-Length: 11675 676 Hello World