guide.md
This file
Path
docs/guide.md
1,041 lines · 33.9 KiB · Markdown
Last changed by
DocsTj Holowaychukbefore adoption0e0cc30
History of this fileTake it
The walk stopped after 200 commits: lines older than 248e7c8 point at it.
Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 1–38why, one step back12### 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 back39 app.use(express.methodOverride());40 app.use(express.bodyDecoder());41 app.use(app.router);42 app.use(express.staticProvider(__dirname + '/public'));43 });Updated connect submoduleTj Holowaychukbefore adoption248e7c8
line 44why, one step back44 DocsTj Holowaychukbefore adoption5234368
lines 45–47why, one step back45 app.configure('development', function(){46 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));47 });Updated connect submoduleTj Holowaychukbefore adoption248e7c8
line 48why, one step back48 DocsTj Holowaychukbefore adoption5234368
lines 49–51why, one step back49 app.configure('production', function(){50 app.use(express.errorHandler());51 });Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 52–66why, one step back5253For 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 });66Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab
line 67why, one step back67To alter the environment we can set the _NODE_ENV_ environment variable, for example:Updated connect submoduleTj Holowaychukbefore adoption248e7c8
line 68why, one step back68Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab
line 69why, one step back69 $ NODE_ENV=production node app.jsUpdated connect submoduleTj Holowaychukbefore adoption248e7c8
line 70why, one step back70NODE_ENV=production docs, VERY IMPORTANT do this, or your app will be slow :pTj Holowaychukbefore adoptiond4868f2
lines 71–72why, one step back71This is _very_ important, as many caching mechanisms are _only enabled_ when in production.72Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 73–81why, one step back73### Settings7475Express 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 optionsMerge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 82–83why, one step back82 * _partials_ Root view partials directory defaulting to _views_/partials.83 * _stream threshold_ Bytesize indicating when a file should be streamed for _res.sendfile()_ using _fs.ReadStream()_ and _sys.pump()_.Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 84–92why, one step back8485### Routing8687Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.88For example we may want to render a user's account for the path _/user/12_, this89can be done by defining the route below. The values associated to the named placeholders 90are available as `req.params`.9192 app.get('/user/:id', function(req, res){DocsTj Holowaychukbefore adoption5234368
lines 93–94why, one step back93 res.send('user ' + req.params.id);94 });Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 95–149why, one step back9596A route is simple a string which is compiled to a _RegExp_ internally. For example97when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:9899 \/user\/([^\/]+)\/?100101Regular expression literals may also be passed for complex uses. Since capture102groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.103104 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){105 res.send(req.params);106 });107108Curl requests against the previously defined route:109110 $ curl http://dev:3000/user111 [null,null]112 $ curl http://dev:3000/users113 [null,null]114 $ curl http://dev:3000/users/1115 ["1",null]116 $ curl http://dev:3000/users/1..15117 ["1","15"]118119Below are some route examples, and the associated paths that they120may consume:121122 "/user/:id"123 /user/12124125 "/users/:id?"126 /users/5127 /users128129 "/files/*"130 /files/jquery.js131 /files/javascripts/jquery.js132133 "/file/*.*"134 /files/jquery.js135 /files/javascripts/jquery.js136 137 "/user/:id/:operation?"138 /user/1139 /user/1/edit140 141 "/products.:format"142 /products.json143 /products.xml144145 "/products.:format?"146 /products.json147 /products.xml148 /products149DocsTj Holowaychukbefore adoption5234368
lines 150–162why, one step back150For 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_:151152 var express = require('express')153 , app = express.createServer();154155 app.use(express.bodyDecoder());156157 app.post('/', function(req, res){158 res.send(req.body);159 });160161 app.listen(3000);162Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 163–166why, one step back163### Passing Route Control164165We may pass control to the next _matching_ route, by calling the _third_ argument,166the _next()_ function. When a match cannot be made, control is passed back to Connect,Added route-middleware exampleTj Holowaychukbefore adoption4983e96
line 167why, one step back167and 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()_.Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 168–180why, one step back168169 app.get('/users/:id?', function(req, res, next){170 var id = req.params.id;171 if (id) {172 // do something173 } else {174 next();175 }176 });177 178 app.get('/users', function(req, res){179 // do something else180 });DocsTj Holowaychukbefore adoption5234368
lines 181–214why, one step back181182Express 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:183184 var express = require('express')185 , app = express.createServer();186187 var users = [{ name: 'tj' }];188189 app.all('/user/:id/:op?', function(req, res, next){190 req.user = users[req.params.id];191 if (req.user) {192 next();193 } else {194 next(new Error('cannot find user ' + req.params.id));195 }196 });197198 app.get('/user/:id', function(req, res){199 res.send('viewing ' + req.user.name);200 });201202 app.get('/user/:id/edit', function(req, res){203 res.send('editing ' + req.user.name);204 });205206 app.put('/user/:id', function(req, res){207 res.send('updating ' + req.user.name);208 });209210 app.get('*', function(req, res){211 res.send('what???', 404);212 });213214 app.listen(3000); Added route-middleware exampleTj Holowaychukbefore adoption4983e96
line 215why, one step back215Ordering docsTj Holowaychukbefore adoption296f127
lines 216–240why, one step back216### Middleware217218Middleware via [Connect](http://github.com/senchalabs/connect) can be219passed to _express.createServer()_ as you would with a regular Connect server. For example:220221 var express = require('express');222223 var app = express.createServer(224 express.logger(),225 express.bodyDecoder()226 );227228Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:229230 app.use(express.logger({ format: ':method :uri' }));231232Typically with connect middleware you would _require('connect')_ like so:233234 var connect = require('connect');235 app.use(connect.logger());236237This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:238239 app.use(express.logger());240Added route-middleware exampleTj Holowaychukbefore adoption4983e96
lines 241–243why, one step back241### Route Middleware242243Routes 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.Updated connect submoduleTj Holowaychukbefore adoption248e7c8
line 244why, one step back244Fixed docsTj Holowaychukbefore adoptioncef14ca
line 245why, one step back245Typically 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 246why, one step back246Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 247–248why, one step back247 app.get('/user/:id', function(req, res, next){248 loadUser(req.params.id, function(err, user){Doc cleanupTj Holowaychukbefore adoptionb083aed
lines 249–250why, one step back249 if (err) return next(err);250 res.send('Viewing user ' + user.name);Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 251–252why, one step back251 });252 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 253–255why, one step back253254To 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. 255Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 256–269why, one step back256 function loadUser(req, res, next) {257 // You would fetch your user from the db258 var user = users[req.params.id];259 if (user) {260 req.user = user;261 next();262 } else {263 next(new Error('Failed to load user ' + req.params.id));264 }265 }266 267 app.get('/user/:id', loadUser, function(req, res){268 res.send('Viewing user ' + req.user.name);269 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 270–272why, one step back270271Multiple 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.272Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 273–274why, one step back273 function andRestrictToSelf(req, res, next) {274 req.authenticatedUser.id == req.user.idDoc cleanupTj Holowaychukbefore adoptionb083aed
lines 275–276why, one step back275 ? next()276 : next(new Error('Unauthorized'));Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 277–281why, one step back277 }278 279 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){280 res.send('Editing user ' + req.user.name);281 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
line 282why, one step back282Fixed docsTj Holowaychukbefore adoptioncef14ca
line 283why, one step back283Keeping 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 284why, one step back284Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 285–287why, one step back285 function andRestrictTo(role) {286 return function(req, res, next) {287 req.authenticatedUser.role == roleDoc cleanupTj Holowaychukbefore adoptionb083aed
lines 288–289why, one step back288 ? next()289 : next(new Error('Unauthorized'));Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 290–296why, one step back290 }291 }292 293 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){294 res.send('Deleted user ' + req.user.name);295 });296Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 297–298why, one step back297Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.298Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 299–308why, one step back299 var a = [middleware1, middleware2]300 , b = [middleware3, middleware4]301 , all = [a, b];302 303 app.get('/foo', a, function(){});304 app.get('/bar', a, function(){});305 306 app.get('/', a, middleware3, middleware4, function(){});307 app.get('/', a, b, function(){});308 app.get('/', all, function(){});Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 309–311why, one step back309310For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.311HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 312–317why, one step back312### HTTP Methods313314We 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.315316 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.317 Doc typoTj Holowaychukbefore adoptionc9268f2
lines 318–322why, one step back318 <form method="post" action="/">319 <input type="text" name="user[name]" />320 <input type="text" name="user[email]" />321 <input type="submit" value="Submit" />322 </form>HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 323–352why, one step back323324By 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:325326 app.use(express.bodyDecoder());327328Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.329330 app.post('/', function(req, res){331 console.log(req.body.user);332 res.redirect('back');333 });334335When 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.336337 app.use(express.bodyDecoder());338 app.use(express.methodOverride());339340The 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:341342 <form method="post" action="/">343 <input type="hidden" name="_method" value="put" />344 <input type="text" name="user[name]" />345 <input type="text" name="user[email]" />346 <input type="submit" value="Submit" /> 347 </form>348349 app.put('/', function(){350 console.log(req.body.user);351 res.redirect('back');352 });Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 353–462why, one step back353354### Error Handling355356Express provides the _app.error()_ method which receives exceptions thrown within a route,357or passed to _next(err)_. Below is an example which serves different pages based on our358ad-hoc _NotFound_ exception:359360 function NotFound(msg){361 this.name = 'NotFound';362 Error.call(this, msg);363 Error.captureStackTrace(this, arguments.callee);364 }365366 sys.inherits(NotFound, Error);367368 app.get('/404', function(req, res){369 throw new NotFound;370 });371372 app.get('/500', function(req, res){373 throw new Error('keyboard cat!');374 });375376We can call _app.error()_ several times as shown below.377Here we check for an instanceof _NotFound_ and show the378404 page, or we pass on to the next error handler.379380Note that these handlers can be defined anywhere, as they381will be placed below the route handlers on _listen()_. This 382allows for definition within _configure()_ blocks so we can383handle exceptions in different ways based on the environment.384385 app.error(function(err, req, res, next){386 if (err instanceof NotFound) {387 res.render('404.jade');388 } else {389 next(err);390 }391 });392393Here we assume all errors as 500 for the simplicity of394this demo, however you can choose whatever you like395396 app.error(function(err, req, res){397 res.render('500.jade', {398 locals: {399 error: err400 } 401 });402 });403404Our apps could also utilize the Connect _errorHandler_ middleware405to report on exceptions. For example if we wish to output exceptions 406in "development" mode to _stderr_ we can use:407408 app.use(express.errorHandler({ dumpExceptions: true }));409410Also during development we may want fancy html pages to show exceptions411that are passed or thrown, so we can set _showStack_ to true:412413 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));414415The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_416is present, which is useful for developing apps that rely heavily on client-side JavaScript.417418### View Rendering419420View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name421of the module that will be required. For example the view _layout.ejs_ will422tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 423_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.424425Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,426and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 427the _body_ local variable in _layout.haml_.428429 app.get('/', function(req, res){430 res.render('index.haml', {431 locals: { title: 'My Site' }432 });433 });434435The new _view engine_ setting allows us to specify our default template engine,436so for example when using [Jade](http://github.com/visionmedia/jade) we could set:437438 app.set('view engine', 'jade');439440Allowing us to render with:441442 res.render('index');443444vs:445446 res.render('index.jade');447448When _view engine_ is set, extensions are entirely optional, however we can still449mix and match template engines:450451 res.render('another-page.ejs');452453Express 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:454455 app.set('view options', {456 layout: false457 });458459Which can then be overridden within the `res.render()` call if need be:460461 res.render('myview.ejs', { layout: true });462Docs for layout optionTj Holowaychukbefore adoption0a96621
lines 463–474why, one step back463When 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:464465 res.render('page', { layout: 'mylayout' });466467Otherwise we must specify the extension:468469 res.render('page', { layout: 'mylayout.jade' });470471These paths may also be absolute:472473 res.render('page', { layout: __dirname + '/../../mylayout.jade' });474Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 475–497why, one step back475A good example of this is specifying custom _ejs_ opening and closing tags:476477 app.set('view options', {478 open: '{{',479 close: '}}'480 });481482### View Partials483484The Express view system has built-in support for partials and collections, which are485sort of "mini" views representing a document fragment. For example rather than iterating486in a view to display comments, we would use a partial with collection support:487488 partial('comment.haml', { collection: comments });489490To make things even less verbose we can assume the extension as _.haml_ when omitted,491however if we wished we could use an ejs partial, within a haml view for example.492493 partial('comment', { collection: comments });494495And once again even further, when rendering a collection we can simply pass496an array, if no other options are desired:497More partial() docsTj Holowaychukbefore adoptione87d637
line 498why, one step back498 partial('comment', comments);Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 499–505why, one step back499500When using the partial collection support a few "magic" variables are provided501for free:502503 * _firstInCollection_ True if this is the first object504 * _indexInCollection_ Index of the object in the collection505 * _lastInCollection_ True if this is the last objectMore partial() docsTj Holowaychukbefore adoptione87d637
line 506why, one step back506 * _collectionLength_ Length of the collectionUpdated connect submoduleTj Holowaychukbefore adoption248e7c8
line 507why, one step back507More partial() docsTj Holowaychukbefore adoptione87d637
lines 508–509why, one step back508For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).509Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 510–516why, one step back510### Template Engines511512Below are a few template engines commonly used with Express:513514 * [Jade](http://jade-lang.com) haml.js successor515 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templates516 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScriptAdded CoffeeKup as a suggested template engine (let me know of others please :) )Tj Holowaychukbefore adoption687e435
line 517why, one step back517 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templatingAdded link to node-jqtpl template engineTj Holowaychukbefore adoptioncccda60
line 518why, one step back518 * [jQuery Templates](https://github.com/kof/node-jqtpl) for nodeAdded session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe
lines 519–531why, one step back519520### Session Support521522Sessions 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_.523524 app.use(express.cookieDecoder());525 app.use(express.session());526527By 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:528529 var RedisStore = require('connect-redis');530 app.use(express.cookieDecoder());531 app.use(express.session({ store: new RedisStore }));Updated connect submoduleTj Holowaychukbefore adoption248e7c8
line 532why, one step back532More session docsTj Holowaychukbefore adoption4bc8a86
lines 533–535why, one step back533Now 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:534535 var RedisStore = require('connect-redis');Doc typoTj Holowaychukbefore adoption7da2743
line 536why, one step back536 app.use(express.bodyDecoder());More session docsTj Holowaychukbefore adoption4bc8a86
lines 537–559why, one step back537 app.use(express.cookieDecoder());538 app.use(express.session({ store: new RedisStore }));539540 app.post('/add-to-cart', function(req, res){541 // Perhaps we posted several items with a form542 // (use the bodyDecoder() middleware for this)543 var items = req.body.items;544 req.session.items = items;545 res.redirect('back');546 });547548 app.get('/add-to-cart', function(req, res){549 // When redirected back to GET /add-to-cart550 // we could check req.session.items && req.session.items.length551 // to print out a message552 if (req.session.items && req.session.items.length) {553 req.flash('info', 'You have %s items in your cart', req.session.items.length);554 }555 res.render('shopping-cart');556 });557558The _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.559Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc
lines 560–563why, one step back560### Migration Guide561562 Pre-beta Express developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.563Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 564–595why, one step back564### req.header(key[, defaultValue])565566Get the case-insensitive request header _key_, with optional _defaultValue_:567568 req.header('Host');569 req.header('host');570 req.header('Accept', '*/*');571572### req.accepts(type)573574Check if the _Accept_ header is present, and includes the given _type_.575576When the _Accept_ header is not present _true_ is returned. Otherwise577the given _type_ is matched by an exact match, and then subtypes. You578may pass the subtype such as "html" which is then converted internally579to "text/html" using the mime lookup table.580581 // Accept: text/html582 req.accepts('html');583 // => true584585 // Accept: text/*; application/json586 req.accepts('html');587 req.accepts('text/html');588 req.accepts('text/plain');589 req.accepts('application/json');590 // => true591592 req.accepts('image/png');593 req.accepts('png');594 // => false595Added req.is() docsTj Holowaychukbefore adoption806aefa
lines 596–633why, one step back596### req.is(type)597598Check if the incoming request contains the _Content-Type_599header field, and it contains the give mime _type_.600 601 // With Content-Type: text/html; charset=utf-8602 req.is('html');603 req.is('text/html');604 // => true605 606 // When Content-Type is application/json607 req.is('json');608 req.is('application/json');609 // => true610 611 req.is('html');612 // => false613 614Ad-hoc callbacks can also be registered with Express, to perform615assertions again the request, for example if we need an expressive616way to check if our incoming request is an image, we can register _"an image"_617callback:618 619 app.is('an image', function(req){620 return 0 == req.headers['content-type'].indexOf('image');621 });622 623Now within our route callbacks, we can use to to assert content types624such as _"image/jpeg"_, _"image/png"_, etc.625 626 app.post('/image/upload', function(req, res, next){627 if (req.is('an image')) {628 // do something629 } else {630 next();631 }632 });633More is() docsTj Holowaychukbefore adoption071ea95
lines 634–636why, one step back634Keep in mind this method is _not_ limited to checking _Content-Type_, you635can perform any request assertion you wish.636Merge branch 'is'Tj Holowaychukbefore adoption7a71380
lines 637–644why, one step back637Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:638639 req.is('image/*');640641We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.642643 req.is('*/json');644Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 645–719why, one step back645### req.param(name)646647Return the value of param _name_ when present.648649 - Checks route placeholders (_req.params_), ex: /user/:id650 - Checks query string params (_req.query_), ex: ?id=12651 - Checks urlencoded body params (_req.body_), ex: id=12652653To utilize urlencoded request bodies, _req.body_654should be an object. This can be done by using655the _express.bodyDecoder_ middleware.656657### req.flash(type[, msg])658659Queue flash _msg_ of the given _type_.660661 req.flash('info', 'email sent');662 req.flash('error', 'email delivery failed');663 req.flash('info', 'email re-sent');664 // => 2665666 req.flash('info');667 // => ['email sent', 'email re-sent']668669 req.flash('info');670 // => []671672 req.flash();673 // => { error: ['email delivery failed'], info: [] }674675Flash notification message may also utilize formatters, by default only the %s string formatter is available:676677 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);678679### req.isXMLHttpRequest680681Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header682to see if it was issued by an _XMLHttpRequest_:683684 req.xhr685 req.isXMLHttpRequest686687### res.header(key[, val])688689Get or set the response header _key_.690691 res.header('Content-Length');692 // => undefined693694 res.header('Content-Length', 123);695 // => 123696697 res.header('Content-Length');698 // => 123699700### res.contentType(type)701702Sets the _Content-Type_ response header to the given _type_.703704 var filename = 'path/to/image.png';705 res.contentType(filename);706 // res.headers['Content-Type'] is now "image/png"707708### res.attachment([filename])709710Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.711712 res.attachment('path/to/my/image.png');713714### res.sendfile(path)715716Used by `res.download()` to transfer an arbitrary file. 717718 res.sendfile('path/to/my.file');719Merge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 720–730why, one step back720This 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.721722 res.sendfile(path, function(err, path){723 if (err) {724 // handle the error725 } else {726 console.log('transferred %s', path);727 }728 });729730When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 731–749why, one step back731732### res.download(file[, filename])733734Transfer the given _file_ as an attachment with optional alternative _filename_.735736 res.download('path/to/image.png');737 res.download('path/to/image.png', 'foo.png');738739This is equivalent to:740741 res.attachment(file);742 res.sendfile(file);743744### res.send(body|status[, headers|status[, status]])745746The `res.send()` method is a high level response utility allowing you to pass747objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status748code based responses. The following are all valid uses:749Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
line 750why, one step back750 res.send(); // 204Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 751–775why, one step back751 res.send(new Buffer('wahoo'));752 res.send({ some: 'json' });753 res.send('<p>some html</p>');754 res.send('Sorry, cant find that', 404);755 res.send('text', { 'Content-Type': 'text/plain' }, 201);756 res.send(404);757758By default the _Content-Type_ response header is set, however if explicitly759assigned through `res.send()` or previously with `res.header()` or `res.contentType()`760it will not be set again.761762### res.redirect(url[, status])763764Redirect to the given _url_ with a default response _status_ of 302.765766 res.redirect('/', 301);767 res.redirect('/account');768 res.redirect('http://google.com');769 res.redirect('home');770 res.redirect('back');771772Express supports "redirect mapping", which by default provides _home_, and _back_.773The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes774the "home" setting and defaults to "/".775Cookie docsTj Holowaychukbefore adoptiona89767c
lines 776–796why, one step back776### res.cookie(name, val[, options])777778Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.779780 // "Remember me" for 15 minutes 781 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });782783To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:784785 app.use(express.cookieDecoder());786 787 app.get('/', function(req, res){788 // use req.cookies.rememberme789 });790791### res.clearCookie(name)792793Clear cookie _name_ by setting "expires" far in the past.794795 res.clearCookie('rememberme');796Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 797–805why, one step back797### res.render(view[, options[, fn]])798799Render _view_ with the given _options_ and optional callback _fn_.800When a callback function is given a response will _not_ be made801automatically, however otherwise a response of _200_ and _text/html_ is given.802803 Most engines accept one or more of the following options,804 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:805Updated docsTj Holowaychukbefore adoptionfd4c88d
line 806why, one step back806 - _scope_ Template evaluation context (value of _this_)Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 807–808why, one step back807 - _locals_ Object containing local variables808 - _debug_ Output debugging informationMerge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
lines 809–810why, one step back809 - _status_ Response status code, defaults to 200810 - _headers_ Response headers objectUpdated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 811–816why, one step back811812### res.partial(view[, options])813814Render _view_ partial with the given _options_. This method is always available815to the view as a local variable.816New partial() docsTj Holowaychukbefore adoption1c90332
lines 817–818why, one step back817- _object_ the object named by _as_ or derived from the view name818- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 819–828why, one step back819 * as: 'something' will add the _something_ local variable820 * as: this will use the collection value as the template context821 * as: global will merge the collection value's properties with _locals_822823- _collection_ Array of objects, the name is derived from the view name itself. 824 For example _video.html_ will have a object _video_ available to it.825826The following are equivalent, and the name of collection value when passed827to the partial will be _movie_ as derived from the name.828More partial() docsTj Holowaychukbefore adoptione87d637
lines 829–830why, one step back829 partial('theatre/movie.jade', { collection: movies });830 partial('theatre/movie.jade', movies);Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 831–849why, one step back831 partial('movie.jade', { collection: movies });832 partial('movie.jade', movies);833 partial('movie', movies);834 // In view: movie.director835836To change the local from _movie_ to _video_ we can use the "as" option:837838 partial('movie', { collection: movies, as: 'video' });839 // In view: video.director840841Also we can make our movie the value of _this_ within our view so that instead842of _movie.director_ we could use _this.director_.843844 partial('movie', { collection: movies, as: this });845 // In view: this.director846847Another alternative is to "explode" the properties of the collection item into848pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:849New partial() docsTj Holowaychukbefore adoption1c90332
line 850why, one step back850 partial('movie', { collection: movies, as: global });Updated connect submoduleTj Holowaychukbefore adoption248e7c8
line 851why, one step back851 // In view: directorNew partial() docsTj Holowaychukbefore adoption1c90332
lines 852–870why, one step back852853This same logic applies to a single partial object usage:854855 partial('movie', { object: movie, as: this });856 // In view: this.director857858 partial('movie', { object: movie, as: global });859 // In view: director860861 partial('movie', { object: movie, as: 'video' });862 // In view: video.director863864 partial('movie', { object: movie });865 // In view: movie.director866867When 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:868869 partial('movie', movie);870 // => In view: movie.directorUpdated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 871–880why, one step back871872### app.set(name[, val])873874Apply an application level setting _name_ to _val_, or875get the value of _name_ when _val_ is not present:876877 app.set('views', __dirname + '/views');878 app.set('views');879 // => ...path...880Settings docsTj Holowaychukbefore adoptione562adc
lines 881–885why, one step back881Alternatively you may simply access the settings via _app.settings_:882883 app.settings.views884 // => ...path...885Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 886–1014why, one step back886### app.enable(name)887888Enable the given setting _name_:889890 app.enable('some arbitrary setting');891 app.set('some arbitrary setting');892 // => true893894### app.disable(name)895896Disable the given setting _name_:897898 app.disable('some setting');899 app.set('some setting');900 // => false901902### app.configure(env|function[, function])903904Define a callback function for the given _env_ (or all environments) with callback _function_:905906 app.configure(function(){907 // executed for each env908 });909910 app.configure('development', function(){911 // executed for 'development' only912 });913914### app.redirect(name, val)915916For use with `res.redirect()` we can map redirects at the application level as shown below:917918 app.redirect('google', 'http://google.com');919920Now in a route we may call:921922 res.redirect('google');923924We may also map dynamic redirects:925926 app.redirect('comments', function(req, res){927 return '/post/' + req.params.id + '/comments';928 });929930So now we may do the following, and the redirect will dynamically adjust to931the context of the request. If we called this route with _GET /post/12_ our932redirect _Location_ would be _/post/12/comments_.933934 app.get('/post/:id', function(req, res){935 res.redirect('comments');936 });937938### app.error(function)939940Adds an error handler _function_ which will receive the exception as the first parameter as shown below.941Note that we may set several error handlers by making several calls to this method, however the handler942should call _next(err)_ if it does not wish to deal with the exception:943944 app.error(function(err, req, res, next){945 res.send(err.message, 500);946 });947948### app.helpers(obj)949950Registers static view helpers.951952 app.helpers({953 name: function(first, last){ return first + ', ' + last },954 firstName: 'tj',955 lastName: 'holowaychuk'956 });957958Our view could now utilize the _firstName_ and _lastName_ variables,959as well as the _name()_ function exposed.960961 <%= name(firstName, lastName) %>962963### app.dynamicHelpers(obj)964965Registers dynamic view helpers. Dynamic view helpers966are simply functions which accept _req_, _res_, and are967evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function968becomes the local variable it is associated with.969970 app.dynamicHelpers({971 session: function(req, res){972 return req.session;973 }974 });975976All views would now have _session_ available so that session data can be accessed via _session.name_ etc:977978 <%= session.name %>979980### app.mounted(fn)981982Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.983984 var app = express.createServer(),985 blog = express.createServer();986 987 blog.mounted(function(parent){988 // parent is app989 // "this" is blog990 });991 992 app.use(blog);993994### app.register(ext, exports)995996Register the given template engine _exports_997as _ext_. For example we may wish to map ".html"998files to jade:9991000 app.register('.html', require('jade'));10011002This is also useful for libraries that may not1003match extensions correctly. For example my haml.js1004library is installed from npm as "hamljs" so instead1005of layout.hamljs, we can register the engine as ".haml":10061007 app.register('.haml', require('haml-js'));10081009For engines that do not comply with the Express1010specification, we can also wrap their api this way.10111012 app.register('.foo', {1013 render: function(str, options) {1014 // perhaps their api isFix up app.register() docs. Closes #450Tj Holowaychukbefore adoption6ef6ba7
line 1015why, one step back1015 // return foo.toHTML(str, options);Updated connect submoduleTj Holowaychukbefore adoption248e7c8
lines 1016–1041why, one step back1016 }1017 });10181019### app.listen([port[, host]])10201021Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1022connections will be accepted via _INADDR_ANY_.10231024 app.listen();1025 app.listen(3000);1026 app.listen(3000, 'n.n.n.n');10271028The _port_ argument may also be a string representing the path to a unix domain socket:10291030 app.listen('/tmp/express.sock');10311032Then try it out:10331034 $ telnet /tmp/express.sock1035 GET / HTTP/1.110361037 HTTP/1.1 200 OK1038 Content-Type: text/plain1039 Content-Length: 111040 1041 Hello World