Skip to content
Myr

guide.md

This file

Path

docs/guide.md

974 lines · 31.7 KiB · Markdown

Last changed by

Misc doc changesTj Holowaychukbefore adoptiond6cfcbe

History of this file

Take it

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 1–44why, one step back
1
2### Installation34curl:56 $ curl -# http://expressjs.com/install.sh | sh78npm: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_.41Note 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.4344 app.configure(function(){

Updated docsTj Holowaychukbefore adoption344218f

lines 45–46why, one step back
45 app.use(express.methodOverride());
46 app.use(express.bodyDecoder());

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 47why, one step back
47 app.use(app.router);

Updated docsTj Holowaychukbefore adoption344218f

line 48why, one step back
48 app.use(express.staticProvider(__dirname + '/public'));

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

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

Updated docsTj Holowaychukbefore adoption344218f

line 52why, one step back
52 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 53–55why, one step back
53 });
54 55 app.configure('production', function(){

Updated docsTj Holowaychukbefore adoption344218f

line 56why, one step back
56 app.use(express.errorHandler());

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 57–72why, one step back
57 });
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 });72

Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab

line 73why, one step back
73To alter the environment we can set the _NODE_ENV_ environment variable, for example:

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 74why, one step back
74

Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab

line 75why, one step back
75 $ NODE_ENV=production node app.js

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 76why, one step back
76

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

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 79–86why, one step back
79### Settings
8081Express supports the following settings out of the box:8283 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_84 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.85 * _views_ Root views directory defaulting to **CWD/views**86 * _view engine_ Default view engine name for views rendered without extensions

Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c

line 87why, one step back
87 * _view options_ An object specifying global view options

Merge branch 'downloads'Tj Holowaychukbefore adoption949803d

lines 88–89why, one step back
88 * _partials_ Root view partials directory defaulting to _views_/partials.
89 * _stream threshold_ Bytesize indicating when a file should be streamed for _res.sendfile()_ using _fs.ReadStream()_ and _sys.pump()_.

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 90–159why, one step back
90
91### Routing9293Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.94For example we may want to render a user's account for the path _/user/12_, this95can be done by defining the route below. The values associated to the named placeholders 96are available as `req.params`.9798 app.get('/user/:id', function(req, res){99 res.send('user ' + req.params.id);100 });101102A route is simple a string which is compiled to a _RegExp_ internally. For example103when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:104105 \/user\/([^\/]+)\/?106107Regular expression literals may also be passed for complex uses. Since capture108groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.109110 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){111 res.send(req.params);112 });113114Curl requests against the previously defined route:115116 $ curl http://dev:3000/user117 [null,null]118 $ curl http://dev:3000/users119 [null,null]120 $ curl http://dev:3000/users/1121 ["1",null]122 $ curl http://dev:3000/users/1..15123 ["1","15"]124125Below are some route examples, and the associated paths that they126may consume:127128 "/user/:id"129 /user/12130131 "/users/:id?"132 /users/5133 /users134135 "/files/*"136 /files/jquery.js137 /files/javascripts/jquery.js138139 "/file/*.*"140 /files/jquery.js141 /files/javascripts/jquery.js142 143 "/user/:id/:operation?"144 /user/1145 /user/1/edit146 147 "/products.:format"148 /products.json149 /products.xml150151 "/products.:format?"152 /products.json153 /products.xml154 /products155156### Passing Route Control157158We may pass control to the next _matching_ route, by calling the _third_ argument,159the _next()_ function. When a match cannot be made, control is passed back to Connect,

Added route-middleware exampleTj Holowaychukbefore adoption4983e96

line 160why, one step back
160and 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()_.

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 161why, one step back
161

Fixed doc typoTj Holowaychukbefore adoption47ff7d9

line 162why, one step back
162 app.get('/users/:id?', function(req, res, next){

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 163–173why, one step back
163 var id = req.params.id;
164 if (id) {165 // do something166 } else {167 next();168 }169 });170 171 app.get('/users', function(req, res){172 // do something else173 });

Added route-middleware exampleTj Holowaychukbefore adoption4983e96

line 174why, one step back
174

Ordering docsTj Holowaychukbefore adoption296f127

lines 175–199why, one step back
175### Middleware
176177Middleware via [Connect](http://github.com/senchalabs/connect) can be178passed to _express.createServer()_ as you would with a regular Connect server. For example:179180 var express = require('express');181182 var app = express.createServer(183 express.logger(),184 express.bodyDecoder()185 );186187Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:188189 app.use(express.logger({ format: ':method :uri' }));190191Typically with connect middleware you would _require('connect')_ like so:192193 var connect = require('connect');194 app.use(connect.logger());195196This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:197198 app.use(express.logger());199

Added route-middleware exampleTj Holowaychukbefore adoption4983e96

lines 200–202why, one step back
200### Route Middleware
201202Routes 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.

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 203why, one step back
203

Fixed docsTj Holowaychukbefore adoptioncef14ca

line 204why, one step back
204Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user.

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

line 205why, one step back
205

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 206–207why, one step back
206 app.get('/user/:id', function(req, res, next){
207 loadUser(req.params.id, function(err, user){

Doc cleanupTj Holowaychukbefore adoptionb083aed

lines 208–209why, one step back
208 if (err) return next(err);
209 res.send('Viewing user ' + user.name);

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 210–211why, one step back
210 });
211 });

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

lines 212–214why, one step back
212
213To 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. 214

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 215–228why, one step back
215 function loadUser(req, res, next) {
216 // You would fetch your user from the db217 var user = users[req.params.id];218 if (user) {219 req.user = user;220 next();221 } else {222 next(new Error('Failed to load user ' + req.params.id));223 }224 }225 226 app.get('/user/:id', loadUser, function(req, res){227 res.send('Viewing user ' + req.user.name);228 });

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

lines 229–231why, one step back
229
230Multiple 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.231

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 232–233why, one step back
232 function andRestrictToSelf(req, res, next) {
233 req.authenticatedUser.id == req.user.id

Doc cleanupTj Holowaychukbefore adoptionb083aed

lines 234–235why, one step back
234 ? next()
235 : next(new Error('Unauthorized'));

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 236–240why, one step back
236 }
237 238 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){239 res.send('Editing user ' + req.user.name);240 });

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

line 241why, one step back
241

Fixed docsTj Holowaychukbefore adoptioncef14ca

line 242why, one step back
242Keeping 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.

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

line 243why, one step back
243

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 244–246why, one step back
244 function andRestrictTo(role) {
245 return function(req, res, next) {246 req.authenticatedUser.role == role

Doc cleanupTj Holowaychukbefore adoptionb083aed

lines 247–248why, one step back
247 ? next()
248 : next(new Error('Unauthorized'));

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 249–255why, one step back
249 }
250 }251 252 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){253 res.send('Deleted user ' + req.user.name);254 });255

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

lines 256–257why, one step back
256Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.
257

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 258–267why, one step back
258 var a = [middleware1, middleware2]
259 , b = [middleware3, middleware4]260 , all = [a, b];261 262 app.get('/foo', a, function(){});263 app.get('/bar', a, function(){});264 265 app.get('/', a, middleware3, middleware4, function(){});266 app.get('/', a, b, function(){});267 app.get('/', all, function(){});

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

lines 268–270why, one step back
268
269For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.270

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 271–276why, one step back
271### HTTP Methods
272273We 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.274275 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.276

Doc typoTj Holowaychukbefore adoptionc9268f2

lines 277–281why, one step back
277 <form method="post" action="/">
278 <input type="text" name="user[name]" />279 <input type="text" name="user[email]" />280 <input type="submit" value="Submit" />281 </form>

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 282–311why, one step back
282
283By 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:284285 app.use(express.bodyDecoder());286287Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.288289 app.post('/', function(req, res){290 console.log(req.body.user);291 res.redirect('back');292 });293294When 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.295296 app.use(express.bodyDecoder());297 app.use(express.methodOverride());298299The 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:300301 <form method="post" action="/">302 <input type="hidden" name="_method" value="put" />303 <input type="text" name="user[name]" />304 <input type="text" name="user[email]" />305 <input type="submit" value="Submit" /> 306 </form>307308 app.put('/', function(){309 console.log(req.body.user);310 res.redirect('back');311 });

Updated docsTj Holowaychukbefore adoption344218f

line 312why, one step back
312

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 313–338why, one step back
313### Error Handling
314315Express provides the _app.error()_ method which receives exceptions thrown within a route,316or passed to _next(err)_. Below is an example which serves different pages based on our317ad-hoc _NotFound_ exception:318319 function NotFound(msg){320 this.name = 'NotFound';321 Error.call(this, msg);322 Error.captureStackTrace(this, arguments.callee);323 }324325 sys.inherits(NotFound, Error);326327 app.get('/404', function(req, res){328 throw new NotFound;329 });330331 app.get('/500', function(req, res){332 throw new Error('keyboard cat!');333 });334335We can call _app.error()_ several times as shown below.336Here we check for an instanceof _NotFound_ and show the337404 page, or we pass on to the next error handler.338

Merge branch 'fix-error'Tj Holowaychukbefore adoption498115d

lines 339–343why, one step back
339Note that these handlers can be defined anywhere, as they
340will be placed below the route handlers on _listen()_. This 341allows for definition within _configure()_ blocks so we can342handle exceptions in different ways based on the environment.343

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 344–366why, one step back
344 app.error(function(err, req, res, next){
345 if (err instanceof NotFound) {346 res.render('404.jade');347 } else {348 next(err);349 }350 });351352Here we assume all errors as 500 for the simplicity of353this demo, however you can choose whatever you like354355 app.error(function(err, req, res){356 res.render('500.jade', {357 locals: {358 error: err359 } 360 });361 });362363Our apps could also utilize the Connect _errorHandler_ middleware364to report on exceptions. For example if we wish to output exceptions 365in "development" mode to _stderr_ we can use:366

Updated docsTj Holowaychukbefore adoption344218f

line 367why, one step back
367 app.use(express.errorHandler({ dumpExceptions: true }));

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 368–371why, one step back
368
369Also during development we may want fancy html pages to show exceptions370that are passed or thrown, so we can set _showStack_ to true:371

Updated docsTj Holowaychukbefore adoption344218f

line 372why, one step back
372 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 373–380why, one step back
373
374The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_375is present, which is useful for developing apps that rely heavily on client-side JavaScript.376377### View Rendering378379View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name380of the module that will be required. For example the view _layout.ejs_ will

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 381–382why, one step back
381tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however
382_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 383–410why, one step back
383
384Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,385and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 386the _body_ local variable in _layout.haml_.387388 app.get('/', function(req, res){389 res.render('index.haml', {390 locals: { title: 'My Site' }391 });392 });393394The new _view engine_ setting allows us to specify our default template engine,395so for example when using [Jade](http://github.com/visionmedia/jade) we could set:396397 app.set('view engine', 'jade');398399Allowing us to render with:400401 res.render('index');402403vs:404405 res.render('index.jade');406407When _view engine_ is set, extensions are entirely optional, however we can still408mix and match template engines:409410 res.render('another-page.ejs');

Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c

lines 411–421why, one step back
411
412Express 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:413414 app.set('view options', {415 layout: false416 });417418Which can then be overridden within the `res.render()` call if need be:419420 res.render('myview.ejs', { layout: true });421

Docs for layout optionTj Holowaychukbefore adoption0a96621

lines 422–433why, one step back
422When 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:
423424 res.render('page', { layout: 'mylayout' });425426Otherwise we must specify the extension:427428 res.render('page', { layout: 'mylayout.jade' });429430These paths may also be absolute:431432 res.render('page', { layout: __dirname + '/../../mylayout.jade' });433

Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c

lines 434–439why, one step back
434A good example of this is specifying custom _ejs_ opening and closing tags:
435436 app.set('view options', {437 open: '{{',438 close: '}}'439 });

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 440–456why, one step back
440
441### View Partials442443The Express view system has built-in support for partials and collections, which are444sort of "mini" views representing a document fragment. For example rather than iterating445in a view to display comments, we would use a partial with collection support:446447 partial('comment.haml', { collection: comments });448449To make things even less verbose we can assume the extension as _.haml_ when omitted,450however if we wished we could use an ejs partial, within a haml view for example.451452 partial('comment', { collection: comments });453454And once again even further, when rendering a collection we can simply pass455an array, if no other options are desired:456

More partial() docsTj Holowaychukbefore adoptione87d637

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 458–463why, one step back
458
459When using the partial collection support a few "magic" variables are provided460for free:461462 * _firstInCollection_ True if this is the first object463 * _indexInCollection_ Index of the object in the collection

Doc typosTj Holowaychukbefore adoption02b4ec0

line 464why, one step back
464 * _lastInCollection_ True if this is the last object

More partial() docsTj Holowaychukbefore adoptione87d637

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 466why, one step back
466

More partial() docsTj Holowaychukbefore adoptione87d637

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 469–472why, one step back
469### Template Engines
470471Below are a few template engines commonly used with Express:472

Doc typosTj Holowaychukbefore adoption02b4ec0

lines 473–474why, one step back
473 * [Jade](http://jade-lang.com) haml.js successor
474 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templates

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 475why, one step back
475 * [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 476why, one step back
476 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating

Added session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe

lines 477–489why, one step back
477
478### Session Support479480Sessions 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_.481482 app.use(express.cookieDecoder());483 app.use(express.session());484485By 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:486487 var RedisStore = require('connect-redis');488 app.use(express.cookieDecoder());489 app.use(express.session({ store: new RedisStore }));

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

line 490why, one step back
490

More session docsTj Holowaychukbefore adoption4bc8a86

lines 491–493why, one step back
491Now 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:
492493 var RedisStore = require('connect-redis');

Doc typoTj Holowaychukbefore adoption7da2743

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

More session docsTj Holowaychukbefore adoption4bc8a86

lines 495–517why, one step back
495 app.use(express.cookieDecoder());
496 app.use(express.session({ store: new RedisStore }));497498 app.post('/add-to-cart', function(req, res){499 // Perhaps we posted several items with a form500 // (use the bodyDecoder() middleware for this)501 var items = req.body.items;502 req.session.items = items;503 res.redirect('back');504 });505506 app.get('/add-to-cart', function(req, res){507 // When redirected back to GET /add-to-cart508 // we could check req.session.items && req.session.items.length509 // to print out a message510 if (req.session.items && req.session.items.length) {511 req.flash('info', 'You have %s items in your cart', req.session.items.length);512 }513 res.render('shopping-cart');514 });515516The _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.517

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 522–553why, one step back
522### req.header(key[, defaultValue])
523524Get the case-insensitive request header _key_, with optional _defaultValue_:525526 req.header('Host');527 req.header('host');528 req.header('Accept', '*/*');529530### req.accepts(type)531532Check if the _Accept_ header is present, and includes the given _type_.533534When the _Accept_ header is not present _true_ is returned. Otherwise535the given _type_ is matched by an exact match, and then subtypes. You536may pass the subtype such as "html" which is then converted internally537to "text/html" using the mime lookup table.538539 // Accept: text/html540 req.accepts('html');541 // => true542543 // Accept: text/*; application/json544 req.accepts('html');545 req.accepts('text/html');546 req.accepts('text/plain');547 req.accepts('application/json');548 // => true549550 req.accepts('image/png');551 req.accepts('png');552 // => false553

Added req.is() docsTj Holowaychukbefore adoption806aefa

lines 554–591why, one step back
554### req.is(type)
555556Check if the incoming request contains the _Content-Type_557header field, and it contains the give mime _type_.558 559 // With Content-Type: text/html; charset=utf-8560 req.is('html');561 req.is('text/html');562 // => true563 564 // When Content-Type is application/json565 req.is('json');566 req.is('application/json');567 // => true568 569 req.is('html');570 // => false571 572Ad-hoc callbacks can also be registered with Express, to perform573assertions again the request, for example if we need an expressive574way to check if our incoming request is an image, we can register _"an image"_575callback:576 577 app.is('an image', function(req){578 return 0 == req.headers['content-type'].indexOf('image');579 });580 581Now within our route callbacks, we can use to to assert content types582such as _"image/jpeg"_, _"image/png"_, etc.583 584 app.post('/image/upload', function(req, res, next){585 if (req.is('an image')) {586 // do something587 } else {588 next();589 }590 });591

More is() docsTj Holowaychukbefore adoption071ea95

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

Merge branch 'is'Tj Holowaychukbefore adoption7a71380

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 603–612why, one step back
603### req.param(name)
604605Return the value of param _name_ when present.606607 - Checks route placeholders (_req.params_), ex: /user/:id608 - Checks query string params (_req.query_), ex: ?id=12609 - Checks urlencoded body params (_req.body_), ex: id=12610611To utilize urlencoded request bodies, _req.body_612should be an object. This can be done by using

Updated docsTj Holowaychukbefore adoption344218f

line 613why, one step back
613the _express.bodyDecoder_ middleware.

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 614–632why, one step back
614
615### req.flash(type[, msg])616617Queue flash _msg_ of the given _type_.618619 req.flash('info', 'email sent');620 req.flash('error', 'email delivery failed');621 req.flash('info', 'email re-sent');622 // => 2623624 req.flash('info');625 // => ['email sent', 'email re-sent']626627 req.flash('info');628 // => []629630 req.flash();631 // => { error: ['email delivery failed'], info: [] }632

Added flash formatter docsTj Holowaychukbefore adoptionf16978d

lines 633–636why, one step back
633Flash notification message may also utilize formatters, by default only the %s string formatter is available:
634635 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);636

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 637–677why, one step back
637### req.isXMLHttpRequest
638639Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header640to see if it was issued by an _XMLHttpRequest_:641642 req.xhr643 req.isXMLHttpRequest644645### res.header(key[, val])646647Get or set the response header _key_.648649 res.header('Content-Length');650 // => undefined651652 res.header('Content-Length', 123);653 // => 123654655 res.header('Content-Length');656 // => 123657658### res.contentType(type)659660Sets the _Content-Type_ response header to the given _type_.661662 var filename = 'path/to/image.png';663 res.contentType(filename);664 // res.headers['Content-Type'] is now "image/png"665666### res.attachment([filename])667668Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.669670 res.attachment('path/to/my/image.png');671672### res.sendfile(path)673674Used by `res.download()` to transfer an arbitrary file. 675676 res.sendfile('path/to/my.file');677

Merge branch 'downloads'Tj Holowaychukbefore adoption949803d

lines 678–688why, one step back
678This 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.
679680 res.sendfile(path, function(err, path){681 if (err) {682 // handle the error683 } else {684 console.log('transferred %s', path);685 }686 });687688When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 689–707why, one step back
689
690### res.download(file[, filename])691692Transfer the given _file_ as an attachment with optional alternative _filename_.693694 res.download('path/to/image.png');695 res.download('path/to/image.png', 'foo.png');696697This is equivalent to:698699 res.attachment(file);700 res.sendfile(file);701702### res.send(body|status[, headers|status[, status]])703704The `res.send()` method is a high level response utility allowing you to pass705objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status706code based responses. The following are all valid uses:707

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d

line 708why, one step back
708 res.send(); // 204

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 709–733why, one step back
709 res.send(new Buffer('wahoo'));
710 res.send({ some: 'json' });711 res.send('<p>some html</p>');712 res.send('Sorry, cant find that', 404);713 res.send('text', { 'Content-Type': 'text/plain' }, 201);714 res.send(404);715716By default the _Content-Type_ response header is set, however if explicitly717assigned through `res.send()` or previously with `res.header()` or `res.contentType()`718it will not be set again.719720### res.redirect(url[, status])721722Redirect to the given _url_ with a default response _status_ of 302.723724 res.redirect('/', 301);725 res.redirect('/account');726 res.redirect('http://google.com');727 res.redirect('home');728 res.redirect('back');729730Express supports "redirect mapping", which by default provides _home_, and _back_.731The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes732the "home" setting and defaults to "/".733

Cookie docsTj Holowaychukbefore adoptiona89767c

lines 734–754why, one step back
734### res.cookie(name, val[, options])
735736Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.737738 // "Remember me" for 15 minutes 739 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });740741To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:742743 app.use(express.cookieDecoder());744 745 app.get('/', function(req, res){746 // use req.cookies.rememberme747 });748749### res.clearCookie(name)750751Clear cookie _name_ by setting "expires" far in the past.752753 res.clearCookie('rememberme');754

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 755–763why, one step back
755### res.render(view[, options[, fn]])
756757Render _view_ with the given _options_ and optional callback _fn_.758When a callback function is given a response will _not_ be made759automatically, however otherwise a response of _200_ and _text/html_ is given.760761 Most engines accept one or more of the following options,762 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:763

Updated docsTj Holowaychukbefore adoptionfd4c88d

line 764why, one step back
764 - _scope_ Template evaluation context (value of _this_)

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 765–766why, one step back
765 - _locals_ Object containing local variables
766 - _debug_ Output debugging information

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d

lines 767–768why, one step back
767 - _status_ Response status code, defaults to 200
768 - _headers_ Response headers object

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 769–785why, one step back
769
770### res.partial(view[, options])771772Render _view_ partial with the given _options_. This method is always available773to the view as a local variable.774775- _as_ Variable name for each _collection_ value, defaults to the view name.776 * as: 'something' will add the _something_ local variable777 * as: this will use the collection value as the template context778 * as: global will merge the collection value's properties with _locals_779780- _collection_ Array of objects, the name is derived from the view name itself. 781 For example _video.html_ will have a object _video_ available to it.782783The following are equivalent, and the name of collection value when passed784to the partial will be _movie_ as derived from the name.785

More partial() docsTj Holowaychukbefore adoptione87d637

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

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 788–814why, one step back
788 partial('movie.jade', { collection: movies });
789 partial('movie.jade', movies);790 partial('movie', movies);791 // In view: movie.director792793To change the local from _movie_ to _video_ we can use the "as" option:794795 partial('movie', { collection: movies, as: 'video' });796 // In view: video.director797798Also we can make our movie the value of _this_ within our view so that instead799of _movie.director_ we could use _this.director_.800801 partial('movie', { collection: movies, as: this });802 // In view: this.director803804Another alternative is to "explode" the properties of the collection item into805pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:806807 partials('movie', { collection: movies, as: global });808 // In view: director809810### app.set(name[, val])811812Apply an application level setting _name_ to _val_, or813get the value of _name_ when _val_ is not present:814

Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110

lines 815–817why, one step back
815 app.set('views', __dirname + '/views');
816 app.set('views');817 // => ...path...

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 818–925why, one step back
818
819### app.enable(name)820821Enable the given setting _name_:822823 app.enable('some arbitrary setting');824 app.set('some arbitrary setting');825 // => true826827### app.disable(name)828829Disable the given setting _name_:830831 app.disable('some setting');832 app.set('some setting');833 // => false834835### app.configure(env|function[, function])836837Define a callback function for the given _env_ (or all environments) with callback _function_:838839 app.configure(function(){840 // executed for each env841 });842843 app.configure('development', function(){844 // executed for 'development' only845 });846847### app.redirect(name, val)848849For use with `res.redirect()` we can map redirects at the application level as shown below:850851 app.redirect('google', 'http://google.com');852853Now in a route we may call:854855 res.redirect('google');856857We may also map dynamic redirects:858859 app.redirect('comments', function(req, res){860 return '/post/' + req.params.id + '/comments';861 });862863So now we may do the following, and the redirect will dynamically adjust to864the context of the request. If we called this route with _GET /post/12_ our865redirect _Location_ would be _/post/12/comments_.866867 app.get('/post/:id', function(req, res){868 res.redirect('comments');869 });870871### app.error(function)872873Adds an error handler _function_ which will receive the exception as the first parameter as shown below.874Note that we may set several error handlers by making several calls to this method, however the handler875should call _next(err)_ if it does not wish to deal with the exception:876877 app.error(function(err, req, res, next){878 res.send(err.message, 500);879 });880881### app.helpers(obj)882883Registers static view helpers.884885 app.helpers({886 name: function(first, last){ return first + ', ' + last },887 firstName: 'tj',888 lastName: 'holowaychuk'889 });890891Our view could now utilize the _firstName_ and _lastName_ variables,892as well as the _name()_ function exposed.893894 <%= name(firstName, lastName) %>895896### app.dynamicHelpers(obj)897898Registers dynamic view helpers. Dynamic view helpers899are simply functions which accept _req_, _res_, and are900evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function901becomes the local variable it is associated with.902903 app.dynamicHelpers({904 session: function(req, res){905 return req.session;906 }907 });908909All views would now have _session_ available so that session data can be accessed via _session.name_ etc:910911 <%= session.name %>912913### app.mounted(fn)914915Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.916917 var app = express.createServer(),918 blog = express.createServer();919 920 blog.mounted(function(parent){921 // parent is app922 // "this" is blog923 });924 925 app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 926–947why, one step back
926
927### app.register(ext, exports)928929Register the given template engine _exports_930as _ext_. For example we may wish to map ".html"931files to jade:932933 app.register('.html', require('jade'));934935This is also useful for libraries that may not936match extensions correctly. For example my haml.js937library is installed from npm as "hamljs" so instead938of layout.hamljs, we can register the engine as ".haml":939940 app.register('.haml', require('haml-js'));941942For engines that do not comply with the Express943specification, we can also wrap their api this way.944945 app.register('.foo', {946 render: function(str, options) {947 // perhaps their api is

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

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 949–950why, one step back
949 }
950 });

Check CONNECT_ENV before connectEnv.nameTj Holowaychukbefore adoption82dbae6

lines 951–974why, one step back
951
952### app.listen([port[, host]])953954Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all955connections will be accepted via _INADDR_ANY_.956957 app.listen();958 app.listen(3000);959 app.listen(3000, 'n.n.n.n');960961The _port_ argument may also be a string representing the path to a unix domain socket:962963 app.listen('/tmp/express.sock');964965Then try it out:966967 $ telnet /tmp/express.sock968 GET / HTTP/1.1969970 HTTP/1.1 200 OK971 Content-Type: text/plain972 Content-Length: 11973 974 Hello World