guide.md
This file
Path
docs/guide.md
1,406 lines · 48.7 KiB · Markdown
Last changed by
Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
History of this fileTake it
The walk stopped after 200 commits: lines older than eefe51c point at it.
removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 1–4why, one step back1### Installation23 $ npm install express4added quick start to guideTj Holowaychukbefore adoption723774a
lines 5–25why, one step back5or to access the `express(1)` executable install globally:67 $ npm install -g express89## Quick Start1011 The quickest way to get started with express is to utilize the executable `express(1)` to generate an application as shown below:1213 Create the app:1415 $ npm install -g express16 $ express /tmp/foo && cd /tmp/foo1718 Install dependencies:1920 $ npm install -d2122 Start the server:2324 $ node app.js25removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 26–104why, one step back26### Creating A Server2728 To create an instance of the _express.HTTPServer_, simply invoke the _createServer()_ method. With our instance _app_ we can then define routes based on the HTTP verbs, in this example _app.get()_.2930 var app = require('express').createServer();31 32 app.get('/', function(req, res){33 res.send('hello world');34 });35 36 app.listen(3000);3738### Creating An HTTPS Server3940 To initialize a _express.HTTPSServer_ we do the same as above, however we41 pass an options object, accepting _key_, _cert_ and the others mentioned in node's [https documentation](http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer).42 43 var app = require('express').createServer({ key: ... });4445### Configuration4647Express supports arbitrary environments, such as _production_ and _development_. Developers48can use the _configure()_ method to setup needs required by the current environment. When49_configure()_ is called without an environment name it will be run in _every_ environment 50prior to the environment specific callback.5152In the example below we only _dumpExceptions_, and respond with exception stack traces53in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.54Note the use of _app.router_, which can (optionally) be used to mount the application routes,55otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.5657 app.configure(function(){58 app.use(express.methodOverride());59 app.use(express.bodyParser());60 app.use(app.router);61 });62 63 app.configure('development', function(){64 app.use(express.static(__dirname + '/public'));65 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));66 });67 68 app.configure('production', function(){69 var oneYear = 31557600000;70 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));71 app.use(express.errorHandler());72 });7374For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:7576 app.configure(function(){77 app.set('views', __dirname + '/views');78 app.set('views');79 // => "/absolute/path/to/views"80 81 app.enable('some feature');82 // same as app.set('some feature', true);83 84 app.disable('some feature');85 // same as app.set('some feature', false);86 87 app.enabled('some feature')88 // => false89 });9091To alter the environment we can set the _NODE_ENV_ environment variable, for example:9293 $ NODE_ENV=production node app.js9495This is _very_ important, as many caching mechanisms are _only enabled_ when in production.9697### Settings9899Express supports the following settings out of the box:100101 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.102 * _views_ Root views directory defaulting to **CWD/views**103 * _view engine_ Default view engine name for views rendered without extensions104 * _view options_ An object specifying global view optionsdocs for "view cache" settingTj Holowaychukbefore adoption805b9ac
line 105why, one step back105 * _view cache_ Enable view caching (enabled in production)Added "case sensitive routes" option.Tj Holowaychukbefore adoptiond2adcbd
line 106why, one step back106 * _case sensitive routes_ Enable case-sensitive routingremoved manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 107–189why, one step back107108### Routing109110Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.111For example we may want to render a user's account for the path _/user/12_, this112can be done by defining the route below. The values associated to the named placeholders 113are available as `req.params`.114115 app.get('/user/:id', function(req, res){116 res.send('user ' + req.params.id);117 });118119A route is simple a string which is compiled to a _RegExp_ internally. For example120when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:121122 \/user\/([^\/]+)\/?123124Regular expression literals may also be passed for complex uses. Since capture125groups 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]_.126127 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){128 res.send(req.params);129 });130131Curl requests against the previously defined route:132133 $ curl http://dev:3000/user134 [null,null]135 $ curl http://dev:3000/users136 [null,null]137 $ curl http://dev:3000/users/1138 ["1",null]139 $ curl http://dev:3000/users/1..15140 ["1","15"]141142Below are some route examples, and the associated paths that they143may consume:144145 "/user/:id"146 /user/12147148 "/users/:id?"149 /users/5150 /users151152 "/files/*"153 /files/jquery.js154 /files/javascripts/jquery.js155156 "/file/*.*"157 /files/jquery.js158 /files/javascripts/jquery.js159 160 "/user/:id/:operation?"161 /user/1162 /user/1/edit163 164 "/products.:format"165 /products.json166 /products.xml167168 "/products.:format?"169 /products.json170 /products.xml171 /products172 173 "/user/:id.:format?"174 /user/12175 /user/12.json176177For example we can __POST__ some json, and echo the json back using the _bodyParser_ middleware which will parse json request bodies (as well as others), and place the result in _req.body_:178179 var express = require('express')180 , app = express.createServer();181182 app.use(express.bodyParser());183184 app.post('/', function(req, res){185 res.send(req.body);186 });187188 app.listen(3000);189docsTj Holowaychukbefore adoption6106188
line 190why, one step back190Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use _'/user/:id([0-9]+)'_ which will _not_ match unless the placeholder value contains only digits.removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 191–258why, one step back191192### Passing Route Control193194We may pass control to the next _matching_ route, by calling the _third_ argument,195the _next()_ function. When a match cannot be made, control is passed back to Connect,196and middleware continue to be invoked in the order that they are added via _use()_. 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()_ and decides to respond.197198 app.get('/users/:id?', function(req, res, next){199 var id = req.params.id;200 if (id) {201 // do something202 } else {203 next();204 }205 });206 207 app.get('/users', function(req, res){208 // do something else209 });210211The _app.all()_ method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to _req.user_.212213 var express = require('express')214 , app = express.createServer();215216 var users = [{ name: 'tj' }];217218 app.all('/user/:id/:op?', function(req, res, next){219 req.user = users[req.params.id];220 if (req.user) {221 next();222 } else {223 next(new Error('cannot find user ' + req.params.id));224 }225 });226227 app.get('/user/:id', function(req, res){228 res.send('viewing ' + req.user.name);229 });230231 app.get('/user/:id/edit', function(req, res){232 res.send('editing ' + req.user.name);233 });234235 app.put('/user/:id', function(req, res){236 res.send('updating ' + req.user.name);237 });238239 app.get('*', function(req, res){240 res.send('what???', 404);241 });242243 app.listen(3000); 244245### Middleware246247Middleware via [Connect](http://github.com/senchalabs/connect) can be248passed to _express.createServer()_ as you would with a regular Connect server. For example:249250 var express = require('express');251252 var app = express.createServer(253 express.logger()254 , express.bodyParser()255 );256257Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.258Merge pull request #671 from jpalardy/patch-1TJ Holowaychukbefore adoptionc24b2fa
line 259why, one step back259 app.use(express.logger({ format: ':method :url' }));removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 260–271why, one step back260261Typically with connect middleware you would _require('connect')_ like so:262263 var connect = require('connect');264 app.use(connect.logger());265 app.use(connect.bodyParser());266267This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:268269 app.use(express.logger());270 app.use(express.bodyParser());271added better middleware docs and use-casesTj Holowaychukbefore adoption8d6f167
lines 272–298why, one step back272Middleware ordering is important, when Connect receives a request the _first_ middleware we pass to _createServer()_ or _use()_ is executed with three parameters, _request_, _response_, and a callback function usually named _next_. When _next()_ is invoked the second middleware will then have it's turn and so on. This is important to note because many middleware depend on each other, for example _methodOverride()_ checks _req.body._method_ for the HTTP method override, however _bodyParser()_ parses the request body and populates _req.body_. Another example of this is cookie parsing and session support, we must first _use()_ _cookieParser()_ followed by _session()_.273274Many Express applications may contain the line _app.use(app.router)_, while this may appear strange, it's simply the middleware function that contains all defined routes, and performs route lookup based on the current request url and HTTP method. Express allows you to position this middleware, though by default it will be added to the bottom. By positioning the router, we can alter middleware precedence, for example we may want to add error reporting as the _last_ middleware so that any exception passed to _next()_ will be handled by it, or perhaps we want static file serving to have low precedence, allowing our routes to intercept requests to a static file to count downloads etc. This may look a little like below275276 app.use(express.logger(...));277 app.use(express.bodyParser(...));278 app.use(express.cookieParser(...));279 app.use(express.session(...));280 app.use(app.router);281 app.use(express.static(...));282 app.use(express.errorHandler(...));283284First we add _logger()_ so that it may wrap node's _req.end()_ method, providing us with response-time data. Next the request's body will be parsed (if any), followed by cookie parsing and session support, meaning _req.session_ will be defined by the time we hit our routes in _app.router_. If a request such as _GET /javascripts/jquery.js_ is handled by our routes, and we do not call _next()_ then the _static()_ middleware will never see this request, however if were to define a route as shown below, we can record stats, refuse downloads, consume download credits etc.285286 var downloads = {};287288 app.use(app.router);289 app.use(express.static(__dirname + '/public'));290291 app.get('/*', function(req, res, next){292 var file = req.params[0];293 downloads[file] = downloads[file] || 0;294 downloads[file]++;295 next();296 });297298removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 299–369why, one step back299### Route Middleware300301Routes 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.302303Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 304305 app.get('/user/:id', function(req, res, next){306 loadUser(req.params.id, function(err, user){307 if (err) return next(err);308 res.send('Viewing user ' + user.name);309 });310 });311312To 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. 313314 function loadUser(req, res, next) {315 // You would fetch your user from the db316 var user = users[req.params.id];317 if (user) {318 req.user = user;319 next();320 } else {321 next(new Error('Failed to load user ' + req.params.id));322 }323 }324 325 app.get('/user/:id', loadUser, function(req, res){326 res.send('Viewing user ' + req.user.name);327 });328329Multiple 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.330331 function andRestrictToSelf(req, res, next) {332 req.authenticatedUser.id == req.user.id333 ? next()334 : next(new Error('Unauthorized'));335 }336 337 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){338 res.send('Editing user ' + req.user.name);339 });340341Keeping 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.342343 function andRestrictTo(role) {344 return function(req, res, next) {345 req.authenticatedUser.role == role346 ? next()347 : next(new Error('Unauthorized'));348 }349 }350 351 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){352 res.send('Deleted user ' + req.user.name);353 });354355Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.356357 var a = [middleware1, middleware2]358 , b = [middleware3, middleware4]359 , all = [a, b];360 361 app.get('/foo', a, function(){});362 app.get('/bar', a, function(){});363 364 app.get('/', a, middleware3, middleware4, function(){});365 app.get('/', a, b, function(){});366 app.get('/', all, function(){});367368For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.369docs for next("route"). Closes #650Tj Holowaychukbefore adoption2648302
lines 370–371why, one step back370There are times when we may want to "skip" passed remaining route middleware, but continue matching subsequent routes. To do this we invoke `next()` with the string "route" `next('route')`. If no remaining routes match the request url then Express will respond with 404 Not Found.371removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 372–425why, one step back372### HTTP Methods373374We 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.375376 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.377 378 <form method="post" action="/">379 <input type="text" name="user[name]" />380 <input type="text" name="user[email]" />381 <input type="submit" value="Submit" />382 </form>383384By default Express does not know what to do with this request body, so we should add the _bodyParser_ middleware, which will parse _application/x-www-form-urlencoded_ and _application/json_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:385386 app.use(express.bodyParser());387388Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.389390 app.post('/', function(req, res){391 console.log(req.body.user);392 res.redirect('back');393 });394395When 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 _bodyParser_ so that it can utilize it's _req.body_ containing the form values.396397 app.use(express.bodyParser());398 app.use(express.methodOverride());399400The 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:401402 <form method="post" action="/">403 <input type="hidden" name="_method" value="put" />404 <input type="text" name="user[name]" />405 <input type="text" name="user[email]" />406 <input type="submit" value="Submit" /> 407 </form>408409 app.put('/', function(){410 console.log(req.body.user);411 res.redirect('back');412 });413414### Error Handling415416Express provides the _app.error()_ method which receives exceptions thrown within a route,417or passed to _next(err)_. Below is an example which serves different pages based on our418ad-hoc _NotFound_ exception:419420 function NotFound(msg){421 this.name = 'NotFound';422 Error.call(this, msg);423 Error.captureStackTrace(this, arguments.callee);424 }425 doc typoTj Holowaychukbefore adoptionfae1ba9
line 426why, one step back426 NotFound.prototype.__proto__ = Error.prototype;removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 427–617why, one step back427 428 app.get('/404', function(req, res){429 throw new NotFound;430 });431 432 app.get('/500', function(req, res){433 throw new Error('keyboard cat!');434 });435436We can call _app.error()_ several times as shown below.437Here we check for an instanceof _NotFound_ and show the438404 page, or we pass on to the next error handler.439440Note that these handlers can be defined anywhere, as they441will be placed below the route handlers on _listen()_. This 442allows for definition within _configure()_ blocks so we can443handle exceptions in different ways based on the environment.444445 app.error(function(err, req, res, next){446 if (err instanceof NotFound) {447 res.render('404.jade');448 } else {449 next(err);450 }451 });452453Here we assume all errors as 500 for the simplicity of454this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the _error.code_ of _ENOENT_, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.455456 app.error(function(err, req, res){457 res.render('500.jade', {458 error: err459 });460 });461462Our apps could also utilize the Connect _errorHandler_ middleware463to report on exceptions. For example if we wish to output exceptions 464in "development" mode to _stderr_ we can use:465466 app.use(express.errorHandler({ dumpExceptions: true }));467468Also during development we may want fancy html pages to show exceptions469that are passed or thrown, so we can set _showStack_ to true:470471 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));472473The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_474is present, which is useful for developing apps that rely heavily on client-side JavaScript.475476### Route Param Pre-conditions477478Route param 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:479480 app.get('/user/:userId', function(req, res, next){481 User.get(req.params.userId, function(err, user){482 if (err) return next(err);483 res.send('user ' + user.name);484 });485 }); 486487With preconditions our params 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.488489 app.param('userId', function(req, res, next, id){490 User.get(id, function(err, user){491 if (err) return next(err);492 if (!user) return next(new Error('failed to find user'));493 req.user = user;494 next();495 });496 });497498Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:499500 app.get('/user/:userId', function(req, res){501 res.send('user ' + req.user.name);502 });503504### View Rendering505506View filenames take the form "<name>.<engine>", where <engine> is the name507of the module that will be required. For example the view _layout.ejs_ will508tell the view system to _require('ejs')_, the module being loaded must export the method _exports.compile(str, options)_, and return a _Function_ to comply with Express. To alter this behaviour509_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.510511Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,512and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 513the _body_ local variable in _layout.jade_.514515 app.get('/', function(req, res){516 res.render('index.jade', { title: 'My Site' });517 });518519The new _view engine_ setting allows us to specify our default template engine,520so for example when using jade we could set:521522 app.set('view engine', 'jade');523524Allowing us to render with:525526 res.render('index');527528vs:529530 res.render('index.jade');531532When _view engine_ is set, extensions are entirely optional, however we can still533mix and match template engines:534535 res.render('another-page.ejs');536537Express 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:538539 app.set('view options', {540 layout: false541 });542543Which can then be overridden within the _res.render()_ call if need be:544545 res.render('myview.ejs', { layout: true });546547When 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:548549 res.render('page', { layout: 'mylayout' });550551Otherwise we must specify the extension:552553 res.render('page', { layout: 'mylayout.jade' });554555These paths may also be absolute:556557 res.render('page', { layout: __dirname + '/../../mylayout.jade' });558559A good example of this is specifying custom _ejs_ opening and closing tags:560561 app.set('view options', {562 open: '{{',563 close: '}}'564 });565566### View Partials567568The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating569in a view to display comments, we could use partial collection:570571 partial('comment', { collection: comments });572573If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:574575 partial('comment', comments);576577When using the partial collection support a few "magic" locals are provided578for free:579580 * _firstInCollection_ true if this is the first object581 * _indexInCollection_ index of the object in the collection582 * _lastInCollection_ true if this is the last object583 * _collectionLength_ length of the collection584585Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well. So for example if we were to render a blog post with _partial('blog/post', post)_ it would generate the _post_ local, but the view calling this function had the local _user_, it would be available to the _blog/post_ view as well.586587For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).588589__NOTE:__ be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead.590591### View Lookup592593View lookup is performed relative to the parent view, for example if we had a page view named _views/user/list.jade_, and within that view we did _partial('edit')_ it would attempt to load _views/user/edit.jade_, whereas _partial('../messages')_ would load _views/messages.jade_.594595The view system also allows for index templates, allowing you to have a directory of the same name. For example within a route we may have _res.render('users')_ either _views/users.jade_, or _views/users/index.jade_.596597When utilizing index views as shown above, we may reference _views/users/index.jade_ from a view in the same directory by _partial('users')_, and the view system will try _../users/index_, preventing us from needing to call _partial('index')_.598599### Template Engines600601Below are a few template engines commonly used with Express:602603 * [Haml](http://github.com/visionmedia/haml.js) haml implementation604 * [Jade](http://jade-lang.com) haml.js successor605 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript606 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating607 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node608609### Session Support610611Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieParser_ middleware place above it, which will parse and populate cookie data to _req.cookies_.612613 app.use(express.cookieParser());614 app.use(express.session({ secret: "keyboard cat" }));615616By 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:617Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4
line 618why, one step back618 var RedisStore = require('connect-redis')(express);removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 619–623why, one step back619 app.use(express.cookieParser());620 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));621622Now 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:623Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4
line 624why, one step back624 var RedisStore = require('connect-redis')(express);removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 625–755why, one step back625 app.use(express.bodyParser());626 app.use(express.cookieParser());627 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));628629 app.post('/add-to-cart', function(req, res){630 // Perhaps we posted several items with a form631 // (use the bodyParser() middleware for this)632 var items = req.body.items;633 req.session.items = items;634 res.redirect('back');635 });636637 app.get('/add-to-cart', function(req, res){638 // When redirected back to GET /add-to-cart639 // we could check req.session.items && req.session.items.length640 // to print out a message641 if (req.session.items && req.session.items.length) {642 req.flash('info', 'You have %s items in your cart', req.session.items.length);643 }644 res.render('shopping-cart');645 });646647The _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/middleware-session.html) documentation.648649### Migration Guide650651 Express 1.x developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application to work with Express 2.x, Connect 1.x, and Node 0.4.x.652653### req.header(key[, defaultValue])654655Get the case-insensitive request header _key_, with optional _defaultValue_:656657 req.header('Host');658 req.header('host');659 req.header('Accept', '*/*');660661The _Referrer_ and _Referer_ header fields are special-cased, either will work:662663 // sent Referrer: http://google.com664665 req.header('Referer');666 // => "http://google.com"667668 req.header('Referrer');669 // => "http://google.com"670671### req.accepts(type)672673Check if the _Accept_ header is present, and includes the given _type_.674675When the _Accept_ header is not present _true_ is returned. Otherwise676the given _type_ is matched by an exact match, and then subtypes. You677may pass the subtype such as "html" which is then converted internally678to "text/html" using the mime lookup table.679680 // Accept: text/html681 req.accepts('html');682 // => true683684 // Accept: text/*; application/json685 req.accepts('html');686 req.accepts('text/html');687 req.accepts('text/plain');688 req.accepts('application/json');689 // => true690691 req.accepts('image/png');692 req.accepts('png');693 // => false694695### req.is(type)696697Check if the incoming request contains the _Content-Type_698header field, and it contains the give mime _type_.699 700 // With Content-Type: text/html; charset=utf-8701 req.is('html');702 req.is('text/html');703 // => true704 705 // When Content-Type is application/json706 req.is('json');707 req.is('application/json');708 // => true709 710 req.is('html');711 // => false712 713Ad-hoc callbacks can also be registered with Express, to perform714assertions again the request, for example if we need an expressive715way to check if our incoming request is an image, we can register _"an image"_716callback:717 718 app.is('an image', function(req){719 return 0 == req.headers['content-type'].indexOf('image');720 });721 722Now within our route callbacks, we can use to to assert content types723such as _"image/jpeg"_, _"image/png"_, etc.724 725 app.post('/image/upload', function(req, res, next){726 if (req.is('an image')) {727 // do something728 } else {729 next();730 }731 });732733Keep in mind this method is _not_ limited to checking _Content-Type_, you734can perform any request assertion you wish.735736Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:737738 req.is('image/*');739740We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.741742 req.is('*/json');743744### req.param(name[, default])745746Return the value of param _name_ when present or _default_.747748 - Checks route params (_req.params_), ex: /user/:id749 - Checks query string params (_req.query_), ex: ?id=12750 - Checks urlencoded body params (_req.body_), ex: id=12751752To utilize urlencoded request bodies, _req.body_753should be an object. This can be done by using754the _express.bodyParser middleware.755docs for req.get()Tj Holowaychukbefore adoption6bb100d
lines 756–766why, one step back756### req.get(field, param)757758 Get _field_'s _param_ value, defaulting to '' when the _param_759 or _field_ is not present.760761 req.get('content-disposition', 'filename');762 // => "something.png"763764 req.get('Content-Type', 'boundary');765 // => "--foo-bar-baz"766removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 767–872why, one step back767### req.flash(type[, msg])768769Queue flash _msg_ of the given _type_.770771 req.flash('info', 'email sent');772 req.flash('error', 'email delivery failed');773 req.flash('info', 'email re-sent');774 // => 2775776 req.flash('info');777 // => ['email sent', 'email re-sent']778779 req.flash('info');780 // => []781782 req.flash();783 // => { error: ['email delivery failed'], info: [] }784785Flash notification message may also utilize formatters, by default only the %s string formatter is available:786787 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);788789### req.isXMLHttpRequest790791Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header792to see if it was issued by an _XMLHttpRequest_:793794 req.xhr795 req.isXMLHttpRequest796797### res.header(key[, val])798799Get or set the response header _key_.800801 res.header('Content-Length');802 // => undefined803804 res.header('Content-Length', 123);805 // => 123806 807 res.header('Content-Length');808 // => 123809810### res.charset811812Sets the charset for subsequent `Content-Type` header fields. For example `res.send()` and `res.render()` default to "utf8", so we may explicitly set the charset before rendering a template:813814 res.charset = 'ISO-8859-1';815 res.render('users');816817or before responding with `res.send()`:818819 res.charset = 'ISO-8859-1';820 res.send(str);821822or with node's `res.end()`:823824 res.charset = 'ISO-8859-1';825 res.header('Content-Type', 'text/plain');826 res.end(str);827828### res.contentType(type)829830Sets the _Content-Type_ response header to the given _type_.831832 var filename = 'path/to/image.png';833 res.contentType(filename);834 // Content-Type is now "image/png"835836A literal _Content-Type_ works as well:837838 res.contentType('application/json');839840Or simply the extension without leading `.`:841842 res.contentType('json');843844### res.attachment([filename])845846Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.847848 res.attachment('path/to/my/image.png');849850### res.sendfile(path[, options[, callback]])851852Used by `res.download()` to transfer an arbitrary file. 853854 res.sendfile('path/to/my.file');855856This method accepts an optional callback which is called when857an error occurs, or when the transfer is complete. By default failures call `next(err)`, however when a callback is supplied you must do this explicitly, or act on the error.858859 res.sendfile(path, function(err){860 if (err) {861 next(err);862 } else {863 console.log('transferred %s', path);864 }865 });866867Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:868869 res.sendfile(path, { bufferSize: 1024 }, function(err){870 // handle871 });872docsTj Holowaychukbefore adoption236a412
line 873why, one step back873### res.download(file[, filename[, callback[, callback2]]])removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 874–884why, one step back874875Transfer the given _file_ as an attachment with optional alternative _filename_.876877 res.download('path/to/image.png');878 res.download('path/to/image.png', 'foo.png');879880This is equivalent to:881882 res.attachment(file);883 res.sendfile(file);884docsTj Holowaychukbefore adoption236a412
line 885why, one step back885An optional callback may be supplied as either the second or third argument, which is passed to _res.sendfile()_. Within this callback you may still respond, as the header has not been sent.removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 886–888why, one step back886887 res.download(path, 'expenses.doc', function(err){888 // handledocsTj Holowaychukbefore adoption236a412
lines 889–896why, one step back889 });890891An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.892893 res.download(path, function(err){894 // error or finished895 }, function(err){896 // connection related errorremoved manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 897–917why, one step back897 });898899### res.send(body|status[, headers|status[, status]])900901The _res.send()_ method is a high level response utility allowing you to pass902objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:903904 res.send(); // 204905 res.send(new Buffer('wahoo'));906 res.send({ some: 'json' });907 res.send('<p>some html</p>');908 res.send('Sorry, cant find that', 404);909 res.send('text', { 'Content-Type': 'text/plain' }, 201);910 res.send(404);911912By default the _Content-Type_ response header is set, however if explicitly913assigned through `res.send()` or previously with `res.header()` or `res.contentType()`914it will not be set again.915916Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.917Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 918–929why, one step back918### res.json(obj[, headers|status[, status]])919920 Send a JSON response with optional _headers_ and _status_. This method921 is ideal for JSON-only APIs, however _res.send(obj)_ will send JSON as922 well, though not ideal for cases when you want to send for example a string923 as JSON, since the default for _res.send(string)_ is text/html.924925 res.json(null);926 res.json({ user: 'tj' });927 res.json('oh noes!', 500);928 res.json('I dont have that', 404);929removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 930–954why, one step back930### res.redirect(url[, status])931932Redirect to the given _url_ with a default response _status_ of 302.933934 res.redirect('/', 301);935 res.redirect('/account');936 res.redirect('http://google.com');937 res.redirect('home');938 res.redirect('back');939940Express supports "redirect mapping", which by default provides _home_, and _back_.941The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes942the "home" setting and defaults to "/".943944### res.cookie(name, val[, options])945946Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc.947948 // "Remember me" for 15 minutes 949 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });950951The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:952953 res.cookie('rememberme', 'yes', { maxAge: 900000 });954doc typoTj Holowaychukbefore adoption62df63d
line 955why, one step back955To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 956–962why, one step back956957 app.use(express.cookieParser());958 959 app.get('/', function(req, res){960 // use req.cookies.rememberme961 });962Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
line 963why, one step back963### res.clearCookie(name[, options])removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 964–1083why, one step back964965Clear cookie _name_ by setting "expires" far in the past.966967 res.clearCookie('rememberme');968969### res.render(view[, options[, fn]])970971Render _view_ with the given _options_ and optional callback _fn_.972When a callback function is given a response will _not_ be made973automatically, however otherwise a response of _200_ and _text/html_ is given.974975The _options_ passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:976977 var user = { name: 'tj' };978 res.render('index', { layout: false, user: user });979980### res.partial(view[, options])981982Render _view_ partial with the given _options_. This method is always available983to the view as a local variable.984985- _object_ the object named by _as_ or derived from the view name986- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.987 * as: 'something' will add the _something_ local variable988 * as: this will use the collection value as the template context989 * as: global will merge the collection value's properties with _locals_990991- _collection_ Array of objects, the name is derived from the view name itself. 992 For example _video.html_ will have a object _video_ available to it.993994The following are equivalent, and the name of collection value when passed995to the partial will be _movie_ as derived from the name.996997 partial('theatre/movie.jade', { collection: movies });998 partial('theatre/movie.jade', movies);999 partial('movie.jade', { collection: movies });1000 partial('movie.jade', movies);1001 partial('movie', movies);1002 // In view: movie.director10031004To change the local from _movie_ to _video_ we can use the "as" option:10051006 partial('movie', { collection: movies, as: 'video' });1007 // In view: video.director10081009Also we can make our movie the value of _this_ within our view so that instead1010of _movie.director_ we could use _this.director_.10111012 partial('movie', { collection: movies, as: this });1013 // In view: this.director10141015Another alternative is to "expand" the properties of the collection item into1016pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:10171018 partial('movie', { collection: movies, as: global });1019 // In view: director10201021This same logic applies to a single partial object usage:10221023 partial('movie', { object: movie, as: this });1024 // In view: this.director10251026 partial('movie', { object: movie, as: global });1027 // In view: director10281029 partial('movie', { object: movie, as: 'video' });1030 // In view: video.director10311032 partial('movie', { object: movie });1033 // In view: movie.director10341035When 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:10361037 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1038 partial('movie', movie)1039 // => In view: movie.director10401041The exception of this, is when a "plain" object, aka "{}" or "new Object" is passed, which is considered an object with local variable. For example some may expect a "movie" local with the following, however since it is a plain object "director" and "title" are simply locals:10421043 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1044 partial('movie', movie)10451046For cases like this where passing a plain object is desired, simply assign it to a key, or use the `object` key which will use the filename-derived variable name. The examples below are equivalent:10471048 partial('movie', { locals: { movie: movie }})1049 partial('movie', { movie: movie })1050 partial('movie', { object: movie })10511052This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:10531054 app.get('/users', function(req, res){1055 if (req.xhr) {1056 // respond with the each user in the collection1057 // passed to the "user" view1058 res.partial('user', users);1059 } else {1060 // respond with layout, and users page1061 // which internally does partial('user', users)1062 // along with other UI1063 res.render('users', { users: users });1064 }1065 });10661067### res.local(name[, val])10681069Get 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()`.10701071 app.all('/movie/:id', function(req, res, next){1072 Movie.get(req.params.id, function(err, movie){1073 // Assigns res.locals.movie = movie1074 res.local('movie', movie);1075 });1076 });1077 1078 app.get('/movie/:id', function(req, res){1079 // movie is already a local, however we1080 // can pass more if we wish1081 res.render('movie', { displayReviews: true });1082 });1083doc typoTj Holowaychukbefore adoptionc3e6326
line 1084why, one step back1084### res.locals(obj)removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 1085–1206why, one step back10851086 Assign several locals with the given _obj_. The following are equivalent:1087 1088 res.local('foo', bar);1089 res.local('bar', baz);10901091 res.locals({ foo: bar, bar, baz });10921093### app.set(name[, val])10941095Apply an application level setting _name_ to _val_, or1096get the value of _name_ when _val_ is not present:10971098 app.set('views', __dirname + '/views');1099 app.set('views');1100 // => ...path...11011102Alternatively you may simply access the settings via _app.settings_:11031104 app.settings.views1105 // => ...path...11061107### app.enable(name)11081109Enable the given setting _name_:11101111 app.enable('some arbitrary setting');1112 app.set('some arbitrary setting');1113 // => true11141115 app.enabled('some arbitrary setting');1116 // => true11171118### app.enabled(name)11191120Check if setting _name_ is enabled:11211122 app.enabled('view cache');1123 // => false11241125 app.enable('view cache');1126 app.enabled('view cache');1127 // => true11281129### app.disable(name)11301131Disable the given setting _name_:11321133 app.disable('some setting');1134 app.set('some setting');1135 // => false1136 1137 app.disabled('some setting');1138 // => false11391140### app.disabled(name)11411142Check if setting _name_ is disabled:11431144 app.enable('view cache');11451146 app.disabled('view cache');1147 // => false11481149 app.disable('view cache');1150 app.disabled('view cache');1151 // => true11521153### app.configure(env|function[, function])11541155Define a callback function for the given _env_ (or all environments) with callback _function_:11561157 app.configure(function(){1158 // executed for each env1159 });11601161 app.configure('development', function(){1162 // executed for 'development' only1163 });11641165### app.redirect(name, val)11661167For use with _res.redirect()_ we can map redirects at the application level as shown below:11681169 app.redirect('google', 'http://google.com');11701171Now in a route we may call:11721173 res.redirect('google');11741175We may also map dynamic redirects:11761177 app.redirect('comments', function(req, res){1178 return '/post/' + req.params.id + '/comments';1179 });11801181So now we may do the following, and the redirect will dynamically adjust to1182the context of the request. If we called this route with _GET /post/12_ our1183redirect _Location_ would be _/post/12/comments_.11841185 app.get('/post/:id', function(req, res){1186 res.redirect('comments');1187 });11881189When mounted, _res.redirect()_ will respect the mount-point. For example if a blog app is mounted at _/blog_, the following will redirect to _/blog/posts_:11901191 res.redirect('/posts');11921193### app.error(function)11941195Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1196Note that we may set several error handlers by making several calls to this method, however the handler1197should call _next(err)_ if it does not wish to deal with the exception:11981199 app.error(function(err, req, res, next){1200 res.send(err.message, 500);1201 });12021203### app.helpers(obj)12041205Registers static view helpers.1206Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1207–1211why, one step back1207 app.helpers({1208 name: function(first, last){ return first + ', ' + last }1209 , firstName: 'tj'1210 , lastName: 'holowaychuk'1211 });removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 1212–1216why, one step back12121213Our view could now utilize the _firstName_ and _lastName_ variables,1214as well as the _name()_ function exposed.12151216 <%= name(firstName, lastName) %>Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1217–1220why, one step back12171218Express also provides a few locals by default:12191220 - `settings` the app's settings objectdocs for "filename" localTj Holowaychukbefore adoptionbf06d90
line 1221why, one step back1221 - `filename` the view's filenamedocsTj Holowaychukbefore adoption885fb1f
line 1222why, one step back1222 - `layout(path)` specify the layout from within a viewAdded 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1223–1224why, one step back12231224This method is aliased as _app.locals()_.removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 1225–1242why, one step back12251226### app.dynamicHelpers(obj)12271228Registers dynamic view helpers. Dynamic view helpers1229are simply functions which accept _req_, _res_, and are1230evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1231becomes the local variable it is associated with.12321233 app.dynamicHelpers({1234 session: function(req, res){1235 return req.session;1236 }1237 });12381239All views would now have _session_ available so that session data can be accessed via _session.name_ etc:12401241 <%= session.name %>1242docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1243–1247why, one step back1243### app.lookup12441245 The _app.lookup_ http methods returns an array of callback functions1246 associated with the given _path_.1247docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1248why, one step back1248 Suppose we define the following routes:docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1249–1251why, one step back1249 1250 app.get('/user/:id', function(){});1251 app.put('/user/:id', function(){});docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1252why, one step back1252 app.get('/user/:id/:op?', function(){});docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1253–1260why, one step back12531254 We can utilize this lookup functionality to check which routes1255 have been defined, which can be extremely useful for higher level1256 frameworks built on Express.12571258 app.lookup.get('/user/:id');1259 // => [Function]1260docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1261why, one step back1261 app.lookup.get('/user/:id/:op?');docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1262–1278why, one step back1262 // => [Function]12631264 app.lookup.put('/user/:id');1265 // => [Function]12661267 app.lookup.all('/user/:id');1268 // => [Function, Function]12691270 app.lookup.all('/hey');1271 // => []12721273 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1274 without a callback, as a shortcut, for example the following are1275 equivalent:1276 1277 app.lookup.get('/user');1278 app.get('/user');docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1279why, one step back1279more docsTj Holowaychukbefore adoption6230ec5
lines 1280–1295why, one step back1280 Each function returned has the following properties:1281 1282 var fn = app.get('/user/:id/:op?')[0];12831284 fn.regexp1285 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12861287 fn.keys1288 // => ['id', 'op']12891290 fn.path1291 // => '/user/:id/:op?'12921293 fn.method1294 // => 'GET'1295docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
lines 1296–1323why, one step back1296### app.match12971298 The _app.match_ http methods return an array of callback functions1299 which match the given _url_, which may include a query string etc. This1300 is useful when you want reflect on which routes have the opportunity to1301 respond.13021303 Suppose we define the following routes:13041305 app.get('/user/:id', function(){});1306 app.put('/user/:id', function(){});1307 app.get('/user/:id/:op?', function(){});13081309 Our match against __GET__ will return two functions, since the _:op_1310 in our second route is optional.13111312 app.match.get('/user/1');1313 // => [Function, Function]13141315 This second call returns only the callback for _/user/:id/:op?_.13161317 app.match.get('/user/23/edit');1318 // => [Function]13191320 We can also use _all()_ to disregard the http method:13211322 app.match.all('/user/20');1323 // => [Function, Function, Function]more docsTj Holowaychukbefore adoption6230ec5
lines 1324–1336why, one step back13241325 Each function matched has the following properties:1326 1327 var fn = app.match.get('/user/23/edit')[0];13281329 fn.keys1330 // => ['id', 'op']13311332 fn.params1333 // => { id: '23', op: 'edit' }13341335 fn.method1336 // => 'GET'docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
line 1337why, one step back1337removed manpages from makeTj Holowaychukbefore adoptioneefe51c
lines 1338–1406why, one step back1338### app.mounted(fn)13391340Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.13411342 var app = express.createServer(),1343 blog = express.createServer();1344 1345 blog.mounted(function(parent){1346 // parent is app1347 // "this" is blog1348 });1349 1350 app.use(blog);13511352### app.register(ext, exports)13531354Register the given template engine _exports_1355as _ext_. For example we may wish to map ".html"1356files to jade:13571358 app.register('.html', require('jade'));13591360This is also useful for libraries that may not1361match extensions correctly. For example my haml.js1362library is installed from npm as "hamljs" so instead1363of layout.hamljs, we can register the engine as ".haml":13641365 app.register('.haml', require('haml-js'));13661367For engines that do not comply with the Express1368specification, we can also wrap their api this way. Below1369we map _.md_ to render markdown files, rendering the html once1370since it will not change on subsequent calls, and support local substitution1371in the form of "{name}".13721373 app.register('.md', {1374 compile: function(str, options){1375 var html = md.toHTML(str);1376 return function(locals){1377 return html.replace(/\{([^}]+)\}/g, function(_, name){1378 return locals[name];1379 });1380 };1381 }1382 });13831384### app.listen([port[, host]])13851386Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1387connections will be accepted via _INADDR_ANY_.13881389 app.listen();1390 app.listen(3000);1391 app.listen(3000, 'n.n.n.n');13921393The _port_ argument may also be a string representing the path to a unix domain socket:13941395 app.listen('/tmp/express.sock');13961397Then try it out:13981399 $ telnet /tmp/express.sock1400 GET / HTTP/1.114011402 HTTP/1.1 200 OK1403 Content-Type: text/plain1404 Content-Length: 111405 1406 Hello World