Skip to content
Myr

guide.md

This file

Path

docs/guide.md

925 lines · 30.3 KiB · Markdown

Last changed by

Started apps sectionTj Holowaychukbefore adoptiond3f139c

History of this file

Take it

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 1–40why, 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_.

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

lines 41–42why, one step back
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.

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 43–44why, one step back
43
44 app.configure(function(){

Updated docsTj Holowaychukbefore adoption344218f

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

Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3

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'));

s/foo/relative/Tj Holowaychukbefore adoptione554378

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 }));

s/foo/relative/Tj Holowaychukbefore adoptione554378

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());

s/foo/relative/Tj Holowaychukbefore adoptione554378

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:

s/foo/relative/Tj Holowaychukbefore adoptione554378

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 79–83why, 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()_

New "home" docsTj Holowaychukbefore adoption1e7a12f

line 84why, one step back
84 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 85–86why, one step back
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()_.

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 90–94why, 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_, this

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 95–96why, one step back
95can be done by defining the route below. The values associated to the named placeholders
96are available as `req.params`.

s/foo/relative/Tj Holowaychukbefore adoptione554378

line 97why, one step back
97

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 98–99why, one step back
98 app.get('/user/:id', function(req, res){
99 res.send('user ' + req.params.id);

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 100–107why, one step back
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 capture

Updated docsTj Holowaychukbefore adoptiond691ecb

line 108why, one step back
108groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.

s/foo/relative/Tj Holowaychukbefore adoptione554378

line 109why, one step back
109

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 110–111why, one step back
110 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){
111 res.send(req.params);

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 112–157why, one step back
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 Control157

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 158–159why, one step back
158We 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()_.

s/foo/relative/Tj Holowaychukbefore adoptione554378

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){

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 163–164why, one step back
163 var id = req.params.id;
164 if (id) {

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 165–170why, one step back
165 // do something
166 } else {167 next();168 }169 });170

Updated docsTj Holowaychukbefore adoptiond691ecb

line 171why, one step back
171 app.get('/users', function(req, res){

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 172–173why, one step back
172 // do something else
173 });

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.

s/foo/relative/Tj Holowaychukbefore adoptione554378

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

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 }));

s/foo/relative/Tj Holowaychukbefore adoptione554378

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 }));

s/foo/relative/Tj Holowaychukbefore adoptione554378

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.

s/foo/relative/Tj Holowaychukbefore adoptione554378

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 });

s/foo/relative/Tj Holowaychukbefore adoptione554378

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);

s/foo/relative/Tj Holowaychukbefore adoptione554378

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

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 }));

s/foo/relative/Tj Holowaychukbefore adoptione554378

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

Started apps sectionTj Holowaychukbefore adoptiond3f139c

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 522–557why, 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 // => false553554### req.param(name)555556Return the value of param _name_ when present.557

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 558–560why, one step back
558 - Checks route placeholders (_req.params_), ex: /user/:id
559 - Checks query string params (_req.query_), ex: ?id=12560 - Checks urlencoded body params (_req.body_), ex: id=12

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 561–563why, one step back
561
562To utilize urlencoded request bodies, _req.body_563should be an object. This can be done by using

Updated docsTj Holowaychukbefore adoption344218f

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 565–583why, one step back
565
566### req.flash(type[, msg])567568Queue flash _msg_ of the given _type_.569570 req.flash('info', 'email sent');571 req.flash('error', 'email delivery failed');572 req.flash('info', 'email re-sent');573 // => 2574575 req.flash('info');576 // => ['email sent', 'email re-sent']577578 req.flash('info');579 // => []580581 req.flash();582 // => { error: ['email delivery failed'], info: [] }583

Added flash formatter docsTj Holowaychukbefore adoptionf16978d

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 588–628why, one step back
588### req.isXMLHttpRequest
589590Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header591to see if it was issued by an _XMLHttpRequest_:592593 req.xhr594 req.isXMLHttpRequest595596### res.header(key[, val])597598Get or set the response header _key_.599600 res.header('Content-Length');601 // => undefined602603 res.header('Content-Length', 123);604 // => 123605606 res.header('Content-Length');607 // => 123608609### res.contentType(type)610611Sets the _Content-Type_ response header to the given _type_.612613 var filename = 'path/to/image.png';614 res.contentType(filename);615 // res.headers['Content-Type'] is now "image/png"616617### res.attachment([filename])618619Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.620621 res.attachment('path/to/my/image.png');622623### res.sendfile(path)624625Used by `res.download()` to transfer an arbitrary file. 626627 res.sendfile('path/to/my.file');628

Merge branch 'downloads'Tj Holowaychukbefore adoption949803d

lines 629–639why, one step back
629This 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.
630631 res.sendfile(path, function(err, path){632 if (err) {633 // handle the error634 } else {635 console.log('transferred %s', path);636 }637 });638639When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 640–658why, one step back
640
641### res.download(file[, filename])642643Transfer the given _file_ as an attachment with optional alternative _filename_.644645 res.download('path/to/image.png');646 res.download('path/to/image.png', 'foo.png');647648This is equivalent to:649650 res.attachment(file);651 res.sendfile(file);652653### res.send(body|status[, headers|status[, status]])654655The `res.send()` method is a high level response utility allowing you to pass656objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status657code based responses. The following are all valid uses:658

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

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 660–684why, one step back
660 res.send(new Buffer('wahoo'));
661 res.send({ some: 'json' });662 res.send('<p>some html</p>');663 res.send('Sorry, cant find that', 404);664 res.send('text', { 'Content-Type': 'text/plain' }, 201);665 res.send(404);666667By default the _Content-Type_ response header is set, however if explicitly668assigned through `res.send()` or previously with `res.header()` or `res.contentType()`669it will not be set again.670671### res.redirect(url[, status])672673Redirect to the given _url_ with a default response _status_ of 302.674675 res.redirect('/', 301);676 res.redirect('/account');677 res.redirect('http://google.com');678 res.redirect('home');679 res.redirect('back');680681Express supports "redirect mapping", which by default provides _home_, and _back_.682The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes683the "home" setting and defaults to "/".684

Cookie docsTj Holowaychukbefore adoptiona89767c

lines 685–705why, one step back
685### res.cookie(name, val[, options])
686687Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.688689 // "Remember me" for 15 minutes 690 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });691692To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:693694 app.use(express.cookieDecoder());695 696 app.get('/', function(req, res){697 // use req.cookies.rememberme698 });699700### res.clearCookie(name)701702Clear cookie _name_ by setting "expires" far in the past.703704 res.clearCookie('rememberme');705

s/foo/relative/Tj Holowaychukbefore adoptione554378

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

Updated docsTj Holowaychukbefore adoptionfd4c88d

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

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

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

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 720–736why, one step back
720
721### res.partial(view[, options])722723Render _view_ partial with the given _options_. This method is always available724to the view as a local variable.725726- _as_ Variable name for each _collection_ value, defaults to the view name.727 * as: 'something' will add the _something_ local variable728 * as: this will use the collection value as the template context729 * as: global will merge the collection value's properties with _locals_730731- _collection_ Array of objects, the name is derived from the view name itself. 732 For example _video.html_ will have a object _video_ available to it.733734The following are equivalent, and the name of collection value when passed735to the partial will be _movie_ as derived from the name.736

More partial() docsTj Holowaychukbefore adoptione87d637

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

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 739–765why, one step back
739 partial('movie.jade', { collection: movies });
740 partial('movie.jade', movies);741 partial('movie', movies);742 // In view: movie.director743744To change the local from _movie_ to _video_ we can use the "as" option:745746 partial('movie', { collection: movies, as: 'video' });747 // In view: video.director748749Also we can make our movie the value of _this_ within our view so that instead750of _movie.director_ we could use _this.director_.751752 partial('movie', { collection: movies, as: this });753 // In view: this.director754755Another alternative is to "explode" the properties of the collection item into756pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:757758 partials('movie', { collection: movies, as: global });759 // In view: director760761### app.set(name[, val])762763Apply an application level setting _name_ to _val_, or764get the value of _name_ when _val_ is not present:765

Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110

lines 766–768why, one step back
766 app.set('views', __dirname + '/views');
767 app.set('views');768 // => ...path...

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 769–809why, one step back
769
770### app.enable(name)771772Enable the given setting _name_:773774 app.enable('some arbitrary setting');775 app.set('some arbitrary setting');776 // => true777778### app.disable(name)779780Disable the given setting _name_:781782 app.disable('some setting');783 app.set('some setting');784 // => false785786### app.configure(env|function[, function])787788Define a callback function for the given _env_ (or all environments) with callback _function_:789790 app.configure(function(){791 // executed for each env792 });793794 app.configure('development', function(){795 // executed for 'development' only796 });797798### app.redirect(name, val)799800For use with `res.redirect()` we can map redirects at the application level as shown below:801802 app.redirect('google', 'http://google.com');803804Now in a route we may call:805806 res.redirect('google');807808We may also map dynamic redirects:809

Updated docsTj Holowaychukbefore adoptiond691ecb

lines 810–811why, one step back
810 app.redirect('comments', function(req, res){
811 return '/post/' + req.params.id + '/comments';

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 812–849why, one step back
812 });
813814So now we may do the following, and the redirect will dynamically adjust to815the context of the request. If we called this route with _GET /post/12_ our816redirect _Location_ would be _/post/12/comments_.817818 app.get('/post/:id', function(req, res){819 res.redirect('comments');820 });821822### app.error(function)823824Adds an error handler _function_ which will receive the exception as the first parameter as shown below.825Note that we may set several error handlers by making several calls to this method, however the handler826should call _next(err)_ if it does not wish to deal with the exception:827828 app.error(function(err, req, res, next){829 res.send(err.message, 500);830 });831832### app.helpers(obj)833834Registers static view helpers.835836 app.helpers({837 name: function(first, last){ return first + ', ' + last },838 firstName: 'tj',839 lastName: 'holowaychuk'840 });841842Our view could now utilize the _firstName_ and _lastName_ variables,843as well as the _name()_ function exposed.844845 <%= name(firstName, lastName) %>846847### app.dynamicHelpers(obj)848849Registers dynamic view helpers. Dynamic view helpers

Updated docsTj Holowaychukbefore adoptiond691ecb

line 850why, one step back
850are simply functions which accept _req_, _res_, and are

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 851–854why, one step back
851evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function
852becomes the local variable it is associated with.853854 app.dynamicHelpers({

Updated docsTj Holowaychukbefore adoptiond691ecb

line 855why, one step back
855 session: function(req, res){

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 856–862why, one step back
856 return req.session;
857 }858 });859860All views would now have _session_ available so that session data can be accessed via _session.name_ etc:861862 <%= session.name %>

Rebuilt docsTj Holowaychukbefore adoptionba88e48

lines 863–876why, one step back
863
864### app.mounted(fn)865866Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.867868 var app = express.createServer(),869 blog = express.createServer();870 871 blog.mounted(function(parent){872 // parent is app873 // "this" is blog874 });875 876 app.use(blog);

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 877–898why, one step back
877
878### app.register(ext, exports)879880Register the given template engine _exports_881as _ext_. For example we may wish to map ".html"882files to jade:883884 app.register('.html', require('jade'));885886This is also useful for libraries that may not887match extensions correctly. For example my haml.js888library is installed from npm as "hamljs" so instead889of layout.hamljs, we can register the engine as ".haml":890891 app.register('.haml', require('haml-js'));892893For engines that do not comply with the Express894specification, we can also wrap their api this way.895896 app.register('.foo', {897 render: function(str, options) {898 // perhaps their api is

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

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

Added app.register() docsTj Holowaychukbefore adoption77e5d8e

lines 900–901why, one step back
900 }
901 });

s/foo/relative/Tj Holowaychukbefore adoptione554378

lines 902–925why, one step back
902
903### app.listen([port[, host]])904905Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all906connections will be accepted via _INADDR_ANY_.907908 app.listen();909 app.listen(3000);910 app.listen(3000, 'n.n.n.n');911912The _port_ argument may also be a string representing the path to a unix domain socket:913914 app.listen('/tmp/express.sock');915916Then try it out:917918 $ telnet /tmp/express.sock919 GET / HTTP/1.1920921 HTTP/1.1 200 OK922 Content-Type: text/plain923 Content-Length: 11924 925 Hello World