Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,044 lines · 34.2 KiB · Markdown

Last changed by

more partial docsTj Holowaychukbefore adoptionf32279d

History of this file

Take it

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 52–66why, 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 });66

Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 68why, one step back
68

Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 70why, one step back
70

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 73–81why, 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 options

Merge branch 'downloads'Tj Holowaychukbefore adoption949803d

line 82why, one step back
82 * _stream threshold_ Bytesize indicating when a file should be streamed for _res.sendfile()_ using _fs.ReadStream()_ and _sys.pump()_.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 83–91why, one step back
83
84### 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 });

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 94–148why, 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 capture101groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.102103 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 /products148

DocsTj Holowaychukbefore adoption5234368

lines 149–161why, one step back
149For 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_:
150151 var express = require('express')152 , app = express.createServer();153154 app.use(express.bodyDecoder());155156 app.post('/', function(req, res){157 res.send(req.body);158 });159160 app.listen(3000);161

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 162–165why, one step back
162### Passing Route Control
163164We may pass control to the next _matching_ route, by calling the _third_ argument,165the _next()_ function. When a match cannot be made, control is passed back to Connect,

Added route-middleware exampleTj Holowaychukbefore adoption4983e96

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 167–179why, one step back
167
168 app.get('/users/:id?', function(req, res, next){169 var id = req.params.id;170 if (id) {171 // do something172 } else {173 next();174 }175 });176 177 app.get('/users', function(req, res){178 // do something else179 });

DocsTj Holowaychukbefore adoption5234368

lines 180–213why, one step back
180
181Express 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:182183 var express = require('express')184 , app = express.createServer();185186 var users = [{ name: 'tj' }];187188 app.all('/user/:id/:op?', function(req, res, next){189 req.user = users[req.params.id];190 if (req.user) {191 next();192 } else {193 next(new Error('cannot find user ' + req.params.id));194 }195 });196197 app.get('/user/:id', function(req, res){198 res.send('viewing ' + req.user.name);199 });200201 app.get('/user/:id/edit', function(req, res){202 res.send('editing ' + req.user.name);203 });204205 app.put('/user/:id', function(req, res){206 res.send('updating ' + req.user.name);207 });208209 app.get('*', function(req, res){210 res.send('what???', 404);211 });212213 app.listen(3000);

Added route-middleware exampleTj Holowaychukbefore adoption4983e96

line 214why, one step back
214

Ordering docsTj Holowaychukbefore adoption296f127

lines 215–239why, one step back
215### Middleware
216217Middleware via [Connect](http://github.com/senchalabs/connect) can be218passed to _express.createServer()_ as you would with a regular Connect server. For example:219220 var express = require('express');221222 var app = express.createServer(223 express.logger(),224 express.bodyDecoder()225 );226227Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:228229 app.use(express.logger({ format: ':method :uri' }));230231Typically with connect middleware you would _require('connect')_ like so:232233 var connect = require('connect');234 app.use(connect.logger());235236This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:237238 app.use(express.logger());239

Added route-middleware exampleTj Holowaychukbefore adoption4983e96

lines 240–242why, one step back
240### Route Middleware
241242Routes 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.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 243why, one step back
243

Fixed docsTj Holowaychukbefore adoptioncef14ca

line 244why, one step back
244Typically 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 245why, one step back
245

Fixed docsTj Holowaychukbefore adoptioncef14ca

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

Doc cleanupTj Holowaychukbefore adoptionb083aed

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

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 250–251why, one step back
250 });
251 });

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

lines 252–254why, one step back
252
253To 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. 254

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 255–268why, one step back
255 function loadUser(req, res, next) {
256 // You would fetch your user from the db257 var user = users[req.params.id];258 if (user) {259 req.user = user;260 next();261 } else {262 next(new Error('Failed to load user ' + req.params.id));263 }264 }265 266 app.get('/user/:id', loadUser, function(req, res){267 res.send('Viewing user ' + req.user.name);268 });

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

lines 269–271why, one step back
269
270Multiple 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.271

Fixed docsTj Holowaychukbefore adoptioncef14ca

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

Doc cleanupTj Holowaychukbefore adoptionb083aed

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

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 276–280why, one step back
276 }
277 278 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){279 res.send('Editing user ' + req.user.name);280 });

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

line 281why, one step back
281

Fixed docsTj Holowaychukbefore adoptioncef14ca

line 282why, one step back
282Keeping 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 283why, one step back
283

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 284–286why, one step back
284 function andRestrictTo(role) {
285 return function(req, res, next) {286 req.authenticatedUser.role == role

Doc cleanupTj Holowaychukbefore adoptionb083aed

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

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 289–295why, one step back
289 }
290 }291 292 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){293 res.send('Deleted user ' + req.user.name);294 });295

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

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

Fixed docsTj Holowaychukbefore adoptioncef14ca

lines 298–307why, one step back
298 var a = [middleware1, middleware2]
299 , b = [middleware3, middleware4]300 , all = [a, b];301 302 app.get('/foo', a, function(){});303 app.get('/bar', a, function(){});304 305 app.get('/', a, middleware3, middleware4, function(){});306 app.get('/', a, b, function(){});307 app.get('/', all, function(){});

Added route middleware docsTj Holowaychukbefore adoptiondd4ddae

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

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 311–316why, one step back
311### HTTP Methods
312313We 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.314315 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.316

Doc typoTj Holowaychukbefore adoptionc9268f2

lines 317–321why, one step back
317 <form method="post" action="/">
318 <input type="text" name="user[name]" />319 <input type="text" name="user[email]" />320 <input type="submit" value="Submit" />321 </form>

HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951

lines 322–351why, one step back
322
323By 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:324325 app.use(express.bodyDecoder());326327Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.328329 app.post('/', function(req, res){330 console.log(req.body.user);331 res.redirect('back');332 });333334When 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.335336 app.use(express.bodyDecoder());337 app.use(express.methodOverride());338339The 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:340341 <form method="post" action="/">342 <input type="hidden" name="_method" value="put" />343 <input type="text" name="user[name]" />344 <input type="text" name="user[email]" />345 <input type="submit" value="Submit" /> 346 </form>347348 app.put('/', function(){349 console.log(req.body.user);350 res.redirect('back');351 });

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 352–461why, one step back
352
353### Error Handling354355Express provides the _app.error()_ method which receives exceptions thrown within a route,356or passed to _next(err)_. Below is an example which serves different pages based on our357ad-hoc _NotFound_ exception:358359 function NotFound(msg){360 this.name = 'NotFound';361 Error.call(this, msg);362 Error.captureStackTrace(this, arguments.callee);363 }364365 sys.inherits(NotFound, Error);366367 app.get('/404', function(req, res){368 throw new NotFound;369 });370371 app.get('/500', function(req, res){372 throw new Error('keyboard cat!');373 });374375We can call _app.error()_ several times as shown below.376Here we check for an instanceof _NotFound_ and show the377404 page, or we pass on to the next error handler.378379Note that these handlers can be defined anywhere, as they380will be placed below the route handlers on _listen()_. This 381allows for definition within _configure()_ blocks so we can382handle exceptions in different ways based on the environment.383384 app.error(function(err, req, res, next){385 if (err instanceof NotFound) {386 res.render('404.jade');387 } else {388 next(err);389 }390 });391392Here we assume all errors as 500 for the simplicity of393this demo, however you can choose whatever you like394395 app.error(function(err, req, res){396 res.render('500.jade', {397 locals: {398 error: err399 } 400 });401 });402403Our apps could also utilize the Connect _errorHandler_ middleware404to report on exceptions. For example if we wish to output exceptions 405in "development" mode to _stderr_ we can use:406407 app.use(express.errorHandler({ dumpExceptions: true }));408409Also during development we may want fancy html pages to show exceptions410that are passed or thrown, so we can set _showStack_ to true:411412 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));413414The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_415is present, which is useful for developing apps that rely heavily on client-side JavaScript.416417### View Rendering418419View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name420of the module that will be required. For example the view _layout.ejs_ will421tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 422_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.423424Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,425and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 426the _body_ local variable in _layout.haml_.427428 app.get('/', function(req, res){429 res.render('index.haml', {430 locals: { title: 'My Site' }431 });432 });433434The new _view engine_ setting allows us to specify our default template engine,435so for example when using [Jade](http://github.com/visionmedia/jade) we could set:436437 app.set('view engine', 'jade');438439Allowing us to render with:440441 res.render('index');442443vs:444445 res.render('index.jade');446447When _view engine_ is set, extensions are entirely optional, however we can still448mix and match template engines:449450 res.render('another-page.ejs');451452Express 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:453454 app.set('view options', {455 layout: false456 });457458Which can then be overridden within the `res.render()` call if need be:459460 res.render('myview.ejs', { layout: true });461

Docs for layout optionTj Holowaychukbefore adoption0a96621

lines 462–473why, one step back
462When 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:
463464 res.render('page', { layout: 'mylayout' });465466Otherwise we must specify the extension:467468 res.render('page', { layout: 'mylayout.jade' });469470These paths may also be absolute:471472 res.render('page', { layout: __dirname + '/../../mylayout.jade' });473

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 474–496why, one step back
474A good example of this is specifying custom _ejs_ opening and closing tags:
475476 app.set('view options', {477 open: '{{',478 close: '}}'479 });480481### View Partials482483The Express view system has built-in support for partials and collections, which are484sort of "mini" views representing a document fragment. For example rather than iterating485in a view to display comments, we would use a partial with collection support:486487 partial('comment.haml', { collection: comments });488489To make things even less verbose we can assume the extension as _.haml_ when omitted,490however if we wished we could use an ejs partial, within a haml view for example.491492 partial('comment', { collection: comments });493494And once again even further, when rendering a collection we can simply pass495an array, if no other options are desired:496

More partial() docsTj Holowaychukbefore adoptione87d637

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 498–504why, one step back
498
499When using the partial collection support a few "magic" variables are provided500for free:501502 * _firstInCollection_ True if this is the first object503 * _indexInCollection_ Index of the object in the collection504 * _lastInCollection_ True if this is the last object

More partial() docsTj Holowaychukbefore adoptione87d637

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 506why, one step back
506

More partial() docsTj Holowaychukbefore adoptione87d637

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

more partial docsTj Holowaychukbefore adoptionf32279d

lines 508–509why, one step back
508
509NOTE: 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 510why, one step back
510

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 511–517why, one step back
511### Template Engines
512513Below are a few template engines commonly used with Express:514515 * [Jade](http://jade-lang.com) haml.js successor516 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templates517 * [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 518why, one step back
518 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating

Added link to node-jqtpl template engineTj Holowaychukbefore adoptioncccda60

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

Added session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe

lines 520–532why, one step back
520
521### Session Support522523Sessions 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_.524525 app.use(express.cookieDecoder());526 app.use(express.session());527528By 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:529530 var RedisStore = require('connect-redis');531 app.use(express.cookieDecoder());532 app.use(express.session({ store: new RedisStore }));

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

line 533why, one step back
533

More session docsTj Holowaychukbefore adoption4bc8a86

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

Doc typoTj Holowaychukbefore adoption7da2743

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

More session docsTj Holowaychukbefore adoption4bc8a86

lines 538–560why, one step back
538 app.use(express.cookieDecoder());
539 app.use(express.session({ store: new RedisStore }));540541 app.post('/add-to-cart', function(req, res){542 // Perhaps we posted several items with a form543 // (use the bodyDecoder() middleware for this)544 var items = req.body.items;545 req.session.items = items;546 res.redirect('back');547 });548549 app.get('/add-to-cart', function(req, res){550 // When redirected back to GET /add-to-cart551 // we could check req.session.items && req.session.items.length552 // to print out a message553 if (req.session.items && req.session.items.length) {554 req.flash('info', 'You have %s items in your cart', req.session.items.length);555 }556 res.render('shopping-cart');557 });558559The _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.560

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 565–596why, one step back
565### req.header(key[, defaultValue])
566567Get the case-insensitive request header _key_, with optional _defaultValue_:568569 req.header('Host');570 req.header('host');571 req.header('Accept', '*/*');572573### req.accepts(type)574575Check if the _Accept_ header is present, and includes the given _type_.576577When the _Accept_ header is not present _true_ is returned. Otherwise578the given _type_ is matched by an exact match, and then subtypes. You579may pass the subtype such as "html" which is then converted internally580to "text/html" using the mime lookup table.581582 // Accept: text/html583 req.accepts('html');584 // => true585586 // Accept: text/*; application/json587 req.accepts('html');588 req.accepts('text/html');589 req.accepts('text/plain');590 req.accepts('application/json');591 // => true592593 req.accepts('image/png');594 req.accepts('png');595 // => false596

Added req.is() docsTj Holowaychukbefore adoption806aefa

lines 597–634why, one step back
597### req.is(type)
598599Check if the incoming request contains the _Content-Type_600header field, and it contains the give mime _type_.601 602 // With Content-Type: text/html; charset=utf-8603 req.is('html');604 req.is('text/html');605 // => true606 607 // When Content-Type is application/json608 req.is('json');609 req.is('application/json');610 // => true611 612 req.is('html');613 // => false614 615Ad-hoc callbacks can also be registered with Express, to perform616assertions again the request, for example if we need an expressive617way to check if our incoming request is an image, we can register _"an image"_618callback:619 620 app.is('an image', function(req){621 return 0 == req.headers['content-type'].indexOf('image');622 });623 624Now within our route callbacks, we can use to to assert content types625such as _"image/jpeg"_, _"image/png"_, etc.626 627 app.post('/image/upload', function(req, res, next){628 if (req.is('an image')) {629 // do something630 } else {631 next();632 }633 });634

More is() docsTj Holowaychukbefore adoption071ea95

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

Merge branch 'is'Tj Holowaychukbefore adoption7a71380

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 646–720why, one step back
646### req.param(name)
647648Return the value of param _name_ when present.649650 - Checks route placeholders (_req.params_), ex: /user/:id651 - Checks query string params (_req.query_), ex: ?id=12652 - Checks urlencoded body params (_req.body_), ex: id=12653654To utilize urlencoded request bodies, _req.body_655should be an object. This can be done by using656the _express.bodyDecoder_ middleware.657658### req.flash(type[, msg])659660Queue flash _msg_ of the given _type_.661662 req.flash('info', 'email sent');663 req.flash('error', 'email delivery failed');664 req.flash('info', 'email re-sent');665 // => 2666667 req.flash('info');668 // => ['email sent', 'email re-sent']669670 req.flash('info');671 // => []672673 req.flash();674 // => { error: ['email delivery failed'], info: [] }675676Flash notification message may also utilize formatters, by default only the %s string formatter is available:677678 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);679680### req.isXMLHttpRequest681682Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header683to see if it was issued by an _XMLHttpRequest_:684685 req.xhr686 req.isXMLHttpRequest687688### res.header(key[, val])689690Get or set the response header _key_.691692 res.header('Content-Length');693 // => undefined694695 res.header('Content-Length', 123);696 // => 123697698 res.header('Content-Length');699 // => 123700701### res.contentType(type)702703Sets the _Content-Type_ response header to the given _type_.704705 var filename = 'path/to/image.png';706 res.contentType(filename);707 // res.headers['Content-Type'] is now "image/png"708709### res.attachment([filename])710711Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.712713 res.attachment('path/to/my/image.png');714715### res.sendfile(path)716717Used by `res.download()` to transfer an arbitrary file. 718719 res.sendfile('path/to/my.file');720

Merge branch 'downloads'Tj Holowaychukbefore adoption949803d

lines 721–731why, one step back
721This 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.
722723 res.sendfile(path, function(err, path){724 if (err) {725 // handle the error726 } else {727 console.log('transferred %s', path);728 }729 });730731When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 732–762why, one step back
732
733### res.download(file[, filename])734735Transfer the given _file_ as an attachment with optional alternative _filename_.736737 res.download('path/to/image.png');738 res.download('path/to/image.png', 'foo.png');739740This is equivalent to:741742 res.attachment(file);743 res.sendfile(file);744745### res.send(body|status[, headers|status[, status]])746747The `res.send()` method is a high level response utility allowing you to pass748objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status749code based responses. The following are all valid uses:750751 res.send(); // 204752 res.send(new Buffer('wahoo'));753 res.send({ some: 'json' });754 res.send('<p>some html</p>');755 res.send('Sorry, cant find that', 404);756 res.send('text', { 'Content-Type': 'text/plain' }, 201);757 res.send(404);758759By default the _Content-Type_ response header is set, however if explicitly760assigned through `res.send()` or previously with `res.header()` or `res.contentType()`761it will not be set again.762

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

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 765–808why, one step back
765### res.redirect(url[, status])
766767Redirect to the given _url_ with a default response _status_ of 302.768769 res.redirect('/', 301);770 res.redirect('/account');771 res.redirect('http://google.com');772 res.redirect('home');773 res.redirect('back');774775Express supports "redirect mapping", which by default provides _home_, and _back_.776The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes777the "home" setting and defaults to "/".778779### res.cookie(name, val[, options])780781Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.782783 // "Remember me" for 15 minutes 784 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });785786To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:787788 app.use(express.cookieDecoder());789 790 app.get('/', function(req, res){791 // use req.cookies.rememberme792 });793794### res.clearCookie(name)795796Clear cookie _name_ by setting "expires" far in the past.797798 res.clearCookie('rememberme');799800### res.render(view[, options[, fn]])801802Render _view_ with the given _options_ and optional callback _fn_.803When a callback function is given a response will _not_ be made804automatically, however otherwise a response of _200_ and _text/html_ is given.805806 Most engines accept one or more of the following options,807 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:808

Updated docsTj Holowaychukbefore adoptionfd4c88d

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 810–819why, one step back
810 - _locals_ Object containing local variables
811 - _debug_ Output debugging information812 - _status_ Response status code, defaults to 200813 - _headers_ Response headers object814815### res.partial(view[, options])816817Render _view_ partial with the given _options_. This method is always available818to the view as a local variable.819

New partial() docsTj Holowaychukbefore adoption1c90332

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 822–831why, one step back
822 * as: 'something' will add the _something_ local variable
823 * as: this will use the collection value as the template context824 * as: global will merge the collection value's properties with _locals_825826- _collection_ Array of objects, the name is derived from the view name itself. 827 For example _video.html_ will have a object _video_ available to it.828829The following are equivalent, and the name of collection value when passed830to the partial will be _movie_ as derived from the name.831

More partial() docsTj Holowaychukbefore adoptione87d637

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 834–852why, one step back
834 partial('movie.jade', { collection: movies });
835 partial('movie.jade', movies);836 partial('movie', movies);837 // In view: movie.director838839To change the local from _movie_ to _video_ we can use the "as" option:840841 partial('movie', { collection: movies, as: 'video' });842 // In view: video.director843844Also we can make our movie the value of _this_ within our view so that instead845of _movie.director_ we could use _this.director_.846847 partial('movie', { collection: movies, as: this });848 // In view: this.director849850Another alternative is to "explode" the properties of the collection item into851pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:852

New partial() docsTj Holowaychukbefore adoption1c90332

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

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

New partial() docsTj Holowaychukbefore adoption1c90332

lines 855–873why, one step back
855
856This same logic applies to a single partial object usage:857858 partial('movie', { object: movie, as: this });859 // In view: this.director860861 partial('movie', { object: movie, as: global });862 // In view: director863864 partial('movie', { object: movie, as: 'video' });865 // In view: video.director866867 partial('movie', { object: movie });868 // In view: movie.director869870When 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:871872 partial('movie', movie);873 // => In view: movie.director

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 874–883why, one step back
874
875### app.set(name[, val])876877Apply an application level setting _name_ to _val_, or878get the value of _name_ when _val_ is not present:879880 app.set('views', __dirname + '/views');881 app.set('views');882 // => ...path...883

Settings docsTj Holowaychukbefore adoptione562adc

lines 884–888why, one step back
884Alternatively you may simply access the settings via _app.settings_:
885886 app.settings.views887 // => ...path...888

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 889–1017why, one step back
889### app.enable(name)
890891Enable the given setting _name_:892893 app.enable('some arbitrary setting');894 app.set('some arbitrary setting');895 // => true896897### app.disable(name)898899Disable the given setting _name_:900901 app.disable('some setting');902 app.set('some setting');903 // => false904905### app.configure(env|function[, function])906907Define a callback function for the given _env_ (or all environments) with callback _function_:908909 app.configure(function(){910 // executed for each env911 });912913 app.configure('development', function(){914 // executed for 'development' only915 });916917### app.redirect(name, val)918919For use with `res.redirect()` we can map redirects at the application level as shown below:920921 app.redirect('google', 'http://google.com');922923Now in a route we may call:924925 res.redirect('google');926927We may also map dynamic redirects:928929 app.redirect('comments', function(req, res){930 return '/post/' + req.params.id + '/comments';931 });932933So now we may do the following, and the redirect will dynamically adjust to934the context of the request. If we called this route with _GET /post/12_ our935redirect _Location_ would be _/post/12/comments_.936937 app.get('/post/:id', function(req, res){938 res.redirect('comments');939 });940941### app.error(function)942943Adds an error handler _function_ which will receive the exception as the first parameter as shown below.944Note that we may set several error handlers by making several calls to this method, however the handler945should call _next(err)_ if it does not wish to deal with the exception:946947 app.error(function(err, req, res, next){948 res.send(err.message, 500);949 });950951### app.helpers(obj)952953Registers static view helpers.954955 app.helpers({956 name: function(first, last){ return first + ', ' + last },957 firstName: 'tj',958 lastName: 'holowaychuk'959 });960961Our view could now utilize the _firstName_ and _lastName_ variables,962as well as the _name()_ function exposed.963964 <%= name(firstName, lastName) %>965966### app.dynamicHelpers(obj)967968Registers dynamic view helpers. Dynamic view helpers969are simply functions which accept _req_, _res_, and are970evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function971becomes the local variable it is associated with.972973 app.dynamicHelpers({974 session: function(req, res){975 return req.session;976 }977 });978979All views would now have _session_ available so that session data can be accessed via _session.name_ etc:980981 <%= session.name %>982983### app.mounted(fn)984985Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.986987 var app = express.createServer(),988 blog = express.createServer();989 990 blog.mounted(function(parent){991 // parent is app992 // "this" is blog993 });994 995 app.use(blog);996997### app.register(ext, exports)998999Register the given template engine _exports_1000as _ext_. For example we may wish to map ".html"1001files to jade:10021003 app.register('.html', require('jade'));10041005This is also useful for libraries that may not1006match extensions correctly. For example my haml.js1007library is installed from npm as "hamljs" so instead1008of layout.hamljs, we can register the engine as ".haml":10091010 app.register('.haml', require('haml-js'));10111012For engines that do not comply with the Express1013specification, we can also wrap their api this way.10141015 app.register('.foo', {1016 render: function(str, options) {1017 // perhaps their api is

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

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

Merge branch 'guide'Tj Holowaychukbefore adoptionf4a0809

lines 1019–1044why, one step back
1019 }
1020 });10211022### app.listen([port[, host]])10231024Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1025connections will be accepted via _INADDR_ANY_.10261027 app.listen();1028 app.listen(3000);1029 app.listen(3000, 'n.n.n.n');10301031The _port_ argument may also be a string representing the path to a unix domain socket:10321033 app.listen('/tmp/express.sock');10341035Then try it out:10361037 $ telnet /tmp/express.sock1038 GET / HTTP/1.110391040 HTTP/1.1 200 OK1041 Content-Type: text/plain1042 Content-Length: 111043 1044 Hello World