guide.md
This file
Path
docs/guide.md
1,409 lines · 48.9 KiB · Markdown
Last changed by
docsTj Holowaychukbefore adoption6815feb
History of this fileTake it
The walk stopped after 200 commits: lines older than 0c32478 point at it.
Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
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.js25Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
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 routingAdded "strict routing" setting for trailing slashesTj Holowaychukbefore adoption6f7075b
line 107why, one step back107 * _strict routing_ When enabled trailing slashes are no longer ignoredMerge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 108–190why, one step back108109### Routing110111Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.112For example we may want to render a user's account for the path _/user/12_, this113can be done by defining the route below. The values associated to the named placeholders 114are available as `req.params`.115116 app.get('/user/:id', function(req, res){117 res.send('user ' + req.params.id);118 });119120A route is simple a string which is compiled to a _RegExp_ internally. For example121when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:122123 \/user\/([^\/]+)\/?124125Regular expression literals may also be passed for complex uses. Since capture126groups 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]_.127128 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){129 res.send(req.params);130 });131132Curl requests against the previously defined route:133134 $ curl http://dev:3000/user135 [null,null]136 $ curl http://dev:3000/users137 [null,null]138 $ curl http://dev:3000/users/1139 ["1",null]140 $ curl http://dev:3000/users/1..15141 ["1","15"]142143Below are some route examples, and the associated paths that they144may consume:145146 "/user/:id"147 /user/12148149 "/users/:id?"150 /users/5151 /users152153 "/files/*"154 /files/jquery.js155 /files/javascripts/jquery.js156157 "/file/*.*"158 /files/jquery.js159 /files/javascripts/jquery.js160 161 "/user/:id/:operation?"162 /user/1163 /user/1/edit164 165 "/products.:format"166 /products.json167 /products.xml168169 "/products.:format?"170 /products.json171 /products.xml172 /products173 174 "/user/:id.:format?"175 /user/12176 /user/12.json177178For 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_:179180 var express = require('express')181 , app = express.createServer();182183 app.use(express.bodyParser());184185 app.post('/', function(req, res){186 res.send(req.body);187 });188189 app.listen(3000);190docsTj Holowaychukbefore adoption6106188
line 191why, one step back191Typically 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.Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 192–259why, one step back192193### Passing Route Control194195We may pass control to the next _matching_ route, by calling the _third_ argument,196the _next()_ function. When a match cannot be made, control is passed back to Connect,197and 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.198199 app.get('/users/:id?', function(req, res, next){200 var id = req.params.id;201 if (id) {202 // do something203 } else {204 next();205 }206 });207 208 app.get('/users', function(req, res){209 // do something else210 });211212The _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_.213214 var express = require('express')215 , app = express.createServer();216217 var users = [{ name: 'tj' }];218219 app.all('/user/:id/:op?', function(req, res, next){220 req.user = users[req.params.id];221 if (req.user) {222 next();223 } else {224 next(new Error('cannot find user ' + req.params.id));225 }226 });227228 app.get('/user/:id', function(req, res){229 res.send('viewing ' + req.user.name);230 });231232 app.get('/user/:id/edit', function(req, res){233 res.send('editing ' + req.user.name);234 });235236 app.put('/user/:id', function(req, res){237 res.send('updating ' + req.user.name);238 });239240 app.get('*', function(req, res){241 res.send('what???', 404);242 });243244 app.listen(3000); 245246### Middleware247248Middleware via [Connect](http://github.com/senchalabs/connect) can be249passed to _express.createServer()_ as you would with a regular Connect server. For example:250251 var express = require('express');252253 var app = express.createServer(254 express.logger()255 , express.bodyParser()256 );257258Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.259Merge pull request #671 from jpalardy/patch-1TJ Holowaychukbefore adoptionc24b2fa
line 260why, one step back260 app.use(express.logger({ format: ':method :url' }));Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 261–272why, one step back261262Typically with connect middleware you would _require('connect')_ like so:263264 var connect = require('connect');265 app.use(connect.logger());266 app.use(connect.bodyParser());267268This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:269270 app.use(express.logger());271 app.use(express.bodyParser());272added better middleware docs and use-casesTj Holowaychukbefore adoption8d6f167
lines 273–299why, one step back273Middleware 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()_.274275Many 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 below276277 app.use(express.logger(...));278 app.use(express.bodyParser(...));279 app.use(express.cookieParser(...));280 app.use(express.session(...));281 app.use(app.router);282 app.use(express.static(...));283 app.use(express.errorHandler(...));284285First 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.286287 var downloads = {};288289 app.use(app.router);290 app.use(express.static(__dirname + '/public'));291292 app.get('/*', function(req, res, next){293 var file = req.params[0];294 downloads[file] = downloads[file] || 0;295 downloads[file]++;296 next();297 });298299Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 300–370why, one step back300### Route Middleware301302Routes 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.303304Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 305306 app.get('/user/:id', function(req, res, next){307 loadUser(req.params.id, function(err, user){308 if (err) return next(err);309 res.send('Viewing user ' + user.name);310 });311 });312313To 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. 314315 function loadUser(req, res, next) {316 // You would fetch your user from the db317 var user = users[req.params.id];318 if (user) {319 req.user = user;320 next();321 } else {322 next(new Error('Failed to load user ' + req.params.id));323 }324 }325 326 app.get('/user/:id', loadUser, function(req, res){327 res.send('Viewing user ' + req.user.name);328 });329330Multiple 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.331332 function andRestrictToSelf(req, res, next) {333 req.authenticatedUser.id == req.user.id334 ? next()335 : next(new Error('Unauthorized'));336 }337 338 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){339 res.send('Editing user ' + req.user.name);340 });341342Keeping 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.343344 function andRestrictTo(role) {345 return function(req, res, next) {346 req.authenticatedUser.role == role347 ? next()348 : next(new Error('Unauthorized'));349 }350 }351 352 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){353 res.send('Deleted user ' + req.user.name);354 });355356Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.357358 var a = [middleware1, middleware2]359 , b = [middleware3, middleware4]360 , all = [a, b];361 362 app.get('/foo', a, function(){});363 app.get('/bar', a, function(){});364 365 app.get('/', a, middleware3, middleware4, function(){});366 app.get('/', a, b, function(){});367 app.get('/', all, function(){});368369For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.370docs for next("route"). Closes #650Tj Holowaychukbefore adoption2648302
lines 371–372why, one step back371There 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.372Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 373–618why, one step back373### HTTP Methods374375We 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.376377 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.378 379 <form method="post" action="/">380 <input type="text" name="user[name]" />381 <input type="text" name="user[email]" />382 <input type="submit" value="Submit" />383 </form>384385By 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:386387 app.use(express.bodyParser());388389Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.390391 app.post('/', function(req, res){392 console.log(req.body.user);393 res.redirect('back');394 });395396When 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.397398 app.use(express.bodyParser());399 app.use(express.methodOverride());400401The 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:402403 <form method="post" action="/">404 <input type="hidden" name="_method" value="put" />405 <input type="text" name="user[name]" />406 <input type="text" name="user[email]" />407 <input type="submit" value="Submit" /> 408 </form>409410 app.put('/', function(){411 console.log(req.body.user);412 res.redirect('back');413 });414415### Error Handling416417Express provides the _app.error()_ method which receives exceptions thrown within a route,418or passed to _next(err)_. Below is an example which serves different pages based on our419ad-hoc _NotFound_ exception:420421 function NotFound(msg){422 this.name = 'NotFound';423 Error.call(this, msg);424 Error.captureStackTrace(this, arguments.callee);425 }426 427 NotFound.prototype.__proto__ = Error.prototype;428 429 app.get('/404', function(req, res){430 throw new NotFound;431 });432 433 app.get('/500', function(req, res){434 throw new Error('keyboard cat!');435 });436437We can call _app.error()_ several times as shown below.438Here we check for an instanceof _NotFound_ and show the439404 page, or we pass on to the next error handler.440441Note that these handlers can be defined anywhere, as they442will be placed below the route handlers on _listen()_. This 443allows for definition within _configure()_ blocks so we can444handle exceptions in different ways based on the environment.445446 app.error(function(err, req, res, next){447 if (err instanceof NotFound) {448 res.render('404.jade');449 } else {450 next(err);451 }452 });453454Here we assume all errors as 500 for the simplicity of455this 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.456457 app.error(function(err, req, res){458 res.render('500.jade', {459 error: err460 });461 });462463Our apps could also utilize the Connect _errorHandler_ middleware464to report on exceptions. For example if we wish to output exceptions 465in "development" mode to _stderr_ we can use:466467 app.use(express.errorHandler({ dumpExceptions: true }));468469Also during development we may want fancy html pages to show exceptions470that are passed or thrown, so we can set _showStack_ to true:471472 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));473474The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_475is present, which is useful for developing apps that rely heavily on client-side JavaScript.476477### Route Param Pre-conditions478479Route 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:480481 app.get('/user/:userId', function(req, res, next){482 User.get(req.params.userId, function(err, user){483 if (err) return next(err);484 res.send('user ' + user.name);485 });486 }); 487488With 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.489490 app.param('userId', function(req, res, next, id){491 User.get(id, function(err, user){492 if (err) return next(err);493 if (!user) return next(new Error('failed to find user'));494 req.user = user;495 next();496 });497 });498499Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:500501 app.get('/user/:userId', function(req, res){502 res.send('user ' + req.user.name);503 });504505### View Rendering506507View filenames take the form "<name>.<engine>", where <engine> is the name508of the module that will be required. For example the view _layout.ejs_ will509tell 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 behaviour510_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.511512Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,513and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 514the _body_ local variable in _layout.jade_.515516 app.get('/', function(req, res){517 res.render('index.jade', { title: 'My Site' });518 });519520The new _view engine_ setting allows us to specify our default template engine,521so for example when using jade we could set:522523 app.set('view engine', 'jade');524525Allowing us to render with:526527 res.render('index');528529vs:530531 res.render('index.jade');532533When _view engine_ is set, extensions are entirely optional, however we can still534mix and match template engines:535536 res.render('another-page.ejs');537538Express 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:539540 app.set('view options', {541 layout: false542 });543544Which can then be overridden within the _res.render()_ call if need be:545546 res.render('myview.ejs', { layout: true });547548When 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:549550 res.render('page', { layout: 'mylayout' });551552Otherwise we must specify the extension:553554 res.render('page', { layout: 'mylayout.jade' });555556These paths may also be absolute:557558 res.render('page', { layout: __dirname + '/../../mylayout.jade' });559560A good example of this is specifying custom _ejs_ opening and closing tags:561562 app.set('view options', {563 open: '{{',564 close: '}}'565 });566567### View Partials568569The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating570in a view to display comments, we could use partial collection:571572 partial('comment', { collection: comments });573574If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:575576 partial('comment', comments);577578When using the partial collection support a few "magic" locals are provided579for free:580581 * _firstInCollection_ true if this is the first object582 * _indexInCollection_ index of the object in the collection583 * _lastInCollection_ true if this is the last object584 * _collectionLength_ length of the collection585586Local 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.587588For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).589590__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.591592### View Lookup593594View 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_.595596The 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_.597598When 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')_.599600### Template Engines601602Below are a few template engines commonly used with Express:603604 * [Haml](http://github.com/visionmedia/haml.js) haml implementation605 * [Jade](http://jade-lang.com) haml.js successor606 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript607 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating608 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node609610### Session Support611612Sessions 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_.613614 app.use(express.cookieParser());615 app.use(express.session({ secret: "keyboard cat" }));616617By 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:618Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4
line 619why, one step back619 var RedisStore = require('connect-redis')(express);Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 620–624why, one step back620 app.use(express.cookieParser());621 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));622623Now 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:624Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4
line 625why, one step back625 var RedisStore = require('connect-redis')(express);Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 626–756why, one step back626 app.use(express.bodyParser());627 app.use(express.cookieParser());628 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));629630 app.post('/add-to-cart', function(req, res){631 // Perhaps we posted several items with a form632 // (use the bodyParser() middleware for this)633 var items = req.body.items;634 req.session.items = items;635 res.redirect('back');636 });637638 app.get('/add-to-cart', function(req, res){639 // When redirected back to GET /add-to-cart640 // we could check req.session.items && req.session.items.length641 // to print out a message642 if (req.session.items && req.session.items.length) {643 req.flash('info', 'You have %s items in your cart', req.session.items.length);644 }645 res.render('shopping-cart');646 });647648The _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.649650### Migration Guide651652 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.653654### req.header(key[, defaultValue])655656Get the case-insensitive request header _key_, with optional _defaultValue_:657658 req.header('Host');659 req.header('host');660 req.header('Accept', '*/*');661662The _Referrer_ and _Referer_ header fields are special-cased, either will work:663664 // sent Referrer: http://google.com665666 req.header('Referer');667 // => "http://google.com"668669 req.header('Referrer');670 // => "http://google.com"671672### req.accepts(type)673674Check if the _Accept_ header is present, and includes the given _type_.675676When the _Accept_ header is not present _true_ is returned. Otherwise677the given _type_ is matched by an exact match, and then subtypes. You678may pass the subtype such as "html" which is then converted internally679to "text/html" using the mime lookup table.680681 // Accept: text/html682 req.accepts('html');683 // => true684685 // Accept: text/*; application/json686 req.accepts('html');687 req.accepts('text/html');688 req.accepts('text/plain');689 req.accepts('application/json');690 // => true691692 req.accepts('image/png');693 req.accepts('png');694 // => false695696### req.is(type)697698Check if the incoming request contains the _Content-Type_699header field, and it contains the give mime _type_.700 701 // With Content-Type: text/html; charset=utf-8702 req.is('html');703 req.is('text/html');704 // => true705 706 // When Content-Type is application/json707 req.is('json');708 req.is('application/json');709 // => true710 711 req.is('html');712 // => false713 714Ad-hoc callbacks can also be registered with Express, to perform715assertions again the request, for example if we need an expressive716way to check if our incoming request is an image, we can register _"an image"_717callback:718 719 app.is('an image', function(req){720 return 0 == req.headers['content-type'].indexOf('image');721 });722 723Now within our route callbacks, we can use to to assert content types724such as _"image/jpeg"_, _"image/png"_, etc.725 726 app.post('/image/upload', function(req, res, next){727 if (req.is('an image')) {728 // do something729 } else {730 next();731 }732 });733734Keep in mind this method is _not_ limited to checking _Content-Type_, you735can perform any request assertion you wish.736737Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:738739 req.is('image/*');740741We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.742743 req.is('*/json');744745### req.param(name[, default])746747Return the value of param _name_ when present or _default_.748749 - Checks route params (_req.params_), ex: /user/:id750 - Checks query string params (_req.query_), ex: ?id=12751 - Checks urlencoded body params (_req.body_), ex: id=12752753To utilize urlencoded request bodies, _req.body_754should be an object. This can be done by using755the _express.bodyParser middleware.756docs for req.get()Tj Holowaychukbefore adoption6bb100d
lines 757–767why, one step back757### req.get(field, param)758759 Get _field_'s _param_ value, defaulting to '' when the _param_760 or _field_ is not present.761762 req.get('content-disposition', 'filename');763 // => "something.png"764765 req.get('Content-Type', 'boundary');766 // => "--foo-bar-baz"767Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 768–873why, one step back768### req.flash(type[, msg])769770Queue flash _msg_ of the given _type_.771772 req.flash('info', 'email sent');773 req.flash('error', 'email delivery failed');774 req.flash('info', 'email re-sent');775 // => 2776777 req.flash('info');778 // => ['email sent', 'email re-sent']779780 req.flash('info');781 // => []782783 req.flash();784 // => { error: ['email delivery failed'], info: [] }785786Flash notification message may also utilize formatters, by default only the %s string formatter is available:787788 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);789790### req.isXMLHttpRequest791792Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header793to see if it was issued by an _XMLHttpRequest_:794795 req.xhr796 req.isXMLHttpRequest797798### res.header(key[, val])799800Get or set the response header _key_.801802 res.header('Content-Length');803 // => undefined804805 res.header('Content-Length', 123);806 // => 123807 808 res.header('Content-Length');809 // => 123810811### res.charset812813Sets 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:814815 res.charset = 'ISO-8859-1';816 res.render('users');817818or before responding with `res.send()`:819820 res.charset = 'ISO-8859-1';821 res.send(str);822823or with node's `res.end()`:824825 res.charset = 'ISO-8859-1';826 res.header('Content-Type', 'text/plain');827 res.end(str);828829### res.contentType(type)830831Sets the _Content-Type_ response header to the given _type_.832833 var filename = 'path/to/image.png';834 res.contentType(filename);835 // Content-Type is now "image/png"836837A literal _Content-Type_ works as well:838839 res.contentType('application/json');840841Or simply the extension without leading `.`:842843 res.contentType('json');844845### res.attachment([filename])846847Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.848849 res.attachment('path/to/my/image.png');850851### res.sendfile(path[, options[, callback]])852853Used by `res.download()` to transfer an arbitrary file. 854855 res.sendfile('path/to/my.file');856857This method accepts an optional callback which is called when858an 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.859860 res.sendfile(path, function(err){861 if (err) {862 next(err);863 } else {864 console.log('transferred %s', path);865 }866 });867868Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:869870 res.sendfile(path, { bufferSize: 1024 }, function(err){871 // handle872 });873docsTj Holowaychukbefore adoption236a412
line 874why, one step back874### res.download(file[, filename[, callback[, callback2]]])Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 875–885why, one step back875876Transfer the given _file_ as an attachment with optional alternative _filename_.877878 res.download('path/to/image.png');879 res.download('path/to/image.png', 'foo.png');880881This is equivalent to:882883 res.attachment(file);884 res.sendfile(file);885docsTj Holowaychukbefore adoption236a412
line 886why, one step back886An 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.Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 887–889why, one step back887888 res.download(path, 'expenses.doc', function(err){889 // handledocsTj Holowaychukbefore adoption236a412
lines 890–897why, one step back890 });891892An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.893894 res.download(path, function(err){895 // error or finished896 }, function(err){897 // connection related errorMerge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 898–918why, one step back898 });899900### res.send(body|status[, headers|status[, status]])901902The _res.send()_ method is a high level response utility allowing you to pass903objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:904905 res.send(); // 204906 res.send(new Buffer('wahoo'));907 res.send({ some: 'json' });908 res.send('<p>some html</p>');909 res.send('Sorry, cant find that', 404);910 res.send('text', { 'Content-Type': 'text/plain' }, 201);911 res.send(404);912913By default the _Content-Type_ response header is set, however if explicitly914assigned through `res.send()` or previously with `res.header()` or `res.contentType()`915it will not be set again.916917Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.918Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 919–930why, one step back919### res.json(obj[, headers|status[, status]])920921 Send a JSON response with optional _headers_ and _status_. This method922 is ideal for JSON-only APIs, however _res.send(obj)_ will send JSON as923 well, though not ideal for cases when you want to send for example a string924 as JSON, since the default for _res.send(string)_ is text/html.925926 res.json(null);927 res.json({ user: 'tj' });928 res.json('oh noes!', 500);929 res.json('I dont have that', 404);930Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 931–946why, one step back931### res.redirect(url[, status])932933Redirect to the given _url_ with a default response _status_ of 302.934935 res.redirect('/', 301);936 res.redirect('/account');937 res.redirect('http://google.com');938 res.redirect('home');939 res.redirect('back');940941Express supports "redirect mapping", which by default provides _home_, and _back_.942The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes943the "home" setting and defaults to "/".944945### res.cookie(name, val[, options])946docsTj Holowaychukbefore adoption6815feb
lines 947–948why, one step back947Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc. The _path_ option defaults to the app's "home" setting, which948is typically "/".Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 949–956why, one step back949950 // "Remember me" for 15 minutes 951 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });952953The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:954955 res.cookie('rememberme', 'yes', { maxAge: 900000 });956doc typoTj Holowaychukbefore adoption62df63d
line 957why, one step back957To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 958–964why, one step back958959 app.use(express.cookieParser());960 961 app.get('/', function(req, res){962 // use req.cookies.rememberme963 });964Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
line 965why, one step back965### res.clearCookie(name[, options])Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
line 966why, one step back966docsTj Holowaychukbefore adoption6815feb
lines 967–968why, one step back967Clear cookie _name_ by setting "expires" far in the past. Much like968_res.cookie()_ the _path_ option also defaults to the "home" setting.Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 969–1224why, one step back969970 res.clearCookie('rememberme');971972### res.render(view[, options[, fn]])973974Render _view_ with the given _options_ and optional callback _fn_.975When a callback function is given a response will _not_ be made976automatically, however otherwise a response of _200_ and _text/html_ is given.977978The _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:979980 var user = { name: 'tj' };981 res.render('index', { layout: false, user: user });982983### res.partial(view[, options])984985Render _view_ partial with the given _options_. This method is always available986to the view as a local variable.987988- _object_ the object named by _as_ or derived from the view name989- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.990 * as: 'something' will add the _something_ local variable991 * as: this will use the collection value as the template context992 * as: global will merge the collection value's properties with _locals_993994- _collection_ Array of objects, the name is derived from the view name itself. 995 For example _video.html_ will have a object _video_ available to it.996997The following are equivalent, and the name of collection value when passed998to the partial will be _movie_ as derived from the name.9991000 partial('theatre/movie.jade', { collection: movies });1001 partial('theatre/movie.jade', movies);1002 partial('movie.jade', { collection: movies });1003 partial('movie.jade', movies);1004 partial('movie', movies);1005 // In view: movie.director10061007To change the local from _movie_ to _video_ we can use the "as" option:10081009 partial('movie', { collection: movies, as: 'video' });1010 // In view: video.director10111012Also we can make our movie the value of _this_ within our view so that instead1013of _movie.director_ we could use _this.director_.10141015 partial('movie', { collection: movies, as: this });1016 // In view: this.director10171018Another alternative is to "expand" the properties of the collection item into1019pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:10201021 partial('movie', { collection: movies, as: global });1022 // In view: director10231024This same logic applies to a single partial object usage:10251026 partial('movie', { object: movie, as: this });1027 // In view: this.director10281029 partial('movie', { object: movie, as: global });1030 // In view: director10311032 partial('movie', { object: movie, as: 'video' });1033 // In view: video.director10341035 partial('movie', { object: movie });1036 // In view: movie.director10371038When 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:10391040 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1041 partial('movie', movie)1042 // => In view: movie.director10431044The 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:10451046 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1047 partial('movie', movie)10481049For 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:10501051 partial('movie', { locals: { movie: movie }})1052 partial('movie', { movie: movie })1053 partial('movie', { object: movie })10541055This 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:10561057 app.get('/users', function(req, res){1058 if (req.xhr) {1059 // respond with the each user in the collection1060 // passed to the "user" view1061 res.partial('user', users);1062 } else {1063 // respond with layout, and users page1064 // which internally does partial('user', users)1065 // along with other UI1066 res.render('users', { users: users });1067 }1068 });10691070### res.local(name[, val])10711072Get 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()`.10731074 app.all('/movie/:id', function(req, res, next){1075 Movie.get(req.params.id, function(err, movie){1076 // Assigns res.locals.movie = movie1077 res.local('movie', movie);1078 });1079 });1080 1081 app.get('/movie/:id', function(req, res){1082 // movie is already a local, however we1083 // can pass more if we wish1084 res.render('movie', { displayReviews: true });1085 });10861087### res.locals(obj)10881089 Assign several locals with the given _obj_. The following are equivalent:1090 1091 res.local('foo', bar);1092 res.local('bar', baz);10931094 res.locals({ foo: bar, bar, baz });10951096### app.set(name[, val])10971098Apply an application level setting _name_ to _val_, or1099get the value of _name_ when _val_ is not present:11001101 app.set('views', __dirname + '/views');1102 app.set('views');1103 // => ...path...11041105Alternatively you may simply access the settings via _app.settings_:11061107 app.settings.views1108 // => ...path...11091110### app.enable(name)11111112Enable the given setting _name_:11131114 app.enable('some arbitrary setting');1115 app.set('some arbitrary setting');1116 // => true11171118 app.enabled('some arbitrary setting');1119 // => true11201121### app.enabled(name)11221123Check if setting _name_ is enabled:11241125 app.enabled('view cache');1126 // => false11271128 app.enable('view cache');1129 app.enabled('view cache');1130 // => true11311132### app.disable(name)11331134Disable the given setting _name_:11351136 app.disable('some setting');1137 app.set('some setting');1138 // => false1139 1140 app.disabled('some setting');1141 // => false11421143### app.disabled(name)11441145Check if setting _name_ is disabled:11461147 app.enable('view cache');11481149 app.disabled('view cache');1150 // => false11511152 app.disable('view cache');1153 app.disabled('view cache');1154 // => true11551156### app.configure(env|function[, function])11571158Define a callback function for the given _env_ (or all environments) with callback _function_:11591160 app.configure(function(){1161 // executed for each env1162 });11631164 app.configure('development', function(){1165 // executed for 'development' only1166 });11671168### app.redirect(name, val)11691170For use with _res.redirect()_ we can map redirects at the application level as shown below:11711172 app.redirect('google', 'http://google.com');11731174Now in a route we may call:11751176 res.redirect('google');11771178We may also map dynamic redirects:11791180 app.redirect('comments', function(req, res){1181 return '/post/' + req.params.id + '/comments';1182 });11831184So now we may do the following, and the redirect will dynamically adjust to1185the context of the request. If we called this route with _GET /post/12_ our1186redirect _Location_ would be _/post/12/comments_.11871188 app.get('/post/:id', function(req, res){1189 res.redirect('comments');1190 });11911192When 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_:11931194 res.redirect('/posts');11951196### app.error(function)11971198Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1199Note that we may set several error handlers by making several calls to this method, however the handler1200should call _next(err)_ if it does not wish to deal with the exception:12011202 app.error(function(err, req, res, next){1203 res.send(err.message, 500);1204 });12051206### app.helpers(obj)12071208Registers static view helpers.12091210 app.helpers({1211 name: function(first, last){ return first + ', ' + last }1212 , firstName: 'tj'1213 , lastName: 'holowaychuk'1214 });12151216Our view could now utilize the _firstName_ and _lastName_ variables,1217as well as the _name()_ function exposed.12181219 <%= name(firstName, lastName) %>12201221Express also provides a few locals by default:12221223 - `settings` the app's settings object1224 - `filename` the view's filenamedocsTj Holowaychukbefore adoption885fb1f
line 1225why, one step back1225 - `layout(path)` specify the layout from within a viewMerge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 1226–1245why, one step back12261227This method is aliased as _app.locals()_.12281229### app.dynamicHelpers(obj)12301231Registers dynamic view helpers. Dynamic view helpers1232are simply functions which accept _req_, _res_, and are1233evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1234becomes the local variable it is associated with.12351236 app.dynamicHelpers({1237 session: function(req, res){1238 return req.session;1239 }1240 });12411242All views would now have _session_ available so that session data can be accessed via _session.name_ etc:12431244 <%= session.name %>1245docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1246–1250why, one step back1246### app.lookup12471248 The _app.lookup_ http methods returns an array of callback functions1249 associated with the given _path_.1250docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1251why, one step back1251 Suppose we define the following routes:docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1252–1254why, one step back1252 1253 app.get('/user/:id', function(){});1254 app.put('/user/:id', function(){});docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1255why, one step back1255 app.get('/user/:id/:op?', function(){});docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1256–1263why, one step back12561257 We can utilize this lookup functionality to check which routes1258 have been defined, which can be extremely useful for higher level1259 frameworks built on Express.12601261 app.lookup.get('/user/:id');1262 // => [Function]1263docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1264why, one step back1264 app.lookup.get('/user/:id/:op?');docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1265–1281why, one step back1265 // => [Function]12661267 app.lookup.put('/user/:id');1268 // => [Function]12691270 app.lookup.all('/user/:id');1271 // => [Function, Function]12721273 app.lookup.all('/hey');1274 // => []12751276 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1277 without a callback, as a shortcut, for example the following are1278 equivalent:1279 1280 app.lookup.get('/user');1281 app.get('/user');docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1282why, one step back1282more docsTj Holowaychukbefore adoption6230ec5
lines 1283–1298why, one step back1283 Each function returned has the following properties:1284 1285 var fn = app.get('/user/:id/:op?')[0];12861287 fn.regexp1288 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12891290 fn.keys1291 // => ['id', 'op']12921293 fn.path1294 // => '/user/:id/:op?'12951296 fn.method1297 // => 'GET'1298docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
lines 1299–1326why, one step back1299### app.match13001301 The _app.match_ http methods return an array of callback functions1302 which match the given _url_, which may include a query string etc. This1303 is useful when you want reflect on which routes have the opportunity to1304 respond.13051306 Suppose we define the following routes:13071308 app.get('/user/:id', function(){});1309 app.put('/user/:id', function(){});1310 app.get('/user/:id/:op?', function(){});13111312 Our match against __GET__ will return two functions, since the _:op_1313 in our second route is optional.13141315 app.match.get('/user/1');1316 // => [Function, Function]13171318 This second call returns only the callback for _/user/:id/:op?_.13191320 app.match.get('/user/23/edit');1321 // => [Function]13221323 We can also use _all()_ to disregard the http method:13241325 app.match.all('/user/20');1326 // => [Function, Function, Function]more docsTj Holowaychukbefore adoption6230ec5
lines 1327–1339why, one step back13271328 Each function matched has the following properties:1329 1330 var fn = app.match.get('/user/23/edit')[0];13311332 fn.keys1333 // => ['id', 'op']13341335 fn.params1336 // => { id: '23', op: 'edit' }13371338 fn.method1339 // => 'GET'docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
line 1340why, one step back1340Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 1341–1409why, one step back1341### app.mounted(fn)13421343Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.13441345 var app = express.createServer(),1346 blog = express.createServer();1347 1348 blog.mounted(function(parent){1349 // parent is app1350 // "this" is blog1351 });1352 1353 app.use(blog);13541355### app.register(ext, exports)13561357Register the given template engine _exports_1358as _ext_. For example we may wish to map ".html"1359files to jade:13601361 app.register('.html', require('jade'));13621363This is also useful for libraries that may not1364match extensions correctly. For example my haml.js1365library is installed from npm as "hamljs" so instead1366of layout.hamljs, we can register the engine as ".haml":13671368 app.register('.haml', require('haml-js'));13691370For engines that do not comply with the Express1371specification, we can also wrap their api this way. Below1372we map _.md_ to render markdown files, rendering the html once1373since it will not change on subsequent calls, and support local substitution1374in the form of "{name}".13751376 app.register('.md', {1377 compile: function(str, options){1378 var html = md.toHTML(str);1379 return function(locals){1380 return html.replace(/\{([^}]+)\}/g, function(_, name){1381 return locals[name];1382 });1383 };1384 }1385 });13861387### app.listen([port[, host]])13881389Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1390connections will be accepted via _INADDR_ANY_.13911392 app.listen();1393 app.listen(3000);1394 app.listen(3000, 'n.n.n.n');13951396The _port_ argument may also be a string representing the path to a unix domain socket:13971398 app.listen('/tmp/express.sock');13991400Then try it out:14011402 $ telnet /tmp/express.sock1403 GET / HTTP/1.114041405 HTTP/1.1 200 OK1406 Content-Type: text/plain1407 Content-Length: 111408 1409 Hello World