Skip to content
Myr

guide.md

This file

Path

docs/guide.md

659 lines · 19.2 KiB · Markdown

Last changed by

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

History of this file

Take it

Started guideTj Holowaychukbefore adoption9e3a0c6

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–9why, one step back
8npm:
9

Updated install docsTj Holowaychukbefore adoption193c4a9

line 10why, one step back
10 $ npm install connect

Install docsTj Holowaychukbefore adoption63d02f1

lines 11–12why, one step back
11 $ npm install express
12

Updated install docsTj Holowaychukbefore adoption193c4a9

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

Install docsTj Holowaychukbefore adoption63d02f1

line 14why, one step back
14

Updated install docsTj Holowaychukbefore adoption193c4a9

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

Install docsTj Holowaychukbefore adoption63d02f1

line 16why, one step back
16 $ make install

Updated install docsTj Holowaychukbefore adoption193c4a9

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

Install docsTj Holowaychukbefore adoption63d02f1

line 18why, one step back
18

Removed annoying padding transitionTj Holowaychukbefore adoption346b2a2

line 19why, one step back
19### Creating An Application

Added configuration sectionTj Holowaychukbefore adoption83d2555

lines 20–21why, one step back
20
21The _express.Server_ now inherits from _http.Server_, however

Moved config docs upTj Holowaychukbefore adoption6e8413f

lines 22–23why, one step back
22follows the same idiom by providing _express.createServer()_ as shown below. This means
23that you can utilize Express server's transparently with other libraries.

Added configuration sectionTj Holowaychukbefore adoption83d2555

lines 24–32why, one step back
24
25 var app = require('express').createServer();26 27 app.get('/', function(req, res){28 res.send('hello world');29 });30 31 app.listen(3000);32

Moved config docs upTj Holowaychukbefore adoption6e8413f

lines 33–41why, one step back
33### Configuration
3435Express supports arbitrary environments, such as _production_ and _development_. Developers36can use the _configure()_ method to setup needs required by the current environment. When37_configure()_ is called without an environment name it will be run in _every_ environment 38prior to the environment specific callback.3940In the example below we only _dumpExceptions_, and respond with exception stack traces41in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Moved config docs upTj Holowaychukbefore adoption6e8413f

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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

Moved config docs upTj Holowaychukbefore adoption6e8413f

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

Moved config docs upTj Holowaychukbefore adoption6e8413f

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

Moved config docs upTj Holowaychukbefore adoption6e8413f

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

More docsTj Holowaychukbefore adoptionde81ee7

lines 74–78why, one step back
74To alter the environment we can set the _CONNECT_ENV_ environment variable,
75or more specifically _EXPRESS_ENV_, for example:7677 $ EXPRESS_ENV=production node app.js78

Moved config docs upTj Holowaychukbefore adoption6e8413f

lines 79–82why, one step back
79### Settings
8081Express supports the following settings out of the box:82

Updated docsTj Holowaychukbefore adoption4d32762

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

New "home" docsTj Holowaychukbefore adoption1e7a12f

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

Moved config docs upTj Holowaychukbefore adoption6e8413f

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

Added more setting docsTj Holowaychukbefore adoption38281e6

line 87why, one step back
87 * _reload views_ Reloads altered views, by default watches for _mtime_ changes with

Fixed reload views exampleTj Holowaychukbefore adoption5fcf971

line 88why, one step back
88 with a 5 minute interval. Example: _app.set('reload views', 60000);_

Moved config docs upTj Holowaychukbefore adoption6e8413f

line 89why, one step back
89

Started guideTj Holowaychukbefore adoption9e3a0c6

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

Route passing docsTj Holowaychukbefore adoption0ace97c

lines 94–95why, one step back
94can be done by defining the route below. The values associated to the named placeholders,
95are passed as the _third_ argument, which here we name _params_.

Started guideTj Holowaychukbefore adoption9e3a0c6

lines 96–105why, one step back
96
97 app.get('/user/:id', function(req, res, params){98 res.send('user ' + params.id);99 });100101A route is simple a string which is compiled to a _RegExp_ internally. For example102when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:103104 \/user\/([^\/]+)\/?105

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

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

Updated docsTj Holowaychukbefore adoption0111582

line 107why, one step back
107groups with literal _RegExp_'s are anonymous we can access them directly from the _params_ array.

Started guideTj Holowaychukbefore adoption9e3a0c6

line 108why, one step back
108

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

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

Updated docsTj Holowaychukbefore adoption0111582

line 110why, one step back
110 res.send(params);

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

lines 111–122why, one step back
111 });
112113Curl requests against the previously defined route:114115 $ curl http://dev:3000/user116 [null,null]117 $ curl http://dev:3000/users118 [null,null]119 $ curl http://dev:3000/users/1120 ["1",null]121 $ curl http://dev:3000/users/1..15122 ["1","15"]

Started guideTj Holowaychukbefore adoption9e3a0c6

lines 123–153why, one step back
123
124Below are some route examples, and the associated paths that they125may consume:126127 "/user/:id"128 /user/12129130 "/users/:id?"131 /users/5132 /users133134 "/files/*"135 /files/jquery.js136 /files/javascripts/jquery.js137138 "/file/*.*"139 /files/jquery.js140 /files/javascripts/jquery.js141 142 "/user/:id/:operation?"143 /user/1144 /user/1/edit145 146 "/products.:format"147 /products.json148 /products.xml149150 "/products.:format?"151 /products.json152 /products.xml153 /products

Route passing docsTj Holowaychukbefore adoption0ace97c

lines 154–169why, one step back
154
155### Passing Route Control156157We may pass control to the next _matching_ route, by calling the _fourth_ parameter,158the _next()_ function. When a match cannot be made, control is passed back to Connect.159160 app.get('/users/:id?', function(req, res, params){161 if (params.id) {162 // do something163 } else {164 next();165 }166 });167 168 app.get('/users', function(req, res, params){169 // do something else

Added configuration sectionTj Holowaychukbefore adoption83d2555

lines 170–184why, one step back
170 });
171172### Middleware173174The Express _Plugin_ is no more! middleware via [Connect](http://github.com/extjs/Connect) can be175passed to _express.createServer()_ as you would with a regular Connect server. For example:176177 var connect = require('connect'),178 express = require('express');179180 var app = express.createServer(181 connect.logger(),182 connect.bodyDecoder()183 );184

Error handling docsTj Holowaychukbefore adoption9fbb9fa

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 188–233why, one step back
188
189### Error Handling190191Express provides the _app.error()_ method which receives exceptions thrown within a route,192or passed to _next(err)_. Below is an example which serves different pages based on our193ad-hoc _NotFound_ exception:194195 function NotFound(msg){196 this.name = 'NotFound';197 Error.call(this, msg);198 Error.captureStackTrace(this, arguments.callee);199 }200201 sys.inherits(NotFound, Error);202203 app.get('/404', function(req, res){204 throw new NotFound;205 });206207 app.get('/500', function(req, res){208 throw new Error('keyboard cat!');209 });210211We can call _app.error()_ several times as shown below.212Here we check for an instanceof _NotFound_ and show the213404 page, or we pass on to the next error handler.214215 app.error(function(err, req, res, next){216 if (err instanceof NotFound) {217 res.render('404.jade');218 } else {219 next(err);220 }221 });222223Here we assume all errors as 500 for the simplicity of224this demo, however you can choose whatever you like225226 app.error(function(err, req, res){227 res.render('500.jade', {228 locals: {229 error: err230 } 231 });232 });233

More error handling docsTj Holowaychukbefore adoptioncea401c

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

More error handling docsTj Holowaychukbefore adoptioncea401c

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

Updated docsTj Holowaychukbefore adoptioncacada8

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

More error handling docsTj Holowaychukbefore adoptioncea401c

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

Added more view docsTj Holowaychukbefore adoption2f96506

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

Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b

lines 266–283why, one step back
266The new _view engine_ setting allows us to specify our default template engine,
267so for example when using [Jade](http://github.com/visionmedia/jade) we could set:268269 app.set('view engine', 'jade');270271Allowing us to render with:272273 res.render('index');274275vs:276277 res.render('index.jade');278279When _view engine_ is set, extensions are entirely optional, however we can still280mix and match template engines:281282 res.render('another-page.ejs');283

Added more view docsTj Holowaychukbefore adoption2f96506

lines 284–301why, one step back
284### View Partials
285286The Express view system has built-in support for partials and collections, which are287sort of "mini" views representing a document fragment. For example rather than iterating288in a view to display comments, we would use a partial with collection support:289290 partial('comment.haml', { collection: comments });291292To make things even less verbose we can assume the extension as _.haml_ when omitted,293however if we wished we could use an ejs partial, within a haml view for example.294295 partial('comment', { collection: comments });296297And once again even further, when rendering a collection we can simply pass298an array, if no other options are desired:299300 partial('comments', comments);301

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

lines 302–308why, one step back
302When using the partial collection support a few "magic" variables are provided
303for free:304305 * _firstInCollection_ True if this is the first object306 * _indexInCollection_ Index of the object in the collection307 * _lastInCollection _ True if this is the last object308

Added more view docsTj Holowaychukbefore adoption2f96506

lines 309–316why, one step back
309### Template Engines
310311Below are a few template engines commonly used with Express:312313 * [Jade](http://github.com/visionmedia/jade) haml.js successor314 * [Haml](http://github.com/visionmedia/haml.js) indented templates315 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript316

More docsTj Holowaychukbefore adoptionde81ee7

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

More docsTj Holowaychukbefore adoptiondfecbe5

lines 318–324why, one step back
318
319Get the case-insensitive request header _key_, with optional _defaultValue_:320321 req.header('Host');322 req.header('host');323 req.header('Accept', '*/*');324

More docsTj Holowaychukbefore adoptionde81ee7

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

More docsTj Holowaychukbefore adoptiondfecbe5

lines 326–348why, one step back
326
327Check if the _Accept_ header is present, and includes the given _type_.328329When the _Accept_ header is not present _true_ is returned. Otherwise330the given _type_ is matched by an exact match, and then subtypes. You331may pass the subtype such as "html" which is then converted internally332to "text/html" using the mime lookup table.333334 // Accept: text/html335 req.accepts('html');336 // => true337338 // Accept: text/*; application/json339 req.accepts('html');340 req.accepts('text/html');341 req.accepts('text/plain');342 req.accepts('application/json');343 // => true344345 req.accepts('image/png');346 req.accepts('png');347 // => false348

More docsTj Holowaychukbefore adoptionde81ee7

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

More docsTj Holowaychukbefore adoptiondfecbe5

lines 350–360why, one step back
350
351Return the value of param _name_ when present.352353 - Checks route placeholders, ex: /user/:id354 - Checks query string params, ex: ?id=12355 - Checks urlencoded body params, ex: id=12356357To utilize urlencoded request bodies, _req.body_358should be an object. This can be done by using359the _connect.bodyDecoder_ middleware.360

More docsTj Holowaychukbefore adoptionde81ee7

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

More docsTj Holowaychukbefore adoptiondfecbe5

lines 362–378why, one step back
362
363Queue flash _msg_ of the given _type_.364365 req.flash('info', 'email sent');366 req.flash('error', 'email delivery failed');367 req.flash('info', 'email re-sent');368 // => 2369370 req.flash('info');371 // => ['email sent', 'email re-sent']372373 req.flash('info');374 // => []375376 req.flash();377 // => { error: ['email delivery failed'], info: [] }378

More docsTj Holowaychukbefore adoptionde81ee7

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

More docsTj Holowaychukbefore adoptiondfecbe5

lines 380–386why, one step back
380
381Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header382to see if it was issued by an _XMLHttpRequest_:383384 req.xhr385 req.isXMLHttpRequest386

More docsTj Holowaychukbefore adoptionde81ee7

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

More docs :)Tj Holowaychukbefore adoption0c5fe61

lines 388–399why, one step back
388
389Get or set the response header _key_.390391 res.header('Content-Length');392 // => undefined393394 res.header('Content-Length', 123);395 // => 123396397 res.header('Content-Length');398 // => 123399

More docsTj Holowaychukbefore adoptionde81ee7

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

More docs :)Tj Holowaychukbefore adoption0c5fe61

lines 401–407why, one step back
401
402Sets the _Content-Type_ response header to the given _type_.403404 var filename = 'path/to/image.png';405 res.contentType(filename);406 // res.headers['Content-Type'] is now "image/png"407

More docsTj Holowaychukbefore adoptionde81ee7

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

Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1

lines 409–413why, one step back
409
410Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.411412 res.attachment('path/to/my/image.png');413

More docsTj Holowaychukbefore adoptionde81ee7

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

Docs for new res methodsTj Holowaychukbefore adoptionb08dab9

lines 415–419why, one step back
415
416Used by `res.download()` to transfer an arbitrary file. 417418 res.sendfile('path/to/my.file');419

Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1

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

Docs for new res methodsTj Holowaychukbefore adoptionb08dab9

line 424why, one step back
424

More docsTj Holowaychukbefore adoptionde81ee7

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

Docs for new res methodsTj Holowaychukbefore adoptionb08dab9

lines 426–436why, one step back
426
427Transfer the given _file_ as an attachment with optional alternative _filename_.428429 res.download('path/to/image.png');430 res.download('path/to/image.png', 'foo.png');431432This is equivalent to:433434 res.attachment(file);435 res.sendfile(file);436

More docsTj Holowaychukbefore adoptionde81ee7

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

Docs for res.send()Tj Holowaychukbefore adoption5a48248

lines 438–453why, one step back
438
439The `res.send()` method is a high level response utility allowing you to pass440objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status441code based responses. The following are all valid uses:442443 res.send(new Buffer('wahoo'));444 res.send({ some: 'json' });445 res.send('<p>some html</p>');446 res.send('Sorry, cant find that', 404);447 res.send('text', { 'Content-Type': 'text/plain' }, 201);448 res.send(404);449450By default the _Content-Type_ response header is set, however if explicitly451assigned through `res.send()` or previously with `res.header()` or `res.contentType()`452it will not be set again.453

More docsTj Holowaychukbefore adoptionde81ee7

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

Added configuration sectionTj Holowaychukbefore adoption83d2555

line 455why, one step back
455

More docsTj Holowaychukbefore adoptionbedff32

line 456why, one step back
456Redirect to the given _url_ with a default response _status_ of 302.

Configuration docsTj Holowaychukbefore adoptioncb04364

line 457why, one step back
457

More docsTj Holowaychukbefore adoptionbedff32

lines 458–467why, one step back
458 res.redirect('/', 301);
459 res.redirect('/account');460 res.redirect('http://google.com');461 res.redirect('home');462 res.redirect('back');463464Express supports "redirect mapping", which by default provides _home_, and _back_.465The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes466the "home" setting and defaults to "/".467

More view docsTj Holowaychukbefore adoption1c8ff48

lines 468–478why, one step back
468### res.render(view[, options[, fn]])
469470Render _view_ with the given _options_ and optional callback _fn_.471When a callback function is given a response will _not_ be made472automatically, however otherwise a response of _200_ and _text/html_ is given.473474 Most engines accept one or more of the following options,475 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:476477 - _context|scope_ Template evaluation context (_this_)478 - _locals_ Object containing local variables

Cleaning up view docsTj Holowaychukbefore adoption25c8883

line 479why, one step back
479 - _cache_ Cache intermediate JavaScript in memory (the default in _production_ mode)

More view docsTj Holowaychukbefore adoption1c8ff48

lines 480–481why, one step back
480 - _debug_ Output debugging information
481

In depth partial docsTj Holowaychukbefore adoption793943f

lines 482–519why, one step back
482### res.partial(view[, options])
483484Render _view_ partial with the given _options_. This method is always available485to the view as a local variable.486487- _as_ Variable name for each _collection_ value, defaults to the view name.488 * as: 'something' will add the _something_ local variable489 * as: this will use the collection value as the template context490 * as: global will merge the collection value's properties with _locals_491492- _collection_ Array of objects, the name is derived from the view name itself. 493 For example _video.html_ will have a object _video_ available to it.494495The following are equivalent, and the name of collection value when passed496to the partial will be _movie_ as derived from the name.497498 partial('movie.jade', { collection: movies });499 partial('movie.jade', movies);500 partial('movie', movies);501 // In view: movie.director502503To change the local from _movie_ to _video_ we can use the "as" option:504505 partial('movie', { collection: movies, as: 'video' });506 // In view: video.director507508Also we can make our movie the value of _this_ within our view so that instead509of _movie.director_ we could use _this.director_.510511 partial('movie', { collection: movies, as: this });512 // In view: this.director513514Another alternative is to "explode" the properties of the collection item into515pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:516517 partials('movie', { collection: movies, as: global });518 // In view: director519

More docsTj Holowaychukbefore adoptionde81ee7

lines 520–557why, one step back
520### app.set(name[, val])
521522Apply an application level setting _name_ to _val_, or523get the value of _name_ when _val_ is not present:524525 app.set('reload views', 200);526 app.set('reload views');527 // => 200528529### app.enable(name)530531Enable the given setting _name_:532533 app.enable('some arbitrary setting');534 app.set('some arbitrary setting');535 // => true536537### app.disable(name)538539Disable the given setting _name_:540541 app.disable('some setting');542 app.set('some setting');543 // => false544545### app.configure(env|function[, function])546547Define a callback function for the given _env_ (or all environments) with callback _function_:548549 app.configure(function(){550 // executed for each env551 });552553 app.configure('development', function(){554 // executed for 'development' only555 });556557### app.redirect(name, val)

More docsTj Holowaychukbefore adoptionbedff32

lines 558–579why, one step back
558
559For use with `res.redirect()` we can map redirects at the application level as shown below:560561 app.redirect('google', 'http://google.com');562563Now in a route we may call:564565 res.redirect('google');566567We may also map dynamic redirects:568569 app.redirect('comments', function(req, res, params){570 return '/post/' + params.id + '/comments';571 });572573So now we may do the following, and the redirect will dynamically adjust to574the context of the request. If we called this route with _GET /post/12_ our575redirect _Location_ would be _/post/12/comments_.576577 app.get('/post/:id', function(req, res){578 res.redirect('comments');579 });

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 580–582why, one step back
580
581### app.error(function)582

More error docsTj Holowaychukbefore adoption6227f5c

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

Error handling docsTj Holowaychukbefore adoption9fbb9fa

lines 586–589why, one step back
586
587 app.error(function(err, req, res, next){588 res.send(err.message, 500);589 });

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 590–592why, one step back
590
591### app.helpers(obj)592

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

lines 593–608why, one step back
593Registers static view helpers.
594595 app.helpers({596 name: function(first, last){ return first + ', ' + last },597 firstName: 'tj',598 lastName: 'holowaychuk'599 });600601Our view could now utilize the _firstName_ and _lastName_ variables,602as well as the _name()_ function exposed.603604 <%= name(firstName, lastName) %>605606### app.dynamicHelpers(obj)607608Registers dynamic view helpers. Dynamic view helpers

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

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

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

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

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

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

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

Added app.helpers() docsTj Holowaychukbefore adoption7eb088b

lines 614–618why, one step back
614 session: function(req, res, params){
615 return req.session;616 }617 });618

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

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

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 622–635why, one step back
622
623### app.mounted(fn)624625Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.626627 var app = express.createServer(),628 blog = express.createServer();629 630 blog.mounted(function(parent){631 // parent is app632 // "this" is blog633 });634 635 app.use(blog);

Server#listen() docsTj Holowaychukbefore adoptionf3803c4

lines 636–644why, one step back
636
637### app.listen([port[, host]])638639Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all640connections will be accepted via _INADDR_ANY_.641642 app.listen();643 app.listen(3000);644 app.listen(3000, 'n.n.n.n');

Unix domain socket docsTj Holowaychukbefore adoption2fa7907

lines 645–659why, one step back
645
646The _port_ argument may also be a string representing the path to a unix domain socket:647648 app.listen('/tmp/express.sock');649650Then try it out:651652 $ telnet /tmp/express.sock653 GET / HTTP/1.1654655 HTTP/1.1 200 OK656 Content-Type: text/plain657 Content-Length: 11658 659 Hello World