Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,092 lines · 36.8 KiB · Markdown

Last changed by

Added docs for app.{disabled,enabled}()Tj Holowaychukbefore adoptiona9253a2

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–422why, 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.422

Route precondition docsTj Holowaychukbefore adoptionfd2f67b

lines 423–458why, one step back
423### Route Preconditions
424425Route placeholder pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_,we might typically do something like below:426427 app.get('/user/:userId', function(req, res, next){428 User.get(req.params.userId, function(err, user){429 if (err) return next(err);430 res.send('user ' + user.name);431 });432 }); 433434With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.435436 app.param('userId', function(req, res, next, id){437 User.get(id, function(err, user){438 if (err) return next(err);439 if (!user) return next(new Error('failed to find user'));440 req.user = user;441 next();442 });443 });444445Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:446447 app.get('/user/:userId', function(req, res){448 res.send('user ' + req.user.name);449 });450451For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to _next(err)_.452453 app.param('number', function(n){ return parseInt(n, 10); });454455We may also apply the same callback to several placeholders, for example a route GET _/commits/:from-:to_ are both numbers, so we may define them as an array:456457 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });458

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 459–538why, one step back
459### View Rendering
460461View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name462of the module that will be required. For example the view _layout.ejs_ will463tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 464_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.465466Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,467and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 468the _body_ local variable in _layout.haml_.469470 app.get('/', function(req, res){471 res.render('index.haml', {472 locals: { title: 'My Site' }473 });474 });475476The new _view engine_ setting allows us to specify our default template engine,477so for example when using [Jade](http://github.com/visionmedia/jade) we could set:478479 app.set('view engine', 'jade');480481Allowing us to render with:482483 res.render('index');484485vs:486487 res.render('index.jade');488489When _view engine_ is set, extensions are entirely optional, however we can still490mix and match template engines:491492 res.render('another-page.ejs');493494Express 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:495496 app.set('view options', {497 layout: false498 });499500Which can then be overridden within the `res.render()` call if need be:501502 res.render('myview.ejs', { layout: true });503504When 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:505506 res.render('page', { layout: 'mylayout' });507508Otherwise we must specify the extension:509510 res.render('page', { layout: 'mylayout.jade' });511512These paths may also be absolute:513514 res.render('page', { layout: __dirname + '/../../mylayout.jade' });515516A good example of this is specifying custom _ejs_ opening and closing tags:517518 app.set('view options', {519 open: '{{',520 close: '}}'521 });522523### View Partials524525The Express view system has built-in support for partials and collections, which are526sort of "mini" views representing a document fragment. For example rather than iterating527in a view to display comments, we would use a partial with collection support:528529 partial('comment.haml', { collection: comments });530531To make things even less verbose we can assume the extension as _.haml_ when omitted,532however if we wished we could use an ejs partial, within a haml view for example.533534 partial('comment', { collection: comments });535536And once again even further, when rendering a collection we can simply pass537an array, if no other options are desired:538

More partial() docsTj Holowaychukbefore adoptione87d637

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 540–546why, one step back
540
541When using the partial collection support a few "magic" variables are provided542for free:543544 * _firstInCollection_ True if this is the first object545 * _indexInCollection_ Index of the object in the collection546 * _lastInCollection_ True if this is the last object

More partial() docsTj Holowaychukbefore adoptione87d637

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

line 548why, one step back
548

More partial() docsTj Holowaychukbefore adoptione87d637

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

more partial docsTj Holowaychukbefore adoptionf32279d

lines 550–551why, one step back
550
551NOTE: 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 552why, one step back
552

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 553–559why, one step back
553### Template Engines
554555Below are a few template engines commonly used with Express:556557 * [Jade](http://jade-lang.com) haml.js successor558 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templates559 * [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 560why, one step back
560 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating

Added link to node-jqtpl template engineTj Holowaychukbefore adoptioncccda60

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 562–578why, one step back
562
563### Session Support564565Sessions 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_.566567 app.use(express.cookieDecoder());568 app.use(express.session());569570By 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:571572 var RedisStore = require('connect-redis');573 app.use(express.cookieDecoder());574 app.use(express.session({ store: new RedisStore }));575576Now 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:577578 var RedisStore = require('connect-redis');

Doc typoTj Holowaychukbefore adoption7da2743

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 580–602why, one step back
580 app.use(express.cookieDecoder());
581 app.use(express.session({ store: new RedisStore }));582583 app.post('/add-to-cart', function(req, res){584 // Perhaps we posted several items with a form585 // (use the bodyDecoder() middleware for this)586 var items = req.body.items;587 req.session.items = items;588 res.redirect('back');589 });590591 app.get('/add-to-cart', function(req, res){592 // When redirected back to GET /add-to-cart593 // we could check req.session.items && req.session.items.length594 // to print out a message595 if (req.session.items && req.session.items.length) {596 req.flash('info', 'You have %s items in your cart', req.session.items.length);597 }598 res.render('shopping-cart');599 });600601The _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.602

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 607–638why, one step back
607### req.header(key[, defaultValue])
608609Get the case-insensitive request header _key_, with optional _defaultValue_:610611 req.header('Host');612 req.header('host');613 req.header('Accept', '*/*');614615### req.accepts(type)616617Check if the _Accept_ header is present, and includes the given _type_.618619When the _Accept_ header is not present _true_ is returned. Otherwise620the given _type_ is matched by an exact match, and then subtypes. You621may pass the subtype such as "html" which is then converted internally622to "text/html" using the mime lookup table.623624 // Accept: text/html625 req.accepts('html');626 // => true627628 // Accept: text/*; application/json629 req.accepts('html');630 req.accepts('text/html');631 req.accepts('text/plain');632 req.accepts('application/json');633 // => true634635 req.accepts('image/png');636 req.accepts('png');637 // => false638

Added req.is() docsTj Holowaychukbefore adoption806aefa

lines 639–676why, one step back
639### req.is(type)
640641Check if the incoming request contains the _Content-Type_642header field, and it contains the give mime _type_.643 644 // With Content-Type: text/html; charset=utf-8645 req.is('html');646 req.is('text/html');647 // => true648 649 // When Content-Type is application/json650 req.is('json');651 req.is('application/json');652 // => true653 654 req.is('html');655 // => false656 657Ad-hoc callbacks can also be registered with Express, to perform658assertions again the request, for example if we need an expressive659way to check if our incoming request is an image, we can register _"an image"_660callback:661 662 app.is('an image', function(req){663 return 0 == req.headers['content-type'].indexOf('image');664 });665 666Now within our route callbacks, we can use to to assert content types667such as _"image/jpeg"_, _"image/png"_, etc.668 669 app.post('/image/upload', function(req, res, next){670 if (req.is('an image')) {671 // do something672 } else {673 next();674 }675 });676

More is() docsTj Holowaychukbefore adoption071ea95

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

Merge branch 'is'Tj Holowaychukbefore adoption7a71380

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 688–804why, one step back
688### req.param(name)
689690Return the value of param _name_ when present.691692 - Checks route placeholders (_req.params_), ex: /user/:id693 - Checks query string params (_req.query_), ex: ?id=12694 - Checks urlencoded body params (_req.body_), ex: id=12695696To utilize urlencoded request bodies, _req.body_697should be an object. This can be done by using698the _express.bodyDecoder_ middleware.699700### req.flash(type[, msg])701702Queue flash _msg_ of the given _type_.703704 req.flash('info', 'email sent');705 req.flash('error', 'email delivery failed');706 req.flash('info', 'email re-sent');707 // => 2708709 req.flash('info');710 // => ['email sent', 'email re-sent']711712 req.flash('info');713 // => []714715 req.flash();716 // => { error: ['email delivery failed'], info: [] }717718Flash notification message may also utilize formatters, by default only the %s string formatter is available:719720 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);721722### req.isXMLHttpRequest723724Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header725to see if it was issued by an _XMLHttpRequest_:726727 req.xhr728 req.isXMLHttpRequest729730### res.header(key[, val])731732Get or set the response header _key_.733734 res.header('Content-Length');735 // => undefined736737 res.header('Content-Length', 123);738 // => 123739740 res.header('Content-Length');741 // => 123742743### res.contentType(type)744745Sets the _Content-Type_ response header to the given _type_.746747 var filename = 'path/to/image.png';748 res.contentType(filename);749 // res.headers['Content-Type'] is now "image/png"750751### res.attachment([filename])752753Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.754755 res.attachment('path/to/my/image.png');756757### res.sendfile(path)758759Used by `res.download()` to transfer an arbitrary file. 760761 res.sendfile('path/to/my.file');762763This 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.764765 res.sendfile(path, function(err, path){766 if (err) {767 // handle the error768 } else {769 console.log('transferred %s', path);770 }771 });772773When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.774775### res.download(file[, filename])776777Transfer the given _file_ as an attachment with optional alternative _filename_.778779 res.download('path/to/image.png');780 res.download('path/to/image.png', 'foo.png');781782This is equivalent to:783784 res.attachment(file);785 res.sendfile(file);786787### res.send(body|status[, headers|status[, status]])788789The `res.send()` method is a high level response utility allowing you to pass790objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status791code based responses. The following are all valid uses:792793 res.send(); // 204794 res.send(new Buffer('wahoo'));795 res.send({ some: 'json' });796 res.send('<p>some html</p>');797 res.send('Sorry, cant find that', 404);798 res.send('text', { 'Content-Type': 'text/plain' }, 201);799 res.send(404);800801By default the _Content-Type_ response header is set, however if explicitly802assigned through `res.send()` or previously with `res.header()` or `res.contentType()`803it will not be set again.804

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

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 807–861why, one step back
807### res.redirect(url[, status])
808809Redirect to the given _url_ with a default response _status_ of 302.810811 res.redirect('/', 301);812 res.redirect('/account');813 res.redirect('http://google.com');814 res.redirect('home');815 res.redirect('back');816817Express supports "redirect mapping", which by default provides _home_, and _back_.818The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes819the "home" setting and defaults to "/".820821### res.cookie(name, val[, options])822823Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.824825 // "Remember me" for 15 minutes 826 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });827828To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:829830 app.use(express.cookieDecoder());831 832 app.get('/', function(req, res){833 // use req.cookies.rememberme834 });835836### res.clearCookie(name)837838Clear cookie _name_ by setting "expires" far in the past.839840 res.clearCookie('rememberme');841842### res.render(view[, options[, fn]])843844Render _view_ with the given _options_ and optional callback _fn_.845When a callback function is given a response will _not_ be made846automatically, however otherwise a response of _200_ and _text/html_ is given.847848 Most engines accept one or more of the following options,849 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:850851 - _scope_ Template evaluation context (value of _this_)852 - _locals_ Object containing local variables853 - _debug_ Output debugging information854 - _status_ Response status code, defaults to 200855 - _headers_ Response headers object856857### res.partial(view[, options])858859Render _view_ partial with the given _options_. This method is always available860to the view as a local variable.861

New partial() docsTj Holowaychukbefore adoption1c90332

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 864–873why, one step back
864 * as: 'something' will add the _something_ local variable
865 * as: this will use the collection value as the template context866 * as: global will merge the collection value's properties with _locals_867868- _collection_ Array of objects, the name is derived from the view name itself. 869 For example _video.html_ will have a object _video_ available to it.870871The following are equivalent, and the name of collection value when passed872to the partial will be _movie_ as derived from the name.873

More partial() docsTj Holowaychukbefore adoptione87d637

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 876–894why, one step back
876 partial('movie.jade', { collection: movies });
877 partial('movie.jade', movies);878 partial('movie', movies);879 // In view: movie.director880881To change the local from _movie_ to _video_ we can use the "as" option:882883 partial('movie', { collection: movies, as: 'video' });884 // In view: video.director885886Also we can make our movie the value of _this_ within our view so that instead887of _movie.director_ we could use _this.director_.888889 partial('movie', { collection: movies, as: this });890 // In view: this.director891892Another alternative is to "explode" the properties of the collection item into893pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:894

New partial() docsTj Holowaychukbefore adoption1c90332

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

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

New partial() docsTj Holowaychukbefore adoption1c90332

lines 897–915why, one step back
897
898This same logic applies to a single partial object usage:899900 partial('movie', { object: movie, as: this });901 // In view: this.director902903 partial('movie', { object: movie, as: global });904 // In view: director905906 partial('movie', { object: movie, as: 'video' });907 // In view: video.director908909 partial('movie', { object: movie });910 // In view: movie.director911912When 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:913914 partial('movie', movie);915 // => In view: movie.director

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 916–925why, one step back
916
917### app.set(name[, val])918919Apply an application level setting _name_ to _val_, or920get the value of _name_ when _val_ is not present:921922 app.set('views', __dirname + '/views');923 app.set('views');924 // => ...path...925

Settings docsTj Holowaychukbefore adoptione562adc

lines 926–930why, one step back
926Alternatively you may simply access the settings via _app.settings_:
927928 app.settings.views929 // => ...path...930

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 931–938why, one step back
931### app.enable(name)
932933Enable the given setting _name_:934935 app.enable('some arbitrary setting');936 app.set('some arbitrary setting');937 // => true938

Added docs for app.{disabled,enabled}()Tj Holowaychukbefore adoptiona9253a2

lines 939–941why, one step back
939 app.enabled('some arbitrary setting');
940 // => true941

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 942–947why, one step back
942### app.disable(name)
943944Disable the given setting _name_:945946 app.disable('some setting');947 app.set('some setting');

Added docs for app.{disabled,enabled}()Tj Holowaychukbefore adoptiona9253a2

lines 948–950why, one step back
948 // => false
949 950 app.disabled('some setting');

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 951–1065why, one step back
951 // => false
952953### app.configure(env|function[, function])954955Define a callback function for the given _env_ (or all environments) with callback _function_:956957 app.configure(function(){958 // executed for each env959 });960961 app.configure('development', function(){962 // executed for 'development' only963 });964965### app.redirect(name, val)966967For use with `res.redirect()` we can map redirects at the application level as shown below:968969 app.redirect('google', 'http://google.com');970971Now in a route we may call:972973 res.redirect('google');974975We may also map dynamic redirects:976977 app.redirect('comments', function(req, res){978 return '/post/' + req.params.id + '/comments';979 });980981So now we may do the following, and the redirect will dynamically adjust to982the context of the request. If we called this route with _GET /post/12_ our983redirect _Location_ would be _/post/12/comments_.984985 app.get('/post/:id', function(req, res){986 res.redirect('comments');987 });988989### app.error(function)990991Adds an error handler _function_ which will receive the exception as the first parameter as shown below.992Note that we may set several error handlers by making several calls to this method, however the handler993should call _next(err)_ if it does not wish to deal with the exception:994995 app.error(function(err, req, res, next){996 res.send(err.message, 500);997 });998999### app.helpers(obj)10001001Registers static view helpers.10021003 app.helpers({1004 name: function(first, last){ return first + ', ' + last },1005 firstName: 'tj',1006 lastName: 'holowaychuk'1007 });10081009Our view could now utilize the _firstName_ and _lastName_ variables,1010as well as the _name()_ function exposed.10111012 <%= name(firstName, lastName) %>10131014### app.dynamicHelpers(obj)10151016Registers dynamic view helpers. Dynamic view helpers1017are simply functions which accept _req_, _res_, and are1018evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1019becomes the local variable it is associated with.10201021 app.dynamicHelpers({1022 session: function(req, res){1023 return req.session;1024 }1025 });10261027All views would now have _session_ available so that session data can be accessed via _session.name_ etc:10281029 <%= session.name %>10301031### app.mounted(fn)10321033Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.10341035 var app = express.createServer(),1036 blog = express.createServer();1037 1038 blog.mounted(function(parent){1039 // parent is app1040 // "this" is blog1041 });1042 1043 app.use(blog);10441045### app.register(ext, exports)10461047Register the given template engine _exports_1048as _ext_. For example we may wish to map ".html"1049files to jade:10501051 app.register('.html', require('jade'));10521053This is also useful for libraries that may not1054match extensions correctly. For example my haml.js1055library is installed from npm as "hamljs" so instead1056of layout.hamljs, we can register the engine as ".haml":10571058 app.register('.haml', require('haml-js'));10591060For engines that do not comply with the Express1061specification, we can also wrap their api this way.10621063 app.register('.foo', {1064 render: function(str, options) {1065 // perhaps their api is

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

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

Added guillermo to package.json contribTj Holowaychukbefore adoptionbaca8f0

lines 1067–1092why, one step back
1067 }
1068 });10691070### app.listen([port[, host]])10711072Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1073connections will be accepted via _INADDR_ANY_.10741075 app.listen();1076 app.listen(3000);1077 app.listen(3000, 'n.n.n.n');10781079The _port_ argument may also be a string representing the path to a unix domain socket:10801081 app.listen('/tmp/express.sock');10821083Then try it out:10841085 $ telnet /tmp/express.sock1086 GET / HTTP/1.110871088 HTTP/1.1 200 OK1089 Content-Type: text/plain1090 Content-Length: 111091 1092 Hello World