guide.md
This file
Path
docs/guide.md
749 lines · 22.1 KiB · Markdown
Last changed by
Updated docsTj Holowaychukbefore adoptionfd4c88d
History of this fileTake it
The walk stopped after 200 commits: lines older than b40a241 point at it.
Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 1–3why, one step back12### 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 | sh7Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 8–40why, one step back8npm:910 $ npm install express1112git clone, first update the submodules:1314 $ git submodule update --init15 $ make install16 $ make install-support1718### 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.Better blog partialsTj Holowaychukbefore adoptionb40a241
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'));Better blog partialsTj Holowaychukbefore adoptionb40a241
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 }));Better blog partialsTj Holowaychukbefore adoptionb40a241
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());Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 57–81why, 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 });7273To alter the environment we can set the _CONNECT_ENV_ environment variable,74or more specifically _EXPRESS_ENV_, for example:7576 $ EXPRESS_ENV=production node app.js7778### 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.Better blog partialsTj Holowaychukbefore adoptionb40a241
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 'downloads'Tj Holowaychukbefore adoption949803d
lines 87–88why, one step back87 * _partials_ Root view partials directory defaulting to _views_/partials.88 * _stream threshold_ Bytesize indicating when a file should be streamed for _res.sendfile()_ using _fs.ReadStream()_ and _sys.pump()_.Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 89–93why, one step back8990### Routing9192Express 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_, thisUpdated docsTj Holowaychukbefore adoptiond691ecb
lines 94–95why, one step back94can be done by defining the route below. The values associated to the named placeholders 95are available as `req.params`.Better blog partialsTj Holowaychukbefore adoptionb40a241
line 96why, one step back96Updated docsTj Holowaychukbefore adoptiond691ecb
lines 97–98why, one step back97 app.get('/user/:id', function(req, res){98 res.send('user ' + req.params.id);Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 99–105why, one step back99 });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\/([^\/]+)\/?105Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
line 106why, one step back106Regular expression literals may also be passed for complex uses. Since captureUpdated docsTj Holowaychukbefore adoptiond691ecb
line 107why, one step back107groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.Better blog partialsTj Holowaychukbefore adoptionb40a241
line 108why, one step back108Updated docsTj Holowaychukbefore adoptiond691ecb
lines 109–110why, one step back109 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){110 res.send(req.params);Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
lines 111–122why, one step back111 });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"]Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 123–156why, one step back123124Below 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 /products154155### Passing Route Control156Updated docsTj Holowaychukbefore adoptiond691ecb
lines 157–159why, one step back157We may pass control to the next _matching_ route, by calling the _third_ argument,158the _next()_ function. When a match cannot be made, control is passed back to Connect,159and middleware continue to be invoked.Better blog partialsTj Holowaychukbefore adoptionb40a241
line 160why, one step back160Fixed doc typoTj Holowaychukbefore adoption47ff7d9
line 161why, one step back161 app.get('/users/:id?', function(req, res, next){Updated docsTj Holowaychukbefore adoptiond691ecb
lines 162–163why, one step back162 var id = req.params.id;163 if (id) {Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 164–169why, one step back164 // do something165 } else {166 next();167 }168 });169 Updated docsTj Holowaychukbefore adoptiond691ecb
line 170why, one step back170 app.get('/users', function(req, res){Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 171–175why, one step back171 // do something else172 });173174### Middleware175Fixed Connect linksTj Holowaychukbefore adoptiona2e93eb
line 176why, one step back176The Express _Plugin_ is no more! middleware via [Connect](http://github.com/senchalabs/connect) can beBetter blog partialsTj Holowaychukbefore adoptionb40a241
lines 177–178why, one step back177passed to _express.createServer()_ as you would with a regular Connect server. For example:178Updated docsTj Holowaychukbefore adoption344218f
line 179why, one step back179 var express = require('express');Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 180–181why, one step back180181 var app = express.createServer(Updated docsTj Holowaychukbefore adoption344218f
lines 182–183why, one step back182 express.logger(),183 express.bodyDecoder()Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 184–187why, one step back184 );185186Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:187Updated docsTj Holowaychukbefore adoption344218f
line 188why, one step back188 app.use(express.logger({ format: ':method :uri' }));Better blog partialsTj Holowaychukbefore adoptionb40a241
line 189why, one step back189Updated docsTj Holowaychukbefore adoption344218f
lines 190–198why, one step back190Typically with connect middleware you would _require('connect')_ like so:191192 var connect = require('connect');193 app.use(connect.logger());194195This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:196197 app.use(express.logger());198Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 199–224why, one step back199### Error Handling200201Express provides the _app.error()_ method which receives exceptions thrown within a route,202or passed to _next(err)_. Below is an example which serves different pages based on our203ad-hoc _NotFound_ exception:204205 function NotFound(msg){206 this.name = 'NotFound';207 Error.call(this, msg);208 Error.captureStackTrace(this, arguments.callee);209 }210211 sys.inherits(NotFound, Error);212213 app.get('/404', function(req, res){214 throw new NotFound;215 });216217 app.get('/500', function(req, res){218 throw new Error('keyboard cat!');219 });220221We can call _app.error()_ several times as shown below.222Here we check for an instanceof _NotFound_ and show the223404 page, or we pass on to the next error handler.224Merge branch 'fix-error'Tj Holowaychukbefore adoption498115d
lines 225–229why, one step back225Note that these handlers can be defined anywhere, as they226will be placed below the route handlers on _listen()_. This 227allows for definition within _configure()_ blocks so we can228handle exceptions in different ways based on the environment.229Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 230–252why, one step back230 app.error(function(err, req, res, next){231 if (err instanceof NotFound) {232 res.render('404.jade');233 } else {234 next(err);235 }236 });237238Here we assume all errors as 500 for the simplicity of239this demo, however you can choose whatever you like240241 app.error(function(err, req, res){242 res.render('500.jade', {243 locals: {244 error: err245 } 246 });247 });248249Our apps could also utilize the Connect _errorHandler_ middleware250to report on exceptions. For example if we wish to output exceptions 251in "development" mode to _stderr_ we can use:252Updated docsTj Holowaychukbefore adoption344218f
line 253why, one step back253 app.use(express.errorHandler({ dumpExceptions: true }));Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 254–257why, one step back254255Also during development we may want fancy html pages to show exceptions256that are passed or thrown, so we can set _showStack_ to true:257Updated docsTj Holowaychukbefore adoption344218f
line 258why, one step back258 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 259–266why, one step back259260The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_261is present, which is useful for developing apps that rely heavily on client-side JavaScript.262263### View Rendering264265View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name266of the module that will be required. For example the view _layout.ejs_ willAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 267–268why, one step back267tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 268_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 269–296why, one step back269270Below 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 });279280The 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 });Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 314–337why, one step back314315### 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);332333When 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 collectionDoc typosTj Holowaychukbefore adoption02b4ec0
line 338why, one step back338 * _lastInCollection_ True if this is the last objectBetter blog partialsTj Holowaychukbefore adoptionb40a241
lines 339–343why, one step back339340### Template Engines341342Below are a few template engines commonly used with Express:343Doc typosTj Holowaychukbefore adoption02b4ec0
lines 344–345why, one step back344 * [Jade](http://jade-lang.com) haml.js successor345 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templatesBetter blog partialsTj Holowaychukbefore adoptionb40a241
lines 346–383why, one step back346 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript347348### req.header(key[, defaultValue])349350Get the case-insensitive request header _key_, with optional _defaultValue_:351352 req.header('Host');353 req.header('host');354 req.header('Accept', '*/*');355356### req.accepts(type)357358Check 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 // => false379380### req.param(name)381382Return 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=12Better blog partialsTj Holowaychukbefore adoptionb40a241
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.Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 391–409why, one step back391392### req.flash(type[, msg])393394Queue 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: [] }409Added flash formatter docsTj Holowaychukbefore adoptionf16978d
lines 410–413why, one step back410Flash notification message may also utilize formatters, by default only the %s string formatter is available:411412 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);413Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 414–454why, one step back414### req.isXMLHttpRequest415416Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header417to see if it was issued by an _XMLHttpRequest_:418419 req.xhr420 req.isXMLHttpRequest421422### res.header(key[, val])423424Get or set the response header _key_.425426 res.header('Content-Length');427 // => undefined428429 res.header('Content-Length', 123);430 // => 123431432 res.header('Content-Length');433 // => 123434435### res.contentType(type)436437Sets the _Content-Type_ response header to the given _type_.438439 var filename = 'path/to/image.png';440 res.contentType(filename);441 // res.headers['Content-Type'] is now "image/png"442443### res.attachment([filename])444445Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.446447 res.attachment('path/to/my/image.png');448449### res.sendfile(path)450451Used by `res.download()` to transfer an arbitrary file. 452453 res.sendfile('path/to/my.file');454Merge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 455–465why, one step back455This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has __not__ been streamed, _next(err)_ will be called on an exception.456457 res.sendfile(path, function(err, path){458 if (err) {459 // handle the error460 } else {461 console.log('transferred %s', path);462 }463 });464465When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 466–484why, one step back466467### res.download(file[, filename])468469Transfer the given _file_ as an attachment with optional alternative _filename_.470471 res.download('path/to/image.png');472 res.download('path/to/image.png', 'foo.png');473474This is equivalent to:475476 res.attachment(file);477 res.sendfile(file);478479### res.send(body|status[, headers|status[, status]])480481The `res.send()` method is a high level response utility allowing you to pass482objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status483code based responses. The following are all valid uses:484Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
line 485why, one step back485 res.send(); // 204Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 486–510why, one step back486 res.send(new Buffer('wahoo'));487 res.send({ some: 'json' });488 res.send('<p>some html</p>');489 res.send('Sorry, cant find that', 404);490 res.send('text', { 'Content-Type': 'text/plain' }, 201);491 res.send(404);492493By default the _Content-Type_ response header is set, however if explicitly494assigned through `res.send()` or previously with `res.header()` or `res.contentType()`495it will not be set again.496497### res.redirect(url[, status])498499Redirect to the given _url_ with a default response _status_ of 302.500501 res.redirect('/', 301);502 res.redirect('/account');503 res.redirect('http://google.com');504 res.redirect('home');505 res.redirect('back');506507Express supports "redirect mapping", which by default provides _home_, and _back_.508The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes509the "home" setting and defaults to "/".510Cookie docsTj Holowaychukbefore adoptiona89767c
lines 511–531why, one step back511### res.cookie(name, val[, options])512513Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.514515 // "Remember me" for 15 minutes 516 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });517518To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:519520 app.use(express.cookieDecoder());521 522 app.get('/', function(req, res){523 // use req.cookies.rememberme524 });525526### res.clearCookie(name)527528Clear cookie _name_ by setting "expires" far in the past.529530 res.clearCookie('rememberme');531Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 532–540why, one step back532### res.render(view[, options[, fn]])533534Render _view_ with the given _options_ and optional callback _fn_.535When a callback function is given a response will _not_ be made536automatically, however otherwise a response of _200_ and _text/html_ is given.537538 Most engines accept one or more of the following options,539 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:540Updated docsTj Holowaychukbefore adoptionfd4c88d
line 541why, one step back541 - _scope_ Template evaluation context (value of _this_)Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 542–543why, one step back542 - _locals_ Object containing local variables543 - _debug_ Output debugging informationMerge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
lines 544–545why, one step back544 - _status_ Response status code, defaults to 200545 - _headers_ Response headers objectBetter blog partialsTj Holowaychukbefore adoptionb40a241
lines 546–589why, one step back546547### res.partial(view[, options])548549Render _view_ partial with the given _options_. This method is always available550to the view as a local variable.551552- _as_ Variable name for each _collection_ value, defaults to the view name.553 * as: 'something' will add the _something_ local variable554 * as: this will use the collection value as the template context555 * as: global will merge the collection value's properties with _locals_556557- _collection_ Array of objects, the name is derived from the view name itself. 558 For example _video.html_ will have a object _video_ available to it.559560The following are equivalent, and the name of collection value when passed561to the partial will be _movie_ as derived from the name.562563 partial('movie.jade', { collection: movies });564 partial('movie.jade', movies);565 partial('movie', movies);566 // In view: movie.director567568To change the local from _movie_ to _video_ we can use the "as" option:569570 partial('movie', { collection: movies, as: 'video' });571 // In view: video.director572573Also we can make our movie the value of _this_ within our view so that instead574of _movie.director_ we could use _this.director_.575576 partial('movie', { collection: movies, as: this });577 // In view: this.director578579Another alternative is to "explode" the properties of the collection item into580pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:581582 partials('movie', { collection: movies, as: global });583 // In view: director584585### app.set(name[, val])586587Apply an application level setting _name_ to _val_, or588get the value of _name_ when _val_ is not present:589Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110
lines 590–592why, one step back590 app.set('views', __dirname + '/views');591 app.set('views');592 // => ...path...Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 593–633why, one step back593594### app.enable(name)595596Enable the given setting _name_:597598 app.enable('some arbitrary setting');599 app.set('some arbitrary setting');600 // => true601602### app.disable(name)603604Disable the given setting _name_:605606 app.disable('some setting');607 app.set('some setting');608 // => false609610### app.configure(env|function[, function])611612Define a callback function for the given _env_ (or all environments) with callback _function_:613614 app.configure(function(){615 // executed for each env616 });617618 app.configure('development', function(){619 // executed for 'development' only620 });621622### app.redirect(name, val)623624For use with `res.redirect()` we can map redirects at the application level as shown below:625626 app.redirect('google', 'http://google.com');627628Now in a route we may call:629630 res.redirect('google');631632We may also map dynamic redirects:633Updated docsTj Holowaychukbefore adoptiond691ecb
lines 634–635why, one step back634 app.redirect('comments', function(req, res){635 return '/post/' + req.params.id + '/comments';Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 636–654why, one step back636 });637638So now we may do the following, and the redirect will dynamically adjust to639the context of the request. If we called this route with _GET /post/12_ our640redirect _Location_ would be _/post/12/comments_.641642 app.get('/post/:id', function(req, res){643 res.redirect('comments');644 });645646### app.error(function)647648Adds an error handler _function_ which will receive the exception as the first parameter as shown below.649Note that we may set several error handlers by making several calls to this method, however the handler650should call _next(err)_ if it does not wish to deal with the exception:651652 app.error(function(err, req, res, next){653 res.send(err.message, 500);654 });Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 655–657why, one step back655656### app.helpers(obj)657Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 658–673why, one step back658Registers static view helpers.659660 app.helpers({661 name: function(first, last){ return first + ', ' + last },662 firstName: 'tj',663 lastName: 'holowaychuk'664 });665666Our view could now utilize the _firstName_ and _lastName_ variables,667as well as the _name()_ function exposed.668669 <%= name(firstName, lastName) %>670671### app.dynamicHelpers(obj)672673Registers dynamic view helpers. Dynamic view helpersUpdated docsTj Holowaychukbefore adoptiond691ecb
line 674why, one step back674are simply functions which accept _req_, _res_, and areDocs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 675why, one step back675evaluated against the _Server_ instance before a view is rendered. The _return value_ of this functionAdded app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 676–677why, one step back676becomes the local variable it is associated with.677Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 678why, one step back678 app.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 679why, one step back679 session: function(req, res){Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 680–683why, one step back680 return req.session;681 }682 });683Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 684–686why, one step back684All views would now have _session_ available so that session data can be accessed via _session.name_ etc:685686 <%= session.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 687–700why, one step back687688### app.mounted(fn)689690Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.691692 var app = express.createServer(),693 blog = express.createServer();694 695 blog.mounted(function(parent){696 // parent is app697 // "this" is blog698 });699 700 app.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 701–725why, one step back701702### app.register(ext, exports)703704Register the given template engine _exports_705as _ext_. For example we may wish to map ".html"706files to jade:707708 app.register('.html', require('jade'));709710This is also useful for libraries that may not711match extensions correctly. For example my haml.js712library is installed from npm as "hamljs" so instead713of layout.hamljs, we can register the engine as ".haml":714715 app.register('.haml', require('haml-js'));716717For engines that do not comply with the Express718specification, we can also wrap their api this way.719720 app.register('.foo', {721 render: function(str, options) {722 // perhaps their api is723 // foo.toHTML(str, options);724 }725 });Better blog partialsTj Holowaychukbefore adoptionb40a241
lines 726–749why, one step back726727### app.listen([port[, host]])728729Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all730connections will be accepted via _INADDR_ANY_.731732 app.listen();733 app.listen(3000);734 app.listen(3000, 'n.n.n.n');735736The _port_ argument may also be a string representing the path to a unix domain socket:737738 app.listen('/tmp/express.sock');739740Then try it out:741742 $ telnet /tmp/express.sock743 GET / HTTP/1.1744745 HTTP/1.1 200 OK746 Content-Type: text/plain747 Content-Length: 11748 749 Hello World