Skip to content
Myr

guide.md

This file

Path

docs/guide.md

1,111 lines · 37.5 KiB · Markdown

Last changed by

Updated connect submoduleTj Holowaychukbefore adoptiona9db47f

History of this file

Take it

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

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

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–42why, one step back
39 app.use(express.methodOverride());
40 app.use(express.bodyDecoder());41 app.use(app.router);42 });

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

line 43why, one step back
43

DocsTj Holowaychukbefore adoption5234368

line 44why, one step back
44 app.configure('development', function(){

Updated connect submoduleTj Holowaychukbefore adoptiona9db47f

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

DocsTj Holowaychukbefore adoption5234368

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

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

line 48why, one step back
48

DocsTj Holowaychukbefore adoption5234368

line 49why, one step back
49 app.configure('production', function(){

Updated connect submoduleTj Holowaychukbefore adoptiona9db47f

lines 50–51why, one step back
50 var oneYear = 31557600000;
51 app.use(express.staticProvider({ root: __dirname + '/public', maxAge: oneYear }));

DocsTj Holowaychukbefore adoption5234368

lines 52–53why, one step back
52 app.use(express.errorHandler());
53 });

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

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

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

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

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

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

DocsTj Holowaychukbefore adoption5234368

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

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

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

DocsTj Holowaychukbefore adoptionbba049b

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

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

lines 104–149why, one step back
104
105 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){106 res.send(req.params);107 });108109Curl requests against the previously defined route:110111 $ curl http://dev:3000/user112 [null,null]113 $ curl http://dev:3000/users114 [null,null]115 $ curl http://dev:3000/users/1116 ["1",null]117 $ curl http://dev:3000/users/1..15118 ["1","15"]119120Below are some route examples, and the associated paths that they121may consume:122123 "/user/:id"124 /user/12125126 "/users/:id?"127 /users/5128 /users129130 "/files/*"131 /files/jquery.js132 /files/javascripts/jquery.js133134 "/file/*.*"135 /files/jquery.js136 /files/javascripts/jquery.js137 138 "/user/:id/:operation?"139 /user/1140 /user/1/edit141 142 "/products.:format"143 /products.json144 /products.xml145146 "/products.:format?"147 /products.json148 /products.xml149 /products

DocsTj Holowaychukbefore adoptionbba049b

lines 150–153why, one step back
150
151 "/user/:id.:format?"152 /user/12153 /user/12.json

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

line 154why, one step back
154

DocsTj Holowaychukbefore adoption5234368

lines 155–166why, one step back
155For 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_:
156157 var express = require('express')158 , app = express.createServer();159160 app.use(express.bodyDecoder());161162 app.post('/', function(req, res){163 res.send(req.body);164 });165166 app.listen(3000);

DocsTj Holowaychukbefore adoptionbba049b

line 167why, one step back
167

DocsTj Holowaychukbefore adoption14dce5a

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

DocsTj Holowaychukbefore adoption5234368

line 169why, one step back
169

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

lines 170–187why, one step back
170### Passing Route Control
171172We may pass control to the next _matching_ route, by calling the _third_ argument,173the _next()_ function. When a match cannot be made, control is passed back to Connect,174and 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()_.175176 app.get('/users/:id?', function(req, res, next){177 var id = req.params.id;178 if (id) {179 // do something180 } else {181 next();182 }183 });184 185 app.get('/users', function(req, res){186 // do something else187 });

DocsTj Holowaychukbefore adoption5234368

lines 188–221why, one step back
188
189Express 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:190191 var express = require('express')192 , app = express.createServer();193194 var users = [{ name: 'tj' }];195196 app.all('/user/:id/:op?', function(req, res, next){197 req.user = users[req.params.id];198 if (req.user) {199 next();200 } else {201 next(new Error('cannot find user ' + req.params.id));202 }203 });204205 app.get('/user/:id', function(req, res){206 res.send('viewing ' + req.user.name);207 });208209 app.get('/user/:id/edit', function(req, res){210 res.send('editing ' + req.user.name);211 });212213 app.put('/user/:id', function(req, res){214 res.send('updating ' + req.user.name);215 });216217 app.get('*', function(req, res){218 res.send('what???', 404);219 });220221 app.listen(3000);

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

lines 222–424why, one step back
222
223### Middleware224225Middleware via [Connect](http://github.com/senchalabs/connect) can be226passed to _express.createServer()_ as you would with a regular Connect server. For example:227228 var express = require('express');229230 var app = express.createServer(231 express.logger(),232 express.bodyDecoder()233 );234235Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:236237 app.use(express.logger({ format: ':method :uri' }));238239Typically with connect middleware you would _require('connect')_ like so:240241 var connect = require('connect');242 app.use(connect.logger());243244This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:245246 app.use(express.logger());247248### Route Middleware249250Routes 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.251252Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 253254 app.get('/user/:id', function(req, res, next){255 loadUser(req.params.id, function(err, user){256 if (err) return next(err);257 res.send('Viewing user ' + user.name);258 });259 });260261To 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. 262263 function loadUser(req, res, next) {264 // You would fetch your user from the db265 var user = users[req.params.id];266 if (user) {267 req.user = user;268 next();269 } else {270 next(new Error('Failed to load user ' + req.params.id));271 }272 }273 274 app.get('/user/:id', loadUser, function(req, res){275 res.send('Viewing user ' + req.user.name);276 });277278Multiple 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.279280 function andRestrictToSelf(req, res, next) {281 req.authenticatedUser.id == req.user.id282 ? next()283 : next(new Error('Unauthorized'));284 }285 286 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){287 res.send('Editing user ' + req.user.name);288 });289290Keeping 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.291292 function andRestrictTo(role) {293 return function(req, res, next) {294 req.authenticatedUser.role == role295 ? next()296 : next(new Error('Unauthorized'));297 }298 }299 300 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){301 res.send('Deleted user ' + req.user.name);302 });303304Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.305306 var a = [middleware1, middleware2]307 , b = [middleware3, middleware4]308 , all = [a, b];309 310 app.get('/foo', a, function(){});311 app.get('/bar', a, function(){});312 313 app.get('/', a, middleware3, middleware4, function(){});314 app.get('/', a, b, function(){});315 app.get('/', all, function(){});316317For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.318319### HTTP Methods320321We 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.322323 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.324 325 <form method="post" action="/">326 <input type="text" name="user[name]" />327 <input type="text" name="user[email]" />328 <input type="submit" value="Submit" />329 </form>330331By 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:332333 app.use(express.bodyDecoder());334335Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.336337 app.post('/', function(req, res){338 console.log(req.body.user);339 res.redirect('back');340 });341342When 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.343344 app.use(express.bodyDecoder());345 app.use(express.methodOverride());346347The 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:348349 <form method="post" action="/">350 <input type="hidden" name="_method" value="put" />351 <input type="text" name="user[name]" />352 <input type="text" name="user[email]" />353 <input type="submit" value="Submit" /> 354 </form>355356 app.put('/', function(){357 console.log(req.body.user);358 res.redirect('back');359 });360361### Error Handling362363Express provides the _app.error()_ method which receives exceptions thrown within a route,364or passed to _next(err)_. Below is an example which serves different pages based on our365ad-hoc _NotFound_ exception:366367 function NotFound(msg){368 this.name = 'NotFound';369 Error.call(this, msg);370 Error.captureStackTrace(this, arguments.callee);371 }372373 sys.inherits(NotFound, Error);374375 app.get('/404', function(req, res){376 throw new NotFound;377 });378379 app.get('/500', function(req, res){380 throw new Error('keyboard cat!');381 });382383We can call _app.error()_ several times as shown below.384Here we check for an instanceof _NotFound_ and show the385404 page, or we pass on to the next error handler.386387Note that these handlers can be defined anywhere, as they388will be placed below the route handlers on _listen()_. This 389allows for definition within _configure()_ blocks so we can390handle exceptions in different ways based on the environment.391392 app.error(function(err, req, res, next){393 if (err instanceof NotFound) {394 res.render('404.jade');395 } else {396 next(err);397 }398 });399400Here we assume all errors as 500 for the simplicity of401this demo, however you can choose whatever you like402403 app.error(function(err, req, res){404 res.render('500.jade', {405 locals: {406 error: err407 } 408 });409 });410411Our apps could also utilize the Connect _errorHandler_ middleware412to report on exceptions. For example if we wish to output exceptions 413in "development" mode to _stderr_ we can use:414415 app.use(express.errorHandler({ dumpExceptions: true }));416417Also during development we may want fancy html pages to show exceptions418that are passed or thrown, so we can set _showStack_ to true:419420 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));421422The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_423is present, which is useful for developing apps that rely heavily on client-side JavaScript.424

Route precondition docsTj Holowaychukbefore adoptionfd2f67b

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

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

lines 461–540why, one step back
461### View Rendering
462463View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name464of the module that will be required. For example the view _layout.ejs_ will465tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 466_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.467468Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,469and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 470the _body_ local variable in _layout.haml_.471472 app.get('/', function(req, res){473 res.render('index.haml', {474 locals: { title: 'My Site' }475 });476 });477478The new _view engine_ setting allows us to specify our default template engine,479so for example when using [Jade](http://github.com/visionmedia/jade) we could set:480481 app.set('view engine', 'jade');482483Allowing us to render with:484485 res.render('index');486487vs:488489 res.render('index.jade');490491When _view engine_ is set, extensions are entirely optional, however we can still492mix and match template engines:493494 res.render('another-page.ejs');495496Express 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:497498 app.set('view options', {499 layout: false500 });501502Which can then be overridden within the `res.render()` call if need be:503504 res.render('myview.ejs', { layout: true });505506When 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:507508 res.render('page', { layout: 'mylayout' });509510Otherwise we must specify the extension:511512 res.render('page', { layout: 'mylayout.jade' });513514These paths may also be absolute:515516 res.render('page', { layout: __dirname + '/../../mylayout.jade' });517518A good example of this is specifying custom _ejs_ opening and closing tags:519520 app.set('view options', {521 open: '{{',522 close: '}}'523 });524525### View Partials526527The Express view system has built-in support for partials and collections, which are528sort of "mini" views representing a document fragment. For example rather than iterating529in a view to display comments, we would use a partial with collection support:530531 partial('comment.haml', { collection: comments });532533To make things even less verbose we can assume the extension as _.haml_ when omitted,534however if we wished we could use an ejs partial, within a haml view for example.535536 partial('comment', { collection: comments });537538And once again even further, when rendering a collection we can simply pass539an array, if no other options are desired:540

More partial() docsTj Holowaychukbefore adoptione87d637

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

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

lines 542–548why, one step back
542
543When using the partial collection support a few "magic" variables are provided544for free:545546 * _firstInCollection_ True if this is the first object547 * _indexInCollection_ Index of the object in the collection548 * _lastInCollection_ True if this is the last object

More partial() docsTj Holowaychukbefore adoptione87d637

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

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

line 550why, one step back
550

More partial() docsTj Holowaychukbefore adoptione87d637

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

more partial docsTj Holowaychukbefore adoptionf32279d

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

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

lines 555–562why, one step back
555### Template Engines
556557Below are a few template engines commonly used with Express:558559 * [Jade](http://jade-lang.com) haml.js successor560 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templates561 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript562 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating

Added link to node-jqtpl template engineTj Holowaychukbefore adoptioncccda60

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

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

lines 564–580why, one step back
564
565### Session Support566567Sessions 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_.568569 app.use(express.cookieDecoder());570 app.use(express.session());571572By 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:573574 var RedisStore = require('connect-redis');575 app.use(express.cookieDecoder());576 app.use(express.session({ store: new RedisStore }));577578Now 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:579580 var RedisStore = require('connect-redis');

Doc typoTj Holowaychukbefore adoption7da2743

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

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

lines 582–604why, one step back
582 app.use(express.cookieDecoder());
583 app.use(express.session({ store: new RedisStore }));584585 app.post('/add-to-cart', function(req, res){586 // Perhaps we posted several items with a form587 // (use the bodyDecoder() middleware for this)588 var items = req.body.items;589 req.session.items = items;590 res.redirect('back');591 });592593 app.get('/add-to-cart', function(req, res){594 // When redirected back to GET /add-to-cart595 // we could check req.session.items && req.session.items.length596 // to print out a message597 if (req.session.items && req.session.items.length) {598 req.flash('info', 'You have %s items in your cart', req.session.items.length);599 }600 res.render('shopping-cart');601 });602603The _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.604

Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc

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

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

lines 609–640why, one step back
609### req.header(key[, defaultValue])
610611Get the case-insensitive request header _key_, with optional _defaultValue_:612613 req.header('Host');614 req.header('host');615 req.header('Accept', '*/*');616617### req.accepts(type)618619Check if the _Accept_ header is present, and includes the given _type_.620621When the _Accept_ header is not present _true_ is returned. Otherwise622the given _type_ is matched by an exact match, and then subtypes. You623may pass the subtype such as "html" which is then converted internally624to "text/html" using the mime lookup table.625626 // Accept: text/html627 req.accepts('html');628 // => true629630 // Accept: text/*; application/json631 req.accepts('html');632 req.accepts('text/html');633 req.accepts('text/plain');634 req.accepts('application/json');635 // => true636637 req.accepts('image/png');638 req.accepts('png');639 // => false640

Added req.is() docsTj Holowaychukbefore adoption806aefa

lines 641–678why, one step back
641### req.is(type)
642643Check if the incoming request contains the _Content-Type_644header field, and it contains the give mime _type_.645 646 // With Content-Type: text/html; charset=utf-8647 req.is('html');648 req.is('text/html');649 // => true650 651 // When Content-Type is application/json652 req.is('json');653 req.is('application/json');654 // => true655 656 req.is('html');657 // => false658 659Ad-hoc callbacks can also be registered with Express, to perform660assertions again the request, for example if we need an expressive661way to check if our incoming request is an image, we can register _"an image"_662callback:663 664 app.is('an image', function(req){665 return 0 == req.headers['content-type'].indexOf('image');666 });667 668Now within our route callbacks, we can use to to assert content types669such as _"image/jpeg"_, _"image/png"_, etc.670 671 app.post('/image/upload', function(req, res, next){672 if (req.is('an image')) {673 // do something674 } else {675 next();676 }677 });678

More is() docsTj Holowaychukbefore adoption071ea95

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

Merge branch 'is'Tj Holowaychukbefore adoption7a71380

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

Added default param support to req.param(name, default)Tj Holowaychukbefore adoption0af9126

line 690why, one step back
690### req.param(name[, default])

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

line 691why, one step back
691

Added default param support to req.param(name, default)Tj Holowaychukbefore adoption0af9126

line 692why, one step back
692Return the value of param _name_ when present or _default_.

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

lines 693–806why, one step back
693
694 - Checks route placeholders (_req.params_), ex: /user/:id695 - Checks query string params (_req.query_), ex: ?id=12696 - Checks urlencoded body params (_req.body_), ex: id=12697698To utilize urlencoded request bodies, _req.body_699should be an object. This can be done by using700the _express.bodyDecoder_ middleware.701702### req.flash(type[, msg])703704Queue flash _msg_ of the given _type_.705706 req.flash('info', 'email sent');707 req.flash('error', 'email delivery failed');708 req.flash('info', 'email re-sent');709 // => 2710711 req.flash('info');712 // => ['email sent', 'email re-sent']713714 req.flash('info');715 // => []716717 req.flash();718 // => { error: ['email delivery failed'], info: [] }719720Flash notification message may also utilize formatters, by default only the %s string formatter is available:721722 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);723724### req.isXMLHttpRequest725726Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header727to see if it was issued by an _XMLHttpRequest_:728729 req.xhr730 req.isXMLHttpRequest731732### res.header(key[, val])733734Get or set the response header _key_.735736 res.header('Content-Length');737 // => undefined738739 res.header('Content-Length', 123);740 // => 123741742 res.header('Content-Length');743 // => 123744745### res.contentType(type)746747Sets the _Content-Type_ response header to the given _type_.748749 var filename = 'path/to/image.png';750 res.contentType(filename);751 // res.headers['Content-Type'] is now "image/png"752753### res.attachment([filename])754755Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.756757 res.attachment('path/to/my/image.png');758759### res.sendfile(path)760761Used by `res.download()` to transfer an arbitrary file. 762763 res.sendfile('path/to/my.file');764765This 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.766767 res.sendfile(path, function(err, path){768 if (err) {769 // handle the error770 } else {771 console.log('transferred %s', path);772 }773 });774775When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.776777### res.download(file[, filename])778779Transfer the given _file_ as an attachment with optional alternative _filename_.780781 res.download('path/to/image.png');782 res.download('path/to/image.png', 'foo.png');783784This is equivalent to:785786 res.attachment(file);787 res.sendfile(file);788789### res.send(body|status[, headers|status[, status]])790791The `res.send()` method is a high level response utility allowing you to pass792objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status793code based responses. The following are all valid uses:794795 res.send(); // 204796 res.send(new Buffer('wahoo'));797 res.send({ some: 'json' });798 res.send('<p>some html</p>');799 res.send('Sorry, cant find that', 404);800 res.send('text', { 'Content-Type': 'text/plain' }, 201);801 res.send(404);802803By default the _Content-Type_ response header is set, however if explicitly804assigned through `res.send()` or previously with `res.header()` or `res.contentType()`805it will not be set again.806

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

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

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

lines 809–863why, one step back
809### res.redirect(url[, status])
810811Redirect to the given _url_ with a default response _status_ of 302.812813 res.redirect('/', 301);814 res.redirect('/account');815 res.redirect('http://google.com');816 res.redirect('home');817 res.redirect('back');818819Express supports "redirect mapping", which by default provides _home_, and _back_.820The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes821the "home" setting and defaults to "/".822823### res.cookie(name, val[, options])824825Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.826827 // "Remember me" for 15 minutes 828 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });829830To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:831832 app.use(express.cookieDecoder());833 834 app.get('/', function(req, res){835 // use req.cookies.rememberme836 });837838### res.clearCookie(name)839840Clear cookie _name_ by setting "expires" far in the past.841842 res.clearCookie('rememberme');843844### res.render(view[, options[, fn]])845846Render _view_ with the given _options_ and optional callback _fn_.847When a callback function is given a response will _not_ be made848automatically, however otherwise a response of _200_ and _text/html_ is given.849850 Most engines accept one or more of the following options,851 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:852853 - _scope_ Template evaluation context (value of _this_)854 - _locals_ Object containing local variables855 - _debug_ Output debugging information856 - _status_ Response status code, defaults to 200857 - _headers_ Response headers object858859### res.partial(view[, options])860861Render _view_ partial with the given _options_. This method is always available862to the view as a local variable.863

New partial() docsTj Holowaychukbefore adoption1c90332

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

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

lines 866–875why, one step back
866 * as: 'something' will add the _something_ local variable
867 * as: this will use the collection value as the template context868 * as: global will merge the collection value's properties with _locals_869870- _collection_ Array of objects, the name is derived from the view name itself. 871 For example _video.html_ will have a object _video_ available to it.872873The following are equivalent, and the name of collection value when passed874to the partial will be _movie_ as derived from the name.875

More partial() docsTj Holowaychukbefore adoptione87d637

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

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

lines 878–896why, one step back
878 partial('movie.jade', { collection: movies });
879 partial('movie.jade', movies);880 partial('movie', movies);881 // In view: movie.director882883To change the local from _movie_ to _video_ we can use the "as" option:884885 partial('movie', { collection: movies, as: 'video' });886 // In view: video.director887888Also we can make our movie the value of _this_ within our view so that instead889of _movie.director_ we could use _this.director_.890891 partial('movie', { collection: movies, as: this });892 // In view: this.director893894Another alternative is to "explode" the properties of the collection item into895pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:896

New partial() docsTj Holowaychukbefore adoption1c90332

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

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

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

New partial() docsTj Holowaychukbefore adoption1c90332

lines 899–917why, one step back
899
900This same logic applies to a single partial object usage:901902 partial('movie', { object: movie, as: this });903 // In view: this.director904905 partial('movie', { object: movie, as: global });906 // In view: director907908 partial('movie', { object: movie, as: 'video' });909 // In view: video.director910911 partial('movie', { object: movie });912 // In view: movie.director913914When 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:915916 partial('movie', movie);917 // => In view: movie.director

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

line 918why, one step back
918

Added res.local(name[, val]) docsTj Holowaychukbefore adoption5ac0c6d

lines 919–935why, one step back
919### res.local(name[, val])
920921Get or set the given local variable _name_. The locals built up for a response are applied to those given to the view rendering methods such as `res.render()`.922923 app.all('/movie/:id', function(req, res, next){924 Movie.get(req.params.id, function(err, movie){925 // Assigns res.locals.movie = movie926 res.local('movie', movie);927 });928 });929 930 app.get('/movie/:id', function(req, res){931 // movie is already a local, however we932 // can pass more if we wish933 res.render('movie', { displayReviews: true });934 });935

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

lines 936–944why, one step back
936### app.set(name[, val])
937938Apply an application level setting _name_ to _val_, or939get the value of _name_ when _val_ is not present:940941 app.set('views', __dirname + '/views');942 app.set('views');943 // => ...path...944

Settings docsTj Holowaychukbefore adoptione562adc

lines 945–949why, one step back
945Alternatively you may simply access the settings via _app.settings_:
946947 app.settings.views948 // => ...path...949

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

lines 950–957why, one step back
950### app.enable(name)
951952Enable the given setting _name_:953954 app.enable('some arbitrary setting');955 app.set('some arbitrary setting');956 // => true957

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

lines 958–960why, one step back
958 app.enabled('some arbitrary setting');
959 // => true960

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

lines 961–966why, one step back
961### app.disable(name)
962963Disable the given setting _name_:964965 app.disable('some setting');966 app.set('some setting');

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

lines 967–969why, one step back
967 // => false
968 969 app.disabled('some setting');

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

lines 970–1111why, one step back
970 // => false
971972### app.configure(env|function[, function])973974Define a callback function for the given _env_ (or all environments) with callback _function_:975976 app.configure(function(){977 // executed for each env978 });979980 app.configure('development', function(){981 // executed for 'development' only982 });983984### app.redirect(name, val)985986For use with `res.redirect()` we can map redirects at the application level as shown below:987988 app.redirect('google', 'http://google.com');989990Now in a route we may call:991992 res.redirect('google');993994We may also map dynamic redirects:995996 app.redirect('comments', function(req, res){997 return '/post/' + req.params.id + '/comments';998 });9991000So now we may do the following, and the redirect will dynamically adjust to1001the context of the request. If we called this route with _GET /post/12_ our1002redirect _Location_ would be _/post/12/comments_.10031004 app.get('/post/:id', function(req, res){1005 res.redirect('comments');1006 });10071008### app.error(function)10091010Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1011Note that we may set several error handlers by making several calls to this method, however the handler1012should call _next(err)_ if it does not wish to deal with the exception:10131014 app.error(function(err, req, res, next){1015 res.send(err.message, 500);1016 });10171018### app.helpers(obj)10191020Registers static view helpers.10211022 app.helpers({1023 name: function(first, last){ return first + ', ' + last },1024 firstName: 'tj',1025 lastName: 'holowaychuk'1026 });10271028Our view could now utilize the _firstName_ and _lastName_ variables,1029as well as the _name()_ function exposed.10301031 <%= name(firstName, lastName) %>10321033### app.dynamicHelpers(obj)10341035Registers dynamic view helpers. Dynamic view helpers1036are simply functions which accept _req_, _res_, and are1037evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1038becomes the local variable it is associated with.10391040 app.dynamicHelpers({1041 session: function(req, res){1042 return req.session;1043 }1044 });10451046All views would now have _session_ available so that session data can be accessed via _session.name_ etc:10471048 <%= session.name %>10491050### app.mounted(fn)10511052Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.10531054 var app = express.createServer(),1055 blog = express.createServer();1056 1057 blog.mounted(function(parent){1058 // parent is app1059 // "this" is blog1060 });1061 1062 app.use(blog);10631064### app.register(ext, exports)10651066Register the given template engine _exports_1067as _ext_. For example we may wish to map ".html"1068files to jade:10691070 app.register('.html', require('jade'));10711072This is also useful for libraries that may not1073match extensions correctly. For example my haml.js1074library is installed from npm as "hamljs" so instead1075of layout.hamljs, we can register the engine as ".haml":10761077 app.register('.haml', require('haml-js'));10781079For engines that do not comply with the Express1080specification, we can also wrap their api this way.10811082 app.register('.foo', {1083 render: function(str, options) {1084 // perhaps their api is1085 // return foo.toHTML(str, options);1086 }1087 });10881089### app.listen([port[, host]])10901091Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1092connections will be accepted via _INADDR_ANY_.10931094 app.listen();1095 app.listen(3000);1096 app.listen(3000, 'n.n.n.n');10971098The _port_ argument may also be a string representing the path to a unix domain socket:10991100 app.listen('/tmp/express.sock');11011102Then try it out:11031104 $ telnet /tmp/express.sock1105 GET / HTTP/1.111061107 HTTP/1.1 200 OK1108 Content-Type: text/plain1109 Content-Length: 111110 1111 Hello World