guide.md
This file
Path
docs/guide.md
684 lines · 19.8 KiB · Markdown
Last changed by
Updated docsTj Holowaychukbefore adoption344218f
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–242why, 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.223224 app.error(function(err, req, res, next){225 if (err instanceof NotFound) {226 res.render('404.jade');227 } else {228 next(err);229 }230 });231232Here we assume all errors as 500 for the simplicity of233this demo, however you can choose whatever you like234235 app.error(function(err, req, res){236 res.render('500.jade', {237 locals: {238 error: err239 } 240 });241 });242More error handling docsTj Holowaychukbefore adoptioncea401c
lines 243–246why, one step back243Our apps could also utilize the Connect _errorHandler_ middleware244to report on exceptions. For example if we wish to output exceptions 245in "development" mode to _stderr_ we can use:246Updated docsTj Holowaychukbefore adoption344218f
line 247why, one step back247 app.use(express.errorHandler({ dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 248–251why, one step back248249Also during development we may want fancy html pages to show exceptions250that are passed or thrown, so we can set _showStack_ to true:251Updated docsTj Holowaychukbefore adoption344218f
line 252why, one step back252 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 253–256why, one step back253254The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_255is present, which is useful for developing apps that rely heavily on client-side JavaScript.256Added more view docsTj Holowaychukbefore adoption2f96506
lines 257–274why, one step back257### View Rendering258259View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name260of the module that will be required. For example the view _layout.ejs_ will261tell the view system to _require('ejs')_, the module being loaded must (currently)262export the method _exports.render(str, options)_ to comply with Express, however 263with will likely be extensible in the future.264265Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,266and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 267the _body_ local variable in _layout.haml_.268269 app.get('/', function(req, res){270 res.render('index.haml', {271 locals: { title: 'My Site' }272 });273 });274Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
lines 275–291why, one step back275The new _view engine_ setting allows us to specify our default template engine,276so for example when using [Jade](http://github.com/visionmedia/jade) we could set:277278 app.set('view engine', 'jade');279280Allowing us to render with:281282 res.render('index');283284vs:285286 res.render('index.jade');287288When _view engine_ is set, extensions are entirely optional, however we can still289mix and match template engines:290291 res.render('another-page.ejs');Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 292–308why, one step back292293Express 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:294295 app.set('view options', {296 layout: false297 });298299Which can then be overridden within the `res.render()` call if need be:300301 res.render('myview.ejs', { layout: true });302303A good example of this is specifying custom _ejs_ opening and closing tags:304305 app.set('view options', {306 open: '{{',307 close: '}}'308 });Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
line 309why, one step back309Added more view docsTj Holowaychukbefore adoption2f96506
lines 310–327why, one step back310### View Partials311312The Express view system has built-in support for partials and collections, which are313sort of "mini" views representing a document fragment. For example rather than iterating314in a view to display comments, we would use a partial with collection support:315316 partial('comment.haml', { collection: comments });317318To make things even less verbose we can assume the extension as _.haml_ when omitted,319however if we wished we could use an ejs partial, within a haml view for example.320321 partial('comment', { collection: comments });322323And once again even further, when rendering a collection we can simply pass324an array, if no other options are desired:325326 partial('comments', comments);327Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701
lines 328–334why, one step back328When using the partial collection support a few "magic" variables are provided329for free:330331 * _firstInCollection_ True if this is the first object332 * _indexInCollection_ Index of the object in the collection333 * _lastInCollection _ True if this is the last object334Added more view docsTj Holowaychukbefore adoption2f96506
lines 335–342why, one step back335### Template Engines336337Below are a few template engines commonly used with Express:338339 * [Jade](http://github.com/visionmedia/jade) haml.js successor340 * [Haml](http://github.com/visionmedia/haml.js) indented templates341 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript342More docsTj Holowaychukbefore adoptionde81ee7
line 343why, one step back343### req.header(key[, defaultValue])More docsTj Holowaychukbefore adoptiondfecbe5
lines 344–350why, one step back344345Get the case-insensitive request header _key_, with optional _defaultValue_:346347 req.header('Host');348 req.header('host');349 req.header('Accept', '*/*');350More docsTj Holowaychukbefore adoptionde81ee7
line 351why, one step back351### req.accepts(type)More docsTj Holowaychukbefore adoptiondfecbe5
lines 352–374why, one step back352353Check if the _Accept_ header is present, and includes the given _type_.354355When the _Accept_ header is not present _true_ is returned. Otherwise356the given _type_ is matched by an exact match, and then subtypes. You357may pass the subtype such as "html" which is then converted internally358to "text/html" using the mime lookup table.359360 // Accept: text/html361 req.accepts('html');362 // => true363364 // Accept: text/*; application/json365 req.accepts('html');366 req.accepts('text/html');367 req.accepts('text/plain');368 req.accepts('application/json');369 // => true370371 req.accepts('image/png');372 req.accepts('png');373 // => false374More docsTj Holowaychukbefore adoptionde81ee7
line 375why, one step back375### req.param(name)More docsTj Holowaychukbefore adoptiondfecbe5
lines 376–378why, one step back376377Return the value of param _name_ when present.378Updated docsTj Holowaychukbefore adoptiond691ecb
lines 379–381why, one step back379 - Checks route placeholders (_req.params_), ex: /user/:id380 - Checks query string params (_req.query_), ex: ?id=12381 - Checks urlencoded body params (_req.body_), ex: id=12More docsTj Holowaychukbefore adoptiondfecbe5
lines 382–384why, one step back382383To utilize urlencoded request bodies, _req.body_384should be an object. This can be done by usingUpdated docsTj Holowaychukbefore adoption344218f
line 385why, one step back385the _express.bodyDecoder_ middleware.More docsTj Holowaychukbefore adoptiondfecbe5
line 386why, one step back386More docsTj Holowaychukbefore adoptionde81ee7
line 387why, one step back387### req.flash(type[, msg])More docsTj Holowaychukbefore adoptiondfecbe5
lines 388–404why, one step back388389Queue flash _msg_ of the given _type_.390391 req.flash('info', 'email sent');392 req.flash('error', 'email delivery failed');393 req.flash('info', 'email re-sent');394 // => 2395396 req.flash('info');397 // => ['email sent', 'email re-sent']398399 req.flash('info');400 // => []401402 req.flash();403 // => { error: ['email delivery failed'], info: [] }404More docsTj Holowaychukbefore adoptionde81ee7
line 405why, one step back405### req.isXMLHttpRequestMore docsTj Holowaychukbefore adoptiondfecbe5
lines 406–412why, one step back406407Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header408to see if it was issued by an _XMLHttpRequest_:409410 req.xhr411 req.isXMLHttpRequest412More docsTj Holowaychukbefore adoptionde81ee7
line 413why, one step back413### res.header(key[, val])TasksTj Holowaychukbefore adoptiondf7582b
lines 414–425why, one step back414415Get or set the response header _key_.416417 res.header('Content-Length');418 // => undefined419420 res.header('Content-Length', 123);421 // => 123422423 res.header('Content-Length');424 // => 123425More docsTj Holowaychukbefore adoptionde81ee7
line 426why, one step back426### res.contentType(type)TasksTj Holowaychukbefore adoptiondf7582b
lines 427–433why, one step back427428Sets the _Content-Type_ response header to the given _type_.429430 var filename = 'path/to/image.png';431 res.contentType(filename);432 // res.headers['Content-Type'] is now "image/png"433More docsTj Holowaychukbefore adoptionde81ee7
line 434why, one step back434### res.attachment([filename])TasksTj Holowaychukbefore adoptiondf7582b
lines 435–439why, one step back435436Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.437438 res.attachment('path/to/my/image.png');439More docsTj Holowaychukbefore adoptionde81ee7
line 440why, one step back440### res.sendfile(path)TasksTj Holowaychukbefore adoptiondf7582b
lines 441–445why, one step back441442Used by `res.download()` to transfer an arbitrary file. 443444 res.sendfile('path/to/my.file');445Better docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1
lines 446–449why, one step back446This is _not_ a substitution for Connect's _staticProvider_ middleware, it does not447support HTTP caching, and does not perform any security checks. This method is utilized448by _res.download()_ to transfer static files, and allows you do to so from outside of449the public directory, so suitable security checks should be applied.TasksTj Holowaychukbefore adoptiondf7582b
line 450why, one step back450More docsTj Holowaychukbefore adoptionde81ee7
line 451why, one step back451### res.download(file[, filename])TasksTj Holowaychukbefore adoptiondf7582b
lines 452–462why, one step back452453Transfer the given _file_ as an attachment with optional alternative _filename_.454455 res.download('path/to/image.png');456 res.download('path/to/image.png', 'foo.png');457458This is equivalent to:459460 res.attachment(file);461 res.sendfile(file);462More docsTj Holowaychukbefore adoptionde81ee7
line 463why, one step back463### res.send(body|status[, headers|status[, status]])TasksTj Holowaychukbefore adoptiondf7582b
lines 464–479why, one step back464465The `res.send()` method is a high level response utility allowing you to pass466objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status467code based responses. The following are all valid uses:468469 res.send(new Buffer('wahoo'));470 res.send({ some: 'json' });471 res.send('<p>some html</p>');472 res.send('Sorry, cant find that', 404);473 res.send('text', { 'Content-Type': 'text/plain' }, 201);474 res.send(404);475476By default the _Content-Type_ response header is set, however if explicitly477assigned through `res.send()` or previously with `res.header()` or `res.contentType()`478it will not be set again.479More docsTj Holowaychukbefore adoptionde81ee7
line 480why, one step back480### res.redirect(url[, status])TasksTj Holowaychukbefore adoptiondf7582b
lines 481–493why, one step back481482Redirect to the given _url_ with a default response _status_ of 302.483484 res.redirect('/', 301);485 res.redirect('/account');486 res.redirect('http://google.com');487 res.redirect('home');488 res.redirect('back');489490Express supports "redirect mapping", which by default provides _home_, and _back_.491The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes492the "home" setting and defaults to "/".493More view docsTj Holowaychukbefore adoption1c8ff48
lines 494–506why, one step back494### res.render(view[, options[, fn]])495496Render _view_ with the given _options_ and optional callback _fn_.497When a callback function is given a response will _not_ be made498automatically, however otherwise a response of _200_ and _text/html_ is given.499500 Most engines accept one or more of the following options,501 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:502503 - _context|scope_ Template evaluation context (_this_)504 - _locals_ Object containing local variables505 - _debug_ Output debugging information506In depth partial docsTj Holowaychukbefore adoption793943f
lines 507–544why, one step back507### res.partial(view[, options])508509Render _view_ partial with the given _options_. This method is always available510to the view as a local variable.511512- _as_ Variable name for each _collection_ value, defaults to the view name.513 * as: 'something' will add the _something_ local variable514 * as: this will use the collection value as the template context515 * as: global will merge the collection value's properties with _locals_516517- _collection_ Array of objects, the name is derived from the view name itself. 518 For example _video.html_ will have a object _video_ available to it.519520The following are equivalent, and the name of collection value when passed521to the partial will be _movie_ as derived from the name.522523 partial('movie.jade', { collection: movies });524 partial('movie.jade', movies);525 partial('movie', movies);526 // In view: movie.director527528To change the local from _movie_ to _video_ we can use the "as" option:529530 partial('movie', { collection: movies, as: 'video' });531 // In view: video.director532533Also we can make our movie the value of _this_ within our view so that instead534of _movie.director_ we could use _this.director_.535536 partial('movie', { collection: movies, as: this });537 // In view: this.director538539Another alternative is to "explode" the properties of the collection item into540pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:541542 partials('movie', { collection: movies, as: global });543 // In view: director544More docsTj Holowaychukbefore adoptionde81ee7
lines 545–549why, one step back545### app.set(name[, val])546547Apply an application level setting _name_ to _val_, or548get the value of _name_ when _val_ is not present:549Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110
lines 550–552why, one step back550 app.set('views', __dirname + '/views');551 app.set('views');552 // => ...path...More docsTj Holowaychukbefore adoptionde81ee7
lines 553–582why, one step back553554### app.enable(name)555556Enable the given setting _name_:557558 app.enable('some arbitrary setting');559 app.set('some arbitrary setting');560 // => true561562### app.disable(name)563564Disable the given setting _name_:565566 app.disable('some setting');567 app.set('some setting');568 // => false569570### app.configure(env|function[, function])571572Define a callback function for the given _env_ (or all environments) with callback _function_:573574 app.configure(function(){575 // executed for each env576 });577578 app.configure('development', function(){579 // executed for 'development' only580 });581582### app.redirect(name, val)TasksTj Holowaychukbefore adoptiondf7582b
lines 583–593why, one step back583584For use with `res.redirect()` we can map redirects at the application level as shown below:585586 app.redirect('google', 'http://google.com');587588Now in a route we may call:589590 res.redirect('google');591592We may also map dynamic redirects:593Updated docsTj Holowaychukbefore adoptiond691ecb
lines 594–595why, one step back594 app.redirect('comments', function(req, res){595 return '/post/' + req.params.id + '/comments';TasksTj Holowaychukbefore adoptiondf7582b
lines 596–604why, one step back596 });597598So now we may do the following, and the redirect will dynamically adjust to599the context of the request. If we called this route with _GET /post/12_ our600redirect _Location_ would be _/post/12/comments_.601602 app.get('/post/:id', function(req, res){603 res.redirect('comments');604 });Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 605–607why, one step back605606### app.error(function)607More error docsTj Holowaychukbefore adoption6227f5c
lines 608–610why, one step back608Adds an error handler _function_ which will receive the exception as the first parameter as shown below.609Note that we may set several error handlers by making several calls to this method, however the handler610should call _next(err)_ if it does not wish to deal with the exception:Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 611–614why, one step back611612 app.error(function(err, req, res, next){613 res.send(err.message, 500);614 });Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 615–617why, one step back615616### app.helpers(obj)617Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 618–633why, one step back618Registers static view helpers.619620 app.helpers({621 name: function(first, last){ return first + ', ' + last },622 firstName: 'tj',623 lastName: 'holowaychuk'624 });625626Our view could now utilize the _firstName_ and _lastName_ variables,627as well as the _name()_ function exposed.628629 <%= name(firstName, lastName) %>630631### app.dynamicHelpers(obj)632633Registers dynamic view helpers. Dynamic view helpersUpdated docsTj Holowaychukbefore adoptiond691ecb
line 634why, one step back634are simply functions which accept _req_, _res_, and areDocs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 635why, one step back635evaluated against the _Server_ instance before a view is rendered. The _return value_ of this functionAdded app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 636–637why, one step back636becomes the local variable it is associated with.637Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 638why, one step back638 app.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 639why, one step back639 session: function(req, res){Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 640–643why, one step back640 return req.session;641 }642 });643Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 644–646why, one step back644All views would now have _session_ available so that session data can be accessed via _session.name_ etc:645646 <%= session.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 647–660why, one step back647648### app.mounted(fn)649650Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.651652 var app = express.createServer(),653 blog = express.createServer();654 655 blog.mounted(function(parent){656 // parent is app657 // "this" is blog658 });659 660 app.use(blog);Server#listen() docsTj Holowaychukbefore adoptionf3803c4
lines 661–669why, one step back661662### app.listen([port[, host]])663664Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all665connections will be accepted via _INADDR_ANY_.666667 app.listen();668 app.listen(3000);669 app.listen(3000, 'n.n.n.n');Unix domain socket docsTj Holowaychukbefore adoption2fa7907
lines 670–684why, one step back670671The _port_ argument may also be a string representing the path to a unix domain socket:672673 app.listen('/tmp/express.sock');674675Then try it out:676677 $ telnet /tmp/express.sock678 GET / HTTP/1.1679680 HTTP/1.1 200 OK681 Content-Type: text/plain682 Content-Length: 11683 684 Hello World