Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,050 lines · 34.7 KiB · Markdown

Last changed by

DocsTj Holowaychukbefore adoption14dce5a

History of this file

Take it

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 1–38why, one step back
1
2### Installation34curl:56 $ curl -# http://expressjs.com/install.sh | sh78npm:910 $ npm install express1112### Creating An Application1314The _express.Server_ now inherits from _http.Server_, however15follows the same idiom by providing _express.createServer()_ as shown below. This means16that you can utilize Express server's transparently with other libraries.1718 var app = require('express').createServer();19 20 app.get('/', function(req, res){21 res.send('hello world');22 });23 24 app.listen(3000);2526### Configuration2728Express supports arbitrary environments, such as _production_ and _development_. Developers29can use the _configure()_ method to setup needs required by the current environment. When30_configure()_ is called without an environment name it will be run in _every_ environment 31prior to the environment specific callback.3233In the example below we only _dumpExceptions_, and respond with exception stack traces34in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.35Note the use of _app.router_, which can (optionally) be used to mount the application routes,36otherwise the first call to _app.{get,put,del,post}()_ will mount the routes.3738 app.configure(function(){

DocsTj Holowaychukbefore adoption5234368

lines 39–43why, one step back
39 app.use(express.methodOverride());
40 app.use(express.bodyDecoder());41 app.use(app.router);42 app.use(express.staticProvider(__dirname + '/public'));43 });

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

line 44why, one step back
44

DocsTj Holowaychukbefore adoption5234368

lines 45–47why, one step back
45 app.configure('development', function(){
46 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));47 });

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

line 48why, one step back
48

DocsTj Holowaychukbefore adoption5234368

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 52–70why, one step back
52
53For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:5455 app.configure(function(){56 app.set('views', __dirname + '/views');57 app.set('views');58 // => "... views directory ..."59 60 app.enable('some feature');61 // same as app.set('some feature', true);62 63 app.disable('some feature');64 // same as app.set('some feature', false);65 });6667To alter the environment we can set the _NODE_ENV_ environment variable, for example:6869 $ NODE_ENV=production node app.js70

NODE_ENV=production docs, VERY IMPORTANT do this, or your app will be slow :pTj Holowaychukbefore adoptiond4868f2

lines 71–72why, one step back
71This is _very_ important, as many caching mechanisms are _only enabled_ when in production.
72

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 73–91why, one step back
73### Settings
7475Express supports the following settings out of the box:7677 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_78 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.79 * _views_ Root views directory defaulting to **CWD/views**80 * _view engine_ Default view engine name for views rendered without extensions81 * _view options_ An object specifying global view options82 * _stream threshold_ Bytesize indicating when a file should be streamed for _res.sendfile()_ using _fs.ReadStream()_ and _sys.pump()_.8384### Routing8586Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.87For example we may want to render a user's account for the path _/user/12_, this88can be done by defining the route below. The values associated to the named placeholders 89are available as `req.params`.9091 app.get('/user/:id', function(req, res){

DocsTj Holowaychukbefore adoption5234368

lines 92–93why, one step back
92 res.send('user ' + req.params.id);
93 });

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 94–100why, one step back
94
95A route is simple a string which is compiled to a _RegExp_ internally. For example96when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:9798 \/user\/([^\/]+)\/?99100Regular expression literals may also be passed for complex uses. Since capture

DocsTj Holowaychukbefore adoptionbba049b

line 101why, one step back
101groups with literal _RegExp_'s are anonymous we can access them directly `req.params`. So our first capture group would be _req.params[0]_ and the second would follow as _req.params[1]_.

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 102–147why, one step back
102
103 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){104 res.send(req.params);105 });106107Curl requests against the previously defined route:108109 $ curl http://dev:3000/user110 [null,null]111 $ curl http://dev:3000/users112 [null,null]113 $ curl http://dev:3000/users/1114 ["1",null]115 $ curl http://dev:3000/users/1..15116 ["1","15"]117118Below are some route examples, and the associated paths that they119may consume:120121 "/user/:id"122 /user/12123124 "/users/:id?"125 /users/5126 /users127128 "/files/*"129 /files/jquery.js130 /files/javascripts/jquery.js131132 "/file/*.*"133 /files/jquery.js134 /files/javascripts/jquery.js135 136 "/user/:id/:operation?"137 /user/1138 /user/1/edit139 140 "/products.:format"141 /products.json142 /products.xml143144 "/products.:format?"145 /products.json146 /products.xml147 /products

DocsTj Holowaychukbefore adoptionbba049b

lines 148–151why, one step back
148
149 "/user/:id.:format?"150 /user/12151 /user/12.json

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

line 152why, one step back
152

DocsTj Holowaychukbefore adoption5234368

lines 153–164why, one step back
153For example we can __POST__ some json, and echo the json back using the _bodyDecoder_ middleware which will parse json request bodies (as well as others), and place the result in _req.body_:
154155 var express = require('express')156 , app = express.createServer();157158 app.use(express.bodyDecoder());159160 app.post('/', function(req, res){161 res.send(req.body);162 });163164 app.listen(3000);

DocsTj Holowaychukbefore adoptionbba049b

line 165why, one step back
165

DocsTj Holowaychukbefore adoption14dce5a

line 166why, one step back
166Express 2.0.0-pre also supports named capture groups. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, however say for example we are limiting a user id to digits, we may use _'/user/:id(\\d+)'_ which will _not_ match unless the placeholder value contains only digits.

DocsTj Holowaychukbefore adoption5234368

line 167why, one step back
167

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 168–185why, one step back
168### Passing Route Control
169170We may pass control to the next _matching_ route, by calling the _third_ argument,171the _next()_ function. When a match cannot be made, control is passed back to Connect,172and middleware continue to be invoked. The same is true for several routes which have the same path defined, they will simply be executed in order until one does _not_ call _next()_.173174 app.get('/users/:id?', function(req, res, next){175 var id = req.params.id;176 if (id) {177 // do something178 } else {179 next();180 }181 });182 183 app.get('/users', function(req, res){184 // do something else185 });

DocsTj Holowaychukbefore adoption5234368

lines 186–219why, one step back
186
187Express 1.0 also introduces the _all()_ method, which provides a route callback matching any HTTP method. This is useful in many ways, one example being the loading of resources before executing subsequent routes as shown below:188189 var express = require('express')190 , app = express.createServer();191192 var users = [{ name: 'tj' }];193194 app.all('/user/:id/:op?', function(req, res, next){195 req.user = users[req.params.id];196 if (req.user) {197 next();198 } else {199 next(new Error('cannot find user ' + req.params.id));200 }201 });202203 app.get('/user/:id', function(req, res){204 res.send('viewing ' + req.user.name);205 });206207 app.get('/user/:id/edit', function(req, res){208 res.send('editing ' + req.user.name);209 });210211 app.put('/user/:id', function(req, res){212 res.send('updating ' + req.user.name);213 });214215 app.get('*', function(req, res){216 res.send('what???', 404);217 });218219 app.listen(3000);

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 220–322why, one step back
220
221### Middleware222223Middleware via [Connect](http://github.com/senchalabs/connect) can be224passed to _express.createServer()_ as you would with a regular Connect server. For example:225226 var express = require('express');227228 var app = express.createServer(229 express.logger(),230 express.bodyDecoder()231 );232233Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:234235 app.use(express.logger({ format: ':method :uri' }));236237Typically with connect middleware you would _require('connect')_ like so:238239 var connect = require('connect');240 app.use(connect.logger());241242This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:243244 app.use(express.logger());245246### Route Middleware247248Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.249250Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 251252 app.get('/user/:id', function(req, res, next){253 loadUser(req.params.id, function(err, user){254 if (err) return next(err);255 res.send('Viewing user ' + user.name);256 });257 });258259To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time. 260261 function loadUser(req, res, next) {262 // You would fetch your user from the db263 var user = users[req.params.id];264 if (user) {265 req.user = user;266 next();267 } else {268 next(new Error('Failed to load user ' + req.params.id));269 }270 }271 272 app.get('/user/:id', loadUser, function(req, res){273 res.send('Viewing user ' + req.user.name);274 });275276Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.277278 function andRestrictToSelf(req, res, next) {279 req.authenticatedUser.id == req.user.id280 ? next()281 : next(new Error('Unauthorized'));282 }283 284 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){285 res.send('Editing user ' + req.user.name);286 });287288Keeping in mind that middleware are simply functions, we can define function that _returns_ the middleware in order to create a more expressive and flexible solution as shown below.289290 function andRestrictTo(role) {291 return function(req, res, next) {292 req.authenticatedUser.role == role293 ? next()294 : next(new Error('Unauthorized'));295 }296 }297 298 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){299 res.send('Deleted user ' + req.user.name);300 });301302Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.303304 var a = [middleware1, middleware2]305 , b = [middleware3, middleware4]306 , all = [a, b];307 308 app.get('/foo', a, function(){});309 app.get('/bar', a, function(){});310 311 app.get('/', a, middleware3, middleware4, function(){});312 app.get('/', a, b, function(){});313 app.get('/', all, function(){});314315For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.316317### HTTP Methods318319We have seen _app.get()_ a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as _app.post()_, _app.del()_, etc.320321 A common example for _POST_ usage, is when "submitting" a form. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it.322

Doc typoTj Holowaychukbefore adoptionc9268f2

lines 323–327why, one step back
323 <form method="post" action="/">
324 <input type="text" name="user[name]" />325 <input type="text" name="user[email]" />326 <input type="submit" value="Submit" />327 </form>

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 328–502why, one step back
328
329By default Express does not know what to do with this request body, so we should add the _bodyDecoder_ middleware, which will parse _application/x-www-form-urlencoded_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:330331 app.use(express.bodyDecoder());332333Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.334335 app.post('/', function(req, res){336 console.log(req.body.user);337 res.redirect('back');338 });339340When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyDecoder_ so that it can utilize it's _req.body_ containing the form values.341342 app.use(express.bodyDecoder());343 app.use(express.methodOverride());344345The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as _PUT_ and _DELETE_ can still be accessed by clients which can use them directly, although _methodOverride_ provides a great solution for forms. Below shows what the usage of _PUT_ might look like:346347 <form method="post" action="/">348 <input type="hidden" name="_method" value="put" />349 <input type="text" name="user[name]" />350 <input type="text" name="user[email]" />351 <input type="submit" value="Submit" /> 352 </form>353354 app.put('/', function(){355 console.log(req.body.user);356 res.redirect('back');357 });358359### Error Handling360361Express provides the _app.error()_ method which receives exceptions thrown within a route,362or passed to _next(err)_. Below is an example which serves different pages based on our363ad-hoc _NotFound_ exception:364365 function NotFound(msg){366 this.name = 'NotFound';367 Error.call(this, msg);368 Error.captureStackTrace(this, arguments.callee);369 }370371 sys.inherits(NotFound, Error);372373 app.get('/404', function(req, res){374 throw new NotFound;375 });376377 app.get('/500', function(req, res){378 throw new Error('keyboard cat!');379 });380381We can call _app.error()_ several times as shown below.382Here we check for an instanceof _NotFound_ and show the383404 page, or we pass on to the next error handler.384385Note that these handlers can be defined anywhere, as they386will be placed below the route handlers on _listen()_. This 387allows for definition within _configure()_ blocks so we can388handle exceptions in different ways based on the environment.389390 app.error(function(err, req, res, next){391 if (err instanceof NotFound) {392 res.render('404.jade');393 } else {394 next(err);395 }396 });397398Here we assume all errors as 500 for the simplicity of399this demo, however you can choose whatever you like400401 app.error(function(err, req, res){402 res.render('500.jade', {403 locals: {404 error: err405 } 406 });407 });408409Our apps could also utilize the Connect _errorHandler_ middleware410to report on exceptions. For example if we wish to output exceptions 411in "development" mode to _stderr_ we can use:412413 app.use(express.errorHandler({ dumpExceptions: true }));414415Also during development we may want fancy html pages to show exceptions416that are passed or thrown, so we can set _showStack_ to true:417418 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));419420The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_421is present, which is useful for developing apps that rely heavily on client-side JavaScript.422423### View Rendering424425View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name426of the module that will be required. For example the view _layout.ejs_ will427tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 428_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.429430Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,431and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 432the _body_ local variable in _layout.haml_.433434 app.get('/', function(req, res){435 res.render('index.haml', {436 locals: { title: 'My Site' }437 });438 });439440The new _view engine_ setting allows us to specify our default template engine,441so for example when using [Jade](http://github.com/visionmedia/jade) we could set:442443 app.set('view engine', 'jade');444445Allowing us to render with:446447 res.render('index');448449vs:450451 res.render('index.jade');452453When _view engine_ is set, extensions are entirely optional, however we can still454mix and match template engines:455456 res.render('another-page.ejs');457458Express 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:459460 app.set('view options', {461 layout: false462 });463464Which can then be overridden within the `res.render()` call if need be:465466 res.render('myview.ejs', { layout: true });467468When an alternate layout is required, we may also specify a path. For example if we have _view engine_ set to _jade_ and a file named _./views/mylayout.jade_ we can simply pass:469470 res.render('page', { layout: 'mylayout' });471472Otherwise we must specify the extension:473474 res.render('page', { layout: 'mylayout.jade' });475476These paths may also be absolute:477478 res.render('page', { layout: __dirname + '/../../mylayout.jade' });479480A good example of this is specifying custom _ejs_ opening and closing tags:481482 app.set('view options', {483 open: '{{',484 close: '}}'485 });486487### View Partials488489The Express view system has built-in support for partials and collections, which are490sort of "mini" views representing a document fragment. For example rather than iterating491in a view to display comments, we would use a partial with collection support:492493 partial('comment.haml', { collection: comments });494495To make things even less verbose we can assume the extension as _.haml_ when omitted,496however if we wished we could use an ejs partial, within a haml view for example.497498 partial('comment', { collection: comments });499500And once again even further, when rendering a collection we can simply pass501an array, if no other options are desired:502

More partial() docsTj Holowaychukbefore adoptione87d637

line 503why, one step back
503 partial('comment', comments);

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 504–510why, one step back
504
505When using the partial collection support a few "magic" variables are provided506for free:507508 * _firstInCollection_ True if this is the first object509 * _indexInCollection_ Index of the object in the collection510 * _lastInCollection_ True if this is the last object

More partial() docsTj Holowaychukbefore adoptione87d637

line 511why, one step back
511 * _collectionLength_ Length of the collection

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

line 512why, one step back
512

More partial() docsTj Holowaychukbefore adoptione87d637

line 513why, one step back
513For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).

more partial docsTj Holowaychukbefore adoptionf32279d

lines 514–515why, one step back
514
515NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead. For example do _not_ implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates.

More partial() docsTj Holowaychukbefore adoptione87d637

line 516why, one step back
516

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 517–523why, one step back
517### Template Engines
518519Below are a few template engines commonly used with Express:520521 * [Jade](http://jade-lang.com) haml.js successor522 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templates523 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript

Added CoffeeKup as a suggested template engine (let me know of others please :) )Tj Holowaychukbefore adoption687e435

line 524why, one step back
524 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating

Added link to node-jqtpl template engineTj Holowaychukbefore adoptioncccda60

line 525why, one step back
525 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 526–542why, one step back
526
527### Session Support528529Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieDecoder_ middleware place above it, which will parse and populate cookie data to _req.cookies_.530531 app.use(express.cookieDecoder());532 app.use(express.session());533534By default the _session_ middleware uses the memory store bundled with Connect, however many implementations exist. For example [connect-redis](http://github.com/visionmedia/connect-redis) supplies a [Redis](http://code.google.com/p/redis/) session store and can be used as shown below:535536 var RedisStore = require('connect-redis');537 app.use(express.cookieDecoder());538 app.use(express.session({ store: new RedisStore }));539540Now the _req.session_ and _req.sessionStore_ properties will be accessible to all routes and subsequent middleware. Properties on _req.session_ are automatically saved on a response, so for example if we wish to shopping cart data:541542 var RedisStore = require('connect-redis');

Doc typoTj Holowaychukbefore adoption7da2743

line 543why, one step back
543 app.use(express.bodyDecoder());

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 544–566why, one step back
544 app.use(express.cookieDecoder());
545 app.use(express.session({ store: new RedisStore }));546547 app.post('/add-to-cart', function(req, res){548 // Perhaps we posted several items with a form549 // (use the bodyDecoder() middleware for this)550 var items = req.body.items;551 req.session.items = items;552 res.redirect('back');553 });554555 app.get('/add-to-cart', function(req, res){556 // When redirected back to GET /add-to-cart557 // we could check req.session.items && req.session.items.length558 // to print out a message559 if (req.session.items && req.session.items.length) {560 req.flash('info', 'You have %s items in your cart', req.session.items.length);561 }562 res.render('shopping-cart');563 });564565The _req.session_ object also has methods such as _Session#touch()_, _Session#destroy()_, _Session#regenerate()_ among others to maintain and manipulate sessions. For more information view the [Connect Session](http://senchalabs.github.com/connect/session.html) documentation.566

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

lines 567–570why, one step back
567### Migration Guide
568569 Pre-beta Express developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.570

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 571–602why, one step back
571### req.header(key[, defaultValue])
572573Get the case-insensitive request header _key_, with optional _defaultValue_:574575 req.header('Host');576 req.header('host');577 req.header('Accept', '*/*');578579### req.accepts(type)580581Check if the _Accept_ header is present, and includes the given _type_.582583When the _Accept_ header is not present _true_ is returned. Otherwise584the given _type_ is matched by an exact match, and then subtypes. You585may pass the subtype such as "html" which is then converted internally586to "text/html" using the mime lookup table.587588 // Accept: text/html589 req.accepts('html');590 // => true591592 // Accept: text/*; application/json593 req.accepts('html');594 req.accepts('text/html');595 req.accepts('text/plain');596 req.accepts('application/json');597 // => true598599 req.accepts('image/png');600 req.accepts('png');601 // => false602

Added req.is() docsTj Holowaychukbefore adoption806aefa

lines 603–640why, one step back
603### req.is(type)
604605Check if the incoming request contains the _Content-Type_606header field, and it contains the give mime _type_.607 608 // With Content-Type: text/html; charset=utf-8609 req.is('html');610 req.is('text/html');611 // => true612 613 // When Content-Type is application/json614 req.is('json');615 req.is('application/json');616 // => true617 618 req.is('html');619 // => false620 621Ad-hoc callbacks can also be registered with Express, to perform622assertions again the request, for example if we need an expressive623way to check if our incoming request is an image, we can register _"an image"_624callback:625 626 app.is('an image', function(req){627 return 0 == req.headers['content-type'].indexOf('image');628 });629 630Now within our route callbacks, we can use to to assert content types631such as _"image/jpeg"_, _"image/png"_, etc.632 633 app.post('/image/upload', function(req, res, next){634 if (req.is('an image')) {635 // do something636 } else {637 next();638 }639 });640

More is() docsTj Holowaychukbefore adoption071ea95

lines 641–643why, one step back
641Keep in mind this method is _not_ limited to checking _Content-Type_, you
642can perform any request assertion you wish.643

Merge branch 'is'Tj Holowaychukbefore adoption7a71380

lines 644–651why, one step back
644Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:
645646 req.is('image/*');647648We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.649650 req.is('*/json');651

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 652–768why, one step back
652### req.param(name)
653654Return the value of param _name_ when present.655656 - Checks route placeholders (_req.params_), ex: /user/:id657 - Checks query string params (_req.query_), ex: ?id=12658 - Checks urlencoded body params (_req.body_), ex: id=12659660To utilize urlencoded request bodies, _req.body_661should be an object. This can be done by using662the _express.bodyDecoder_ middleware.663664### req.flash(type[, msg])665666Queue flash _msg_ of the given _type_.667668 req.flash('info', 'email sent');669 req.flash('error', 'email delivery failed');670 req.flash('info', 'email re-sent');671 // => 2672673 req.flash('info');674 // => ['email sent', 'email re-sent']675676 req.flash('info');677 // => []678679 req.flash();680 // => { error: ['email delivery failed'], info: [] }681682Flash notification message may also utilize formatters, by default only the %s string formatter is available:683684 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);685686### req.isXMLHttpRequest687688Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header689to see if it was issued by an _XMLHttpRequest_:690691 req.xhr692 req.isXMLHttpRequest693694### res.header(key[, val])695696Get or set the response header _key_.697698 res.header('Content-Length');699 // => undefined700701 res.header('Content-Length', 123);702 // => 123703704 res.header('Content-Length');705 // => 123706707### res.contentType(type)708709Sets the _Content-Type_ response header to the given _type_.710711 var filename = 'path/to/image.png';712 res.contentType(filename);713 // res.headers['Content-Type'] is now "image/png"714715### res.attachment([filename])716717Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.718719 res.attachment('path/to/my/image.png');720721### res.sendfile(path)722723Used by `res.download()` to transfer an arbitrary file. 724725 res.sendfile('path/to/my.file');726727This 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.728729 res.sendfile(path, function(err, path){730 if (err) {731 // handle the error732 } else {733 console.log('transferred %s', path);734 }735 });736737When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.738739### res.download(file[, filename])740741Transfer the given _file_ as an attachment with optional alternative _filename_.742743 res.download('path/to/image.png');744 res.download('path/to/image.png', 'foo.png');745746This is equivalent to:747748 res.attachment(file);749 res.sendfile(file);750751### res.send(body|status[, headers|status[, status]])752753The `res.send()` method is a high level response utility allowing you to pass754objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status755code based responses. The following are all valid uses:756757 res.send(); // 204758 res.send(new Buffer('wahoo'));759 res.send({ some: 'json' });760 res.send('<p>some html</p>');761 res.send('Sorry, cant find that', 404);762 res.send('text', { 'Content-Type': 'text/plain' }, 201);763 res.send(404);764765By default the _Content-Type_ response header is set, however if explicitly766assigned through `res.send()` or previously with `res.header()` or `res.contentType()`767it will not be set again.768

Make note in docs that res.send() is a convenience method, and should only be called once (ATM)Tj Holowaychukbefore adoptionbed5157

lines 769–770why, one step back
769Note that this method _end()_ the response, so you will want to use node's _res.writeHead()_ / _res.write()_ for multiple writes or streaming.
770

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 771–825why, one step back
771### res.redirect(url[, status])
772773Redirect to the given _url_ with a default response _status_ of 302.774775 res.redirect('/', 301);776 res.redirect('/account');777 res.redirect('http://google.com');778 res.redirect('home');779 res.redirect('back');780781Express supports "redirect mapping", which by default provides _home_, and _back_.782The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes783the "home" setting and defaults to "/".784785### res.cookie(name, val[, options])786787Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.788789 // "Remember me" for 15 minutes 790 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });791792To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:793794 app.use(express.cookieDecoder());795 796 app.get('/', function(req, res){797 // use req.cookies.rememberme798 });799800### res.clearCookie(name)801802Clear cookie _name_ by setting "expires" far in the past.803804 res.clearCookie('rememberme');805806### res.render(view[, options[, fn]])807808Render _view_ with the given _options_ and optional callback _fn_.809When a callback function is given a response will _not_ be made810automatically, however otherwise a response of _200_ and _text/html_ is given.811812 Most engines accept one or more of the following options,813 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:814815 - _scope_ Template evaluation context (value of _this_)816 - _locals_ Object containing local variables817 - _debug_ Output debugging information818 - _status_ Response status code, defaults to 200819 - _headers_ Response headers object820821### res.partial(view[, options])822823Render _view_ partial with the given _options_. This method is always available824to the view as a local variable.825

New partial() docsTj Holowaychukbefore adoption1c90332

lines 826–827why, one step back
826- _object_ the object named by _as_ or derived from the view name
827- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 828–837why, one step back
828 * as: 'something' will add the _something_ local variable
829 * as: this will use the collection value as the template context830 * as: global will merge the collection value's properties with _locals_831832- _collection_ Array of objects, the name is derived from the view name itself. 833 For example _video.html_ will have a object _video_ available to it.834835The following are equivalent, and the name of collection value when passed836to the partial will be _movie_ as derived from the name.837

More partial() docsTj Holowaychukbefore adoptione87d637

lines 838–839why, one step back
838 partial('theatre/movie.jade', { collection: movies });
839 partial('theatre/movie.jade', movies);

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 840–858why, one step back
840 partial('movie.jade', { collection: movies });
841 partial('movie.jade', movies);842 partial('movie', movies);843 // In view: movie.director844845To change the local from _movie_ to _video_ we can use the "as" option:846847 partial('movie', { collection: movies, as: 'video' });848 // In view: video.director849850Also we can make our movie the value of _this_ within our view so that instead851of _movie.director_ we could use _this.director_.852853 partial('movie', { collection: movies, as: this });854 // In view: this.director855856Another alternative is to "explode" the properties of the collection item into857pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:858

New partial() docsTj Holowaychukbefore adoption1c90332

line 859why, one step back
859 partial('movie', { collection: movies, as: global });

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

line 860why, one step back
860 // In view: director

New partial() docsTj Holowaychukbefore adoption1c90332

lines 861–879why, one step back
861
862This same logic applies to a single partial object usage:863864 partial('movie', { object: movie, as: this });865 // In view: this.director866867 partial('movie', { object: movie, as: global });868 // In view: director869870 partial('movie', { object: movie, as: 'video' });871 // In view: video.director872873 partial('movie', { object: movie });874 // In view: movie.director875876When a non-collection (does _not_ have _.length_) is passed as the second argument, it is assumed to be the _object_, after which the object's local variable name is derived from the view name:877878 partial('movie', movie);879 // => In view: movie.director

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 880–889why, one step back
880
881### app.set(name[, val])882883Apply an application level setting _name_ to _val_, or884get the value of _name_ when _val_ is not present:885886 app.set('views', __dirname + '/views');887 app.set('views');888 // => ...path...889

Settings docsTj Holowaychukbefore adoptione562adc

lines 890–894why, one step back
890Alternatively you may simply access the settings via _app.settings_:
891892 app.settings.views893 // => ...path...894

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 895–1023why, one step back
895### app.enable(name)
896897Enable the given setting _name_:898899 app.enable('some arbitrary setting');900 app.set('some arbitrary setting');901 // => true902903### app.disable(name)904905Disable the given setting _name_:906907 app.disable('some setting');908 app.set('some setting');909 // => false910911### app.configure(env|function[, function])912913Define a callback function for the given _env_ (or all environments) with callback _function_:914915 app.configure(function(){916 // executed for each env917 });918919 app.configure('development', function(){920 // executed for 'development' only921 });922923### app.redirect(name, val)924925For use with `res.redirect()` we can map redirects at the application level as shown below:926927 app.redirect('google', 'http://google.com');928929Now in a route we may call:930931 res.redirect('google');932933We may also map dynamic redirects:934935 app.redirect('comments', function(req, res){936 return '/post/' + req.params.id + '/comments';937 });938939So now we may do the following, and the redirect will dynamically adjust to940the context of the request. If we called this route with _GET /post/12_ our941redirect _Location_ would be _/post/12/comments_.942943 app.get('/post/:id', function(req, res){944 res.redirect('comments');945 });946947### app.error(function)948949Adds an error handler _function_ which will receive the exception as the first parameter as shown below.950Note that we may set several error handlers by making several calls to this method, however the handler951should call _next(err)_ if it does not wish to deal with the exception:952953 app.error(function(err, req, res, next){954 res.send(err.message, 500);955 });956957### app.helpers(obj)958959Registers static view helpers.960961 app.helpers({962 name: function(first, last){ return first + ', ' + last },963 firstName: 'tj',964 lastName: 'holowaychuk'965 });966967Our view could now utilize the _firstName_ and _lastName_ variables,968as well as the _name()_ function exposed.969970 <%= name(firstName, lastName) %>971972### app.dynamicHelpers(obj)973974Registers dynamic view helpers. Dynamic view helpers975are simply functions which accept _req_, _res_, and are976evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function977becomes the local variable it is associated with.978979 app.dynamicHelpers({980 session: function(req, res){981 return req.session;982 }983 });984985All views would now have _session_ available so that session data can be accessed via _session.name_ etc:986987 <%= session.name %>988989### app.mounted(fn)990991Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.992993 var app = express.createServer(),994 blog = express.createServer();995 996 blog.mounted(function(parent){997 // parent is app998 // "this" is blog999 });1000 1001 app.use(blog);10021003### app.register(ext, exports)10041005Register the given template engine _exports_1006as _ext_. For example we may wish to map ".html"1007files to jade:10081009 app.register('.html', require('jade'));10101011This is also useful for libraries that may not1012match extensions correctly. For example my haml.js1013library is installed from npm as "hamljs" so instead1014of layout.hamljs, we can register the engine as ".haml":10151016 app.register('.haml', require('haml-js'));10171018For engines that do not comply with the Express1019specification, we can also wrap their api this way.10201021 app.register('.foo', {1022 render: function(str, options) {1023 // perhaps their api is

Fix up app.register() docs. Closes #450Tj Holowaychukbefore adoption6ef6ba7

line 1024why, one step back
1024 // return foo.toHTML(str, options);

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 1025–1050why, one step back
1025 }
1026 });10271028### app.listen([port[, host]])10291030Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1031connections will be accepted via _INADDR_ANY_.10321033 app.listen();1034 app.listen(3000);1035 app.listen(3000, 'n.n.n.n');10361037The _port_ argument may also be a string representing the path to a unix domain socket:10381039 app.listen('/tmp/express.sock');10401041Then try it out:10421043 $ telnet /tmp/express.sock1044 GET / HTTP/1.110451046 HTTP/1.1 200 OK1047 Content-Type: text/plain1048 Content-Length: 111049 1050 Hello World