guide.md
This file
Path
docs/guide.md
689 lines · 20.0 KiB · Markdown
Last changed by
Merge branch 'fix-error'Tj Holowaychukbefore adoption498115d
History of this fileTake it
The walk stopped after 200 commits: lines older than df7582b point at it.
TasksTj Holowaychukbefore adoptiondf7582b
line 1why, one step back1Install docsTj Holowaychukbefore adoption63d02f1
lines 2–3why, one step back2### Installation3No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9
line 4why, one step back4curl:Updated curl install docsTj Holowaychukbefore adoption3ceb0de
lines 5–7why, one step back56 $ curl -# http://expressjs.com/install.sh | sh7Install docsTj Holowaychukbefore adoption63d02f1
lines 8–11why, one step back8npm:910 $ npm install express11Updated install docsTj Holowaychukbefore adoption193c4a9
line 12why, one step back12git clone, first update the submodules:Install docsTj Holowaychukbefore adoption63d02f1
line 13why, one step back13Updated install docsTj Holowaychukbefore adoption193c4a9
line 14why, one step back14 $ git submodule update --initInstall docsTj Holowaychukbefore adoption63d02f1
line 15why, one step back15 $ make installUpdated install docsTj Holowaychukbefore adoption193c4a9
line 16why, one step back16 $ make install-supportInstall docsTj Holowaychukbefore adoption63d02f1
line 17why, one step back17TasksTj Holowaychukbefore adoptiondf7582b
lines 18–40why, one step back18### Creating An Application1920The _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 back41Note 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 back4344 app.configure(function(){Updated docsTj Holowaychukbefore adoption344218f
lines 45–46why, one step back45 app.use(express.methodOverride());46 app.use(express.bodyDecoder());Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
line 47why, one step back47 app.use(app.router);Updated docsTj Holowaychukbefore adoption344218f
line 48why, one step back48 app.use(express.staticProvider(__dirname + '/public'));TasksTj Holowaychukbefore adoptiondf7582b
lines 49–51why, one step back49 });50 51 app.configure('development', function(){Updated docsTj Holowaychukbefore adoption344218f
line 52why, one step back52 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));TasksTj Holowaychukbefore adoptiondf7582b
lines 53–55why, one step back53 });54 55 app.configure('production', function(){Updated docsTj Holowaychukbefore adoption344218f
line 56why, one step back56 app.use(express.errorHandler());TasksTj Holowaychukbefore adoptiondf7582b
lines 57–72why, one step back57 });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 });72More docsTj Holowaychukbefore adoptionde81ee7
lines 73–77why, one step back73To alter the environment we can set the _CONNECT_ENV_ environment variable,74or more specifically _EXPRESS_ENV_, for example:7576 $ EXPRESS_ENV=production node app.js77TasksTj Holowaychukbefore adoptiondf7582b
lines 78–81why, one step back78### Settings7980Express supports the following settings out of the box:81Updated docsTj Holowaychukbefore adoption4d32762
line 82why, one step back82 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_New "home" docsTj Holowaychukbefore adoption1e7a12f
line 83why, one step back83 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.TasksTj Holowaychukbefore adoptiondf7582b
lines 84–85why, one step back84 * _views_ Root views directory defaulting to **CWD/views**85 * _view engine_ Default view engine name for views rendered without extensionsMerge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 86why, one step back86 * _view options_ An object specifying global view optionsMerge branch 'integration'Tj Holowaychukbefore adoption3fae10d
line 87why, one step back87 * _partials_ Root view partials directory defaulting to _views_/partials. TasksTj Holowaychukbefore adoptiondf7582b
lines 88–92why, one step back8889### 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_, thisUpdated docsTj Holowaychukbefore adoptiond691ecb
lines 93–94why, one step back93can 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 back95Updated docsTj Holowaychukbefore adoptiond691ecb
lines 96–97why, one step back96 app.get('/user/:id', function(req, res){97 res.send('user ' + req.params.id);TasksTj Holowaychukbefore adoptiondf7582b
lines 98–104why, one step back98 });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\/([^\/]+)\/?104Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
line 105why, one step back105Regular expression literals may also be passed for complex uses. Since captureUpdated docsTj Holowaychukbefore adoptiond691ecb
line 106why, one step back106groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.TasksTj Holowaychukbefore adoptiondf7582b
line 107why, one step back107Updated docsTj Holowaychukbefore adoptiond691ecb
lines 108–109why, one step back108 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 back110 });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 back122123Below 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 Control155Updated docsTj Holowaychukbefore adoptiond691ecb
lines 156–158why, one step back156We 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 back159Fixed doc typoTj Holowaychukbefore adoption47ff7d9
line 160why, one step back160 app.get('/users/:id?', function(req, res, next){Updated docsTj Holowaychukbefore adoptiond691ecb
lines 161–162why, one step back161 var id = req.params.id;162 if (id) {TasksTj Holowaychukbefore adoptiondf7582b
lines 163–168why, one step back163 // do something164 } else {165 next();166 }167 });168 Updated docsTj Holowaychukbefore adoptiond691ecb
line 169why, one step back169 app.get('/users', function(req, res){TasksTj Holowaychukbefore adoptiondf7582b
lines 170–177why, one step back170 // do something else171 });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:177Updated docsTj Holowaychukbefore adoption344218f
line 178why, one step back178 var express = require('express');TasksTj Holowaychukbefore adoptiondf7582b
lines 179–180why, one step back179180 var app = express.createServer(Updated docsTj Holowaychukbefore adoption344218f
lines 181–182why, one step back181 express.logger(),182 express.bodyDecoder()TasksTj Holowaychukbefore adoptiondf7582b
lines 183–184why, one step back183 );184Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 185–186why, one step back185Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:186Updated docsTj Holowaychukbefore adoption344218f
line 187why, one step back187 app.use(express.logger({ format: ':method :uri' }));Error handling docsTj Holowaychukbefore adoption9fbb9fa
line 188why, one step back188Updated docsTj Holowaychukbefore adoption344218f
lines 189–197why, one step back189Typically with connect middleware you would _require('connect')_ like so:190191 var connect = require('connect');192 app.use(connect.logger());193194This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:195196 app.use(express.logger());197Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 198–223why, one step back198### Error Handling199200Express provides the _app.error()_ method which receives exceptions thrown within a route,201or passed to _next(err)_. Below is an example which serves different pages based on our202ad-hoc _NotFound_ exception:203204 function NotFound(msg){205 this.name = 'NotFound';206 Error.call(this, msg);207 Error.captureStackTrace(this, arguments.callee);208 }209210 sys.inherits(NotFound, Error);211212 app.get('/404', function(req, res){213 throw new NotFound;214 });215216 app.get('/500', function(req, res){217 throw new Error('keyboard cat!');218 });219220We can call _app.error()_ several times as shown below.221Here we check for an instanceof _NotFound_ and show the222404 page, or we pass on to the next error handler.223Merge branch 'fix-error'Tj Holowaychukbefore adoption498115d
lines 224–228why, one step back224Note that these handlers can be defined anywhere, as they225will be placed below the route handlers on _listen()_. This 226allows for definition within _configure()_ blocks so we can227handle exceptions in different ways based on the environment.228Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 229–247why, one step back229 app.error(function(err, req, res, next){230 if (err instanceof NotFound) {231 res.render('404.jade');232 } else {233 next(err);234 }235 });236237Here we assume all errors as 500 for the simplicity of238this demo, however you can choose whatever you like239240 app.error(function(err, req, res){241 res.render('500.jade', {242 locals: {243 error: err244 } 245 });246 });247More error handling docsTj Holowaychukbefore adoptioncea401c
lines 248–251why, one step back248Our apps could also utilize the Connect _errorHandler_ middleware249to report on exceptions. For example if we wish to output exceptions 250in "development" mode to _stderr_ we can use:251Updated docsTj Holowaychukbefore adoption344218f
line 252why, one step back252 app.use(express.errorHandler({ dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 253–256why, one step back253254Also during development we may want fancy html pages to show exceptions255that are passed or thrown, so we can set _showStack_ to true:256Updated docsTj Holowaychukbefore adoption344218f
line 257why, one step back257 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 258–261why, one step back258259The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_260is present, which is useful for developing apps that rely heavily on client-side JavaScript.261Added more view docsTj Holowaychukbefore adoption2f96506
lines 262–279why, one step back262### View Rendering263264View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name265of the module that will be required. For example the view _layout.ejs_ will266tell the view system to _require('ejs')_, the module being loaded must (currently)267export the method _exports.render(str, options)_ to comply with Express, however 268with will likely be extensible in the future.269270Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,271and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 272the _body_ local variable in _layout.haml_.273274 app.get('/', function(req, res){275 res.render('index.haml', {276 locals: { title: 'My Site' }277 });278 });279Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
lines 280–296why, one step back280The new _view engine_ setting allows us to specify our default template engine,281so for example when using [Jade](http://github.com/visionmedia/jade) we could set:282283 app.set('view engine', 'jade');284285Allowing us to render with:286287 res.render('index');288289vs:290291 res.render('index.jade');292293When _view engine_ is set, extensions are entirely optional, however we can still294mix and match template engines:295296 res.render('another-page.ejs');Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 297–313why, one step back297298Express 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:299300 app.set('view options', {301 layout: false302 });303304Which can then be overridden within the `res.render()` call if need be:305306 res.render('myview.ejs', { layout: true });307308A good example of this is specifying custom _ejs_ opening and closing tags:309310 app.set('view options', {311 open: '{{',312 close: '}}'313 });Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
line 314why, one step back314Added more view docsTj Holowaychukbefore adoption2f96506
lines 315–332why, one step back315### View Partials316317The Express view system has built-in support for partials and collections, which are318sort of "mini" views representing a document fragment. For example rather than iterating319in a view to display comments, we would use a partial with collection support:320321 partial('comment.haml', { collection: comments });322323To make things even less verbose we can assume the extension as _.haml_ when omitted,324however if we wished we could use an ejs partial, within a haml view for example.325326 partial('comment', { collection: comments });327328And once again even further, when rendering a collection we can simply pass329an array, if no other options are desired:330331 partial('comments', comments);332Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701
lines 333–339why, one step back333When using the partial collection support a few "magic" variables are provided334for free:335336 * _firstInCollection_ True if this is the first object337 * _indexInCollection_ Index of the object in the collection338 * _lastInCollection _ True if this is the last object339Added more view docsTj Holowaychukbefore adoption2f96506
lines 340–347why, one step back340### Template Engines341342Below are a few template engines commonly used with Express:343344 * [Jade](http://github.com/visionmedia/jade) haml.js successor345 * [Haml](http://github.com/visionmedia/haml.js) indented templates346 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript347More docsTj Holowaychukbefore adoptionde81ee7
line 348why, one step back348### req.header(key[, defaultValue])More docsTj Holowaychukbefore adoptiondfecbe5
lines 349–355why, one step back349350Get the case-insensitive request header _key_, with optional _defaultValue_:351352 req.header('Host');353 req.header('host');354 req.header('Accept', '*/*');355More docsTj Holowaychukbefore adoptionde81ee7
line 356why, one step back356### req.accepts(type)More docsTj Holowaychukbefore adoptiondfecbe5
lines 357–379why, one step back357358Check if the _Accept_ header is present, and includes the given _type_.359360When the _Accept_ header is not present _true_ is returned. Otherwise361the given _type_ is matched by an exact match, and then subtypes. You362may pass the subtype such as "html" which is then converted internally363to "text/html" using the mime lookup table.364365 // Accept: text/html366 req.accepts('html');367 // => true368369 // Accept: text/*; application/json370 req.accepts('html');371 req.accepts('text/html');372 req.accepts('text/plain');373 req.accepts('application/json');374 // => true375376 req.accepts('image/png');377 req.accepts('png');378 // => false379More docsTj Holowaychukbefore adoptionde81ee7
line 380why, one step back380### req.param(name)More docsTj Holowaychukbefore adoptiondfecbe5
lines 381–383why, one step back381382Return the value of param _name_ when present.383Updated docsTj Holowaychukbefore adoptiond691ecb
lines 384–386why, one step back384 - Checks route placeholders (_req.params_), ex: /user/:id385 - Checks query string params (_req.query_), ex: ?id=12386 - Checks urlencoded body params (_req.body_), ex: id=12More docsTj Holowaychukbefore adoptiondfecbe5
lines 387–389why, one step back387388To utilize urlencoded request bodies, _req.body_389should be an object. This can be done by usingUpdated docsTj Holowaychukbefore adoption344218f
line 390why, one step back390the _express.bodyDecoder_ middleware.More docsTj Holowaychukbefore adoptiondfecbe5
line 391why, one step back391More docsTj Holowaychukbefore adoptionde81ee7
line 392why, one step back392### req.flash(type[, msg])More docsTj Holowaychukbefore adoptiondfecbe5
lines 393–409why, one step back393394Queue flash _msg_ of the given _type_.395396 req.flash('info', 'email sent');397 req.flash('error', 'email delivery failed');398 req.flash('info', 'email re-sent');399 // => 2400401 req.flash('info');402 // => ['email sent', 'email re-sent']403404 req.flash('info');405 // => []406407 req.flash();408 // => { error: ['email delivery failed'], info: [] }409More docsTj Holowaychukbefore adoptionde81ee7
line 410why, one step back410### req.isXMLHttpRequestMore docsTj Holowaychukbefore adoptiondfecbe5
lines 411–417why, one step back411412Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header413to see if it was issued by an _XMLHttpRequest_:414415 req.xhr416 req.isXMLHttpRequest417More docsTj Holowaychukbefore adoptionde81ee7
line 418why, one step back418### res.header(key[, val])TasksTj Holowaychukbefore adoptiondf7582b
lines 419–430why, one step back419420Get or set the response header _key_.421422 res.header('Content-Length');423 // => undefined424425 res.header('Content-Length', 123);426 // => 123427428 res.header('Content-Length');429 // => 123430More docsTj Holowaychukbefore adoptionde81ee7
line 431why, one step back431### res.contentType(type)TasksTj Holowaychukbefore adoptiondf7582b
lines 432–438why, one step back432433Sets the _Content-Type_ response header to the given _type_.434435 var filename = 'path/to/image.png';436 res.contentType(filename);437 // res.headers['Content-Type'] is now "image/png"438More docsTj Holowaychukbefore adoptionde81ee7
line 439why, one step back439### res.attachment([filename])TasksTj Holowaychukbefore adoptiondf7582b
lines 440–444why, one step back440441Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.442443 res.attachment('path/to/my/image.png');444More docsTj Holowaychukbefore adoptionde81ee7
line 445why, one step back445### res.sendfile(path)TasksTj Holowaychukbefore adoptiondf7582b
lines 446–450why, one step back446447Used by `res.download()` to transfer an arbitrary file. 448449 res.sendfile('path/to/my.file');450Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1
lines 451–454why, one step back451This is _not_ a substitution for Connect's _staticProvider_ middleware, it does not452support HTTP caching, and does not perform any security checks. This method is utilized453by _res.download()_ to transfer static files, and allows you do to so from outside of454the public directory, so suitable security checks should be applied.TasksTj Holowaychukbefore adoptiondf7582b
line 455why, one step back455More docsTj Holowaychukbefore adoptionde81ee7
line 456why, one step back456### res.download(file[, filename])TasksTj Holowaychukbefore adoptiondf7582b
lines 457–467why, one step back457458Transfer the given _file_ as an attachment with optional alternative _filename_.459460 res.download('path/to/image.png');461 res.download('path/to/image.png', 'foo.png');462463This is equivalent to:464465 res.attachment(file);466 res.sendfile(file);467More docsTj Holowaychukbefore adoptionde81ee7
line 468why, one step back468### res.send(body|status[, headers|status[, status]])TasksTj Holowaychukbefore adoptiondf7582b
lines 469–484why, one step back469470The `res.send()` method is a high level response utility allowing you to pass471objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status472code based responses. The following are all valid uses:473474 res.send(new Buffer('wahoo'));475 res.send({ some: 'json' });476 res.send('<p>some html</p>');477 res.send('Sorry, cant find that', 404);478 res.send('text', { 'Content-Type': 'text/plain' }, 201);479 res.send(404);480481By default the _Content-Type_ response header is set, however if explicitly482assigned through `res.send()` or previously with `res.header()` or `res.contentType()`483it will not be set again.484More docsTj Holowaychukbefore adoptionde81ee7
line 485why, one step back485### res.redirect(url[, status])TasksTj Holowaychukbefore adoptiondf7582b
lines 486–498why, one step back486487Redirect to the given _url_ with a default response _status_ of 302.488489 res.redirect('/', 301);490 res.redirect('/account');491 res.redirect('http://google.com');492 res.redirect('home');493 res.redirect('back');494495Express supports "redirect mapping", which by default provides _home_, and _back_.496The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes497the "home" setting and defaults to "/".498More view docsTj Holowaychukbefore adoption1c8ff48
lines 499–511why, one step back499### res.render(view[, options[, fn]])500501Render _view_ with the given _options_ and optional callback _fn_.502When a callback function is given a response will _not_ be made503automatically, however otherwise a response of _200_ and _text/html_ is given.504505 Most engines accept one or more of the following options,506 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:507508 - _context|scope_ Template evaluation context (_this_)509 - _locals_ Object containing local variables510 - _debug_ Output debugging information511In depth partial docsTj Holowaychukbefore adoption793943f
lines 512–549why, one step back512### res.partial(view[, options])513514Render _view_ partial with the given _options_. This method is always available515to the view as a local variable.516517- _as_ Variable name for each _collection_ value, defaults to the view name.518 * as: 'something' will add the _something_ local variable519 * as: this will use the collection value as the template context520 * as: global will merge the collection value's properties with _locals_521522- _collection_ Array of objects, the name is derived from the view name itself. 523 For example _video.html_ will have a object _video_ available to it.524525The following are equivalent, and the name of collection value when passed526to the partial will be _movie_ as derived from the name.527528 partial('movie.jade', { collection: movies });529 partial('movie.jade', movies);530 partial('movie', movies);531 // In view: movie.director532533To change the local from _movie_ to _video_ we can use the "as" option:534535 partial('movie', { collection: movies, as: 'video' });536 // In view: video.director537538Also we can make our movie the value of _this_ within our view so that instead539of _movie.director_ we could use _this.director_.540541 partial('movie', { collection: movies, as: this });542 // In view: this.director543544Another alternative is to "explode" the properties of the collection item into545pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:546547 partials('movie', { collection: movies, as: global });548 // In view: director549More docsTj Holowaychukbefore adoptionde81ee7
lines 550–554why, one step back550### app.set(name[, val])551552Apply an application level setting _name_ to _val_, or553get the value of _name_ when _val_ is not present:554Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110
lines 555–557why, one step back555 app.set('views', __dirname + '/views');556 app.set('views');557 // => ...path...More docsTj Holowaychukbefore adoptionde81ee7
lines 558–587why, one step back558559### app.enable(name)560561Enable the given setting _name_:562563 app.enable('some arbitrary setting');564 app.set('some arbitrary setting');565 // => true566567### app.disable(name)568569Disable the given setting _name_:570571 app.disable('some setting');572 app.set('some setting');573 // => false574575### app.configure(env|function[, function])576577Define a callback function for the given _env_ (or all environments) with callback _function_:578579 app.configure(function(){580 // executed for each env581 });582583 app.configure('development', function(){584 // executed for 'development' only585 });586587### app.redirect(name, val)TasksTj Holowaychukbefore adoptiondf7582b
lines 588–598why, one step back588589For use with `res.redirect()` we can map redirects at the application level as shown below:590591 app.redirect('google', 'http://google.com');592593Now in a route we may call:594595 res.redirect('google');596597We may also map dynamic redirects:598Updated docsTj Holowaychukbefore adoptiond691ecb
lines 599–600why, one step back599 app.redirect('comments', function(req, res){600 return '/post/' + req.params.id + '/comments';TasksTj Holowaychukbefore adoptiondf7582b
lines 601–609why, one step back601 });602603So now we may do the following, and the redirect will dynamically adjust to604the context of the request. If we called this route with _GET /post/12_ our605redirect _Location_ would be _/post/12/comments_.606607 app.get('/post/:id', function(req, res){608 res.redirect('comments');609 });Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 610–612why, one step back610611### app.error(function)612More error docsTj Holowaychukbefore adoption6227f5c
lines 613–615why, one step back613Adds an error handler _function_ which will receive the exception as the first parameter as shown below.614Note that we may set several error handlers by making several calls to this method, however the handler615should call _next(err)_ if it does not wish to deal with the exception:Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 616–619why, one step back616617 app.error(function(err, req, res, next){618 res.send(err.message, 500);619 });Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 620–622why, one step back620621### app.helpers(obj)622Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 623–638why, one step back623Registers static view helpers.624625 app.helpers({626 name: function(first, last){ return first + ', ' + last },627 firstName: 'tj',628 lastName: 'holowaychuk'629 });630631Our view could now utilize the _firstName_ and _lastName_ variables,632as well as the _name()_ function exposed.633634 <%= name(firstName, lastName) %>635636### app.dynamicHelpers(obj)637638Registers dynamic view helpers. Dynamic view helpersUpdated docsTj Holowaychukbefore adoptiond691ecb
line 639why, one step back639are simply functions which accept _req_, _res_, and areDocs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 640why, one step back640evaluated against the _Server_ instance before a view is rendered. The _return value_ of this functionAdded app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 641–642why, one step back641becomes the local variable it is associated with.642Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 643why, one step back643 app.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 644why, one step back644 session: function(req, res){Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 645–648why, one step back645 return req.session;646 }647 });648Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 649–651why, one step back649All views would now have _session_ available so that session data can be accessed via _session.name_ etc:650651 <%= session.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 652–665why, one step back652653### app.mounted(fn)654655Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.656657 var app = express.createServer(),658 blog = express.createServer();659 660 blog.mounted(function(parent){661 // parent is app662 // "this" is blog663 });664 665 app.use(blog);Server#listen() docsTj Holowaychukbefore adoptionf3803c4
lines 666–674why, one step back666667### app.listen([port[, host]])668669Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all670connections will be accepted via _INADDR_ANY_.671672 app.listen();673 app.listen(3000);674 app.listen(3000, 'n.n.n.n');Unix domain socket docsTj Holowaychukbefore adoption2fa7907
lines 675–689why, one step back675676The _port_ argument may also be a string representing the path to a unix domain socket:677678 app.listen('/tmp/express.sock');679680Then try it out:681682 $ telnet /tmp/express.sock683 GET / HTTP/1.1684685 HTTP/1.1 200 OK686 Content-Type: text/plain687 Content-Length: 11688 689 Hello World