guide.md
This file
Path
docs/guide.md
1,410 lines · 49.0 KiB · Markdown
Last changed by
moved jsonp testsTj Holowaychukbefore adoption87bc265
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 ignoredmoved jsonp testsTj Holowaychukbefore adoption87bc265
line 108why, one step back108 * _jsonp callback_ Enable _res.send()_ / _res.json()_ transparent jsonp supportMerge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 109–191why, one step back109110### Routing111112Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.113For example we may want to render a user's account for the path _/user/12_, this114can be done by defining the route below. The values associated to the named placeholders 115are available as `req.params`.116117 app.get('/user/:id', function(req, res){118 res.send('user ' + req.params.id);119 });120121A route is simple a string which is compiled to a _RegExp_ internally. For example122when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:123124 \/user\/([^\/]+)\/?125126Regular expression literals may also be passed for complex uses. Since capture127groups 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]_.128129 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){130 res.send(req.params);131 });132133Curl requests against the previously defined route:134135 $ curl http://dev:3000/user136 [null,null]137 $ curl http://dev:3000/users138 [null,null]139 $ curl http://dev:3000/users/1140 ["1",null]141 $ curl http://dev:3000/users/1..15142 ["1","15"]143144Below are some route examples, and the associated paths that they145may consume:146147 "/user/:id"148 /user/12149150 "/users/:id?"151 /users/5152 /users153154 "/files/*"155 /files/jquery.js156 /files/javascripts/jquery.js157158 "/file/*.*"159 /files/jquery.js160 /files/javascripts/jquery.js161 162 "/user/:id/:operation?"163 /user/1164 /user/1/edit165 166 "/products.:format"167 /products.json168 /products.xml169170 "/products.:format?"171 /products.json172 /products.xml173 /products174 175 "/user/:id.:format?"176 /user/12177 /user/12.json178179For 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_:180181 var express = require('express')182 , app = express.createServer();183184 app.use(express.bodyParser());185186 app.post('/', function(req, res){187 res.send(req.body);188 });189190 app.listen(3000);191docsTj Holowaychukbefore adoption6106188
line 192why, one step back192Typically 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 193–260why, one step back193194### Passing Route Control195196We may pass control to the next _matching_ route, by calling the _third_ argument,197the _next()_ function. When a match cannot be made, control is passed back to Connect,198and 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.199200 app.get('/users/:id?', function(req, res, next){201 var id = req.params.id;202 if (id) {203 // do something204 } else {205 next();206 }207 });208 209 app.get('/users', function(req, res){210 // do something else211 });212213The _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_.214215 var express = require('express')216 , app = express.createServer();217218 var users = [{ name: 'tj' }];219220 app.all('/user/:id/:op?', function(req, res, next){221 req.user = users[req.params.id];222 if (req.user) {223 next();224 } else {225 next(new Error('cannot find user ' + req.params.id));226 }227 });228229 app.get('/user/:id', function(req, res){230 res.send('viewing ' + req.user.name);231 });232233 app.get('/user/:id/edit', function(req, res){234 res.send('editing ' + req.user.name);235 });236237 app.put('/user/:id', function(req, res){238 res.send('updating ' + req.user.name);239 });240241 app.get('*', function(req, res){242 res.send('what???', 404);243 });244245 app.listen(3000); 246247### Middleware248249Middleware via [Connect](http://github.com/senchalabs/connect) can be250passed to _express.createServer()_ as you would with a regular Connect server. For example:251252 var express = require('express');253254 var app = express.createServer(255 express.logger()256 , express.bodyParser()257 );258259Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.260Merge pull request #671 from jpalardy/patch-1TJ Holowaychukbefore adoptionc24b2fa
line 261why, one step back261 app.use(express.logger({ format: ':method :url' }));Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 262–273why, one step back262263Typically with connect middleware you would _require('connect')_ like so:264265 var connect = require('connect');266 app.use(connect.logger());267 app.use(connect.bodyParser());268269This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:270271 app.use(express.logger());272 app.use(express.bodyParser());273added better middleware docs and use-casesTj Holowaychukbefore adoption8d6f167
lines 274–300why, one step back274Middleware 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()_.275276Many 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 below277278 app.use(express.logger(...));279 app.use(express.bodyParser(...));280 app.use(express.cookieParser(...));281 app.use(express.session(...));282 app.use(app.router);283 app.use(express.static(...));284 app.use(express.errorHandler(...));285286First 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.287288 var downloads = {};289290 app.use(app.router);291 app.use(express.static(__dirname + '/public'));292293 app.get('/*', function(req, res, next){294 var file = req.params[0];295 downloads[file] = downloads[file] || 0;296 downloads[file]++;297 next();298 });299300Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 301–371why, one step back301### Route Middleware302303Routes 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.304305Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 306307 app.get('/user/:id', function(req, res, next){308 loadUser(req.params.id, function(err, user){309 if (err) return next(err);310 res.send('Viewing user ' + user.name);311 });312 });313314To 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. 315316 function loadUser(req, res, next) {317 // You would fetch your user from the db318 var user = users[req.params.id];319 if (user) {320 req.user = user;321 next();322 } else {323 next(new Error('Failed to load user ' + req.params.id));324 }325 }326 327 app.get('/user/:id', loadUser, function(req, res){328 res.send('Viewing user ' + req.user.name);329 });330331Multiple 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.332333 function andRestrictToSelf(req, res, next) {334 req.authenticatedUser.id == req.user.id335 ? next()336 : next(new Error('Unauthorized'));337 }338 339 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){340 res.send('Editing user ' + req.user.name);341 });342343Keeping 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.344345 function andRestrictTo(role) {346 return function(req, res, next) {347 req.authenticatedUser.role == role348 ? next()349 : next(new Error('Unauthorized'));350 }351 }352 353 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){354 res.send('Deleted user ' + req.user.name);355 });356357Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.358359 var a = [middleware1, middleware2]360 , b = [middleware3, middleware4]361 , all = [a, b];362 363 app.get('/foo', a, function(){});364 app.get('/bar', a, function(){});365 366 app.get('/', a, middleware3, middleware4, function(){});367 app.get('/', a, b, function(){});368 app.get('/', all, function(){});369370For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.371docs for next("route"). Closes #650Tj Holowaychukbefore adoption2648302
lines 372–373why, one step back372There 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.373Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 374–619why, one step back374### HTTP Methods375376We 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.377378 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.379 380 <form method="post" action="/">381 <input type="text" name="user[name]" />382 <input type="text" name="user[email]" />383 <input type="submit" value="Submit" />384 </form>385386By 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:387388 app.use(express.bodyParser());389390Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.391392 app.post('/', function(req, res){393 console.log(req.body.user);394 res.redirect('back');395 });396397When 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.398399 app.use(express.bodyParser());400 app.use(express.methodOverride());401402The 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:403404 <form method="post" action="/">405 <input type="hidden" name="_method" value="put" />406 <input type="text" name="user[name]" />407 <input type="text" name="user[email]" />408 <input type="submit" value="Submit" /> 409 </form>410411 app.put('/', function(){412 console.log(req.body.user);413 res.redirect('back');414 });415416### Error Handling417418Express provides the _app.error()_ method which receives exceptions thrown within a route,419or passed to _next(err)_. Below is an example which serves different pages based on our420ad-hoc _NotFound_ exception:421422 function NotFound(msg){423 this.name = 'NotFound';424 Error.call(this, msg);425 Error.captureStackTrace(this, arguments.callee);426 }427 428 NotFound.prototype.__proto__ = Error.prototype;429 430 app.get('/404', function(req, res){431 throw new NotFound;432 });433 434 app.get('/500', function(req, res){435 throw new Error('keyboard cat!');436 });437438We can call _app.error()_ several times as shown below.439Here we check for an instanceof _NotFound_ and show the440404 page, or we pass on to the next error handler.441442Note that these handlers can be defined anywhere, as they443will be placed below the route handlers on _listen()_. This 444allows for definition within _configure()_ blocks so we can445handle exceptions in different ways based on the environment.446447 app.error(function(err, req, res, next){448 if (err instanceof NotFound) {449 res.render('404.jade');450 } else {451 next(err);452 }453 });454455Here we assume all errors as 500 for the simplicity of456this 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.457458 app.error(function(err, req, res){459 res.render('500.jade', {460 error: err461 });462 });463464Our apps could also utilize the Connect _errorHandler_ middleware465to report on exceptions. For example if we wish to output exceptions 466in "development" mode to _stderr_ we can use:467468 app.use(express.errorHandler({ dumpExceptions: true }));469470Also during development we may want fancy html pages to show exceptions471that are passed or thrown, so we can set _showStack_ to true:472473 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));474475The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_476is present, which is useful for developing apps that rely heavily on client-side JavaScript.477478### Route Param Pre-conditions479480Route 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:481482 app.get('/user/:userId', function(req, res, next){483 User.get(req.params.userId, function(err, user){484 if (err) return next(err);485 res.send('user ' + user.name);486 });487 }); 488489With 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.490491 app.param('userId', function(req, res, next, id){492 User.get(id, function(err, user){493 if (err) return next(err);494 if (!user) return next(new Error('failed to find user'));495 req.user = user;496 next();497 });498 });499500Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:501502 app.get('/user/:userId', function(req, res){503 res.send('user ' + req.user.name);504 });505506### View Rendering507508View filenames take the form "<name>.<engine>", where <engine> is the name509of the module that will be required. For example the view _layout.ejs_ will510tell 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 behaviour511_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.512513Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,514and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 515the _body_ local variable in _layout.jade_.516517 app.get('/', function(req, res){518 res.render('index.jade', { title: 'My Site' });519 });520521The new _view engine_ setting allows us to specify our default template engine,522so for example when using jade we could set:523524 app.set('view engine', 'jade');525526Allowing us to render with:527528 res.render('index');529530vs:531532 res.render('index.jade');533534When _view engine_ is set, extensions are entirely optional, however we can still535mix and match template engines:536537 res.render('another-page.ejs');538539Express 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:540541 app.set('view options', {542 layout: false543 });544545Which can then be overridden within the _res.render()_ call if need be:546547 res.render('myview.ejs', { layout: true });548549When 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:550551 res.render('page', { layout: 'mylayout' });552553Otherwise we must specify the extension:554555 res.render('page', { layout: 'mylayout.jade' });556557These paths may also be absolute:558559 res.render('page', { layout: __dirname + '/../../mylayout.jade' });560561A good example of this is specifying custom _ejs_ opening and closing tags:562563 app.set('view options', {564 open: '{{',565 close: '}}'566 });567568### View Partials569570The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating571in a view to display comments, we could use partial collection:572573 partial('comment', { collection: comments });574575If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:576577 partial('comment', comments);578579When using the partial collection support a few "magic" locals are provided580for free:581582 * _firstInCollection_ true if this is the first object583 * _indexInCollection_ index of the object in the collection584 * _lastInCollection_ true if this is the last object585 * _collectionLength_ length of the collection586587Local 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.588589For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).590591__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.592593### View Lookup594595View 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_.596597The 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_.598599When 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')_.600601### Template Engines602603Below are a few template engines commonly used with Express:604605 * [Haml](http://github.com/visionmedia/haml.js) haml implementation606 * [Jade](http://jade-lang.com) haml.js successor607 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript608 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating609 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node610611### Session Support612613Sessions 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_.614615 app.use(express.cookieParser());616 app.use(express.session({ secret: "keyboard cat" }));617618By 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:619Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4
line 620why, one step back620 var RedisStore = require('connect-redis')(express);Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 621–625why, one step back621 app.use(express.cookieParser());622 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));623624Now 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:625Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption48a14a4
line 626why, one step back626 var RedisStore = require('connect-redis')(express);Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 627–757why, one step back627 app.use(express.bodyParser());628 app.use(express.cookieParser());629 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));630631 app.post('/add-to-cart', function(req, res){632 // Perhaps we posted several items with a form633 // (use the bodyParser() middleware for this)634 var items = req.body.items;635 req.session.items = items;636 res.redirect('back');637 });638639 app.get('/add-to-cart', function(req, res){640 // When redirected back to GET /add-to-cart641 // we could check req.session.items && req.session.items.length642 // to print out a message643 if (req.session.items && req.session.items.length) {644 req.flash('info', 'You have %s items in your cart', req.session.items.length);645 }646 res.render('shopping-cart');647 });648649The _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.650651### Migration Guide652653 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.654655### req.header(key[, defaultValue])656657Get the case-insensitive request header _key_, with optional _defaultValue_:658659 req.header('Host');660 req.header('host');661 req.header('Accept', '*/*');662663The _Referrer_ and _Referer_ header fields are special-cased, either will work:664665 // sent Referrer: http://google.com666667 req.header('Referer');668 // => "http://google.com"669670 req.header('Referrer');671 // => "http://google.com"672673### req.accepts(type)674675Check if the _Accept_ header is present, and includes the given _type_.676677When the _Accept_ header is not present _true_ is returned. Otherwise678the given _type_ is matched by an exact match, and then subtypes. You679may pass the subtype such as "html" which is then converted internally680to "text/html" using the mime lookup table.681682 // Accept: text/html683 req.accepts('html');684 // => true685686 // Accept: text/*; application/json687 req.accepts('html');688 req.accepts('text/html');689 req.accepts('text/plain');690 req.accepts('application/json');691 // => true692693 req.accepts('image/png');694 req.accepts('png');695 // => false696697### req.is(type)698699Check if the incoming request contains the _Content-Type_700header field, and it contains the give mime _type_.701 702 // With Content-Type: text/html; charset=utf-8703 req.is('html');704 req.is('text/html');705 // => true706 707 // When Content-Type is application/json708 req.is('json');709 req.is('application/json');710 // => true711 712 req.is('html');713 // => false714 715Ad-hoc callbacks can also be registered with Express, to perform716assertions again the request, for example if we need an expressive717way to check if our incoming request is an image, we can register _"an image"_718callback:719 720 app.is('an image', function(req){721 return 0 == req.headers['content-type'].indexOf('image');722 });723 724Now within our route callbacks, we can use to to assert content types725such as _"image/jpeg"_, _"image/png"_, etc.726 727 app.post('/image/upload', function(req, res, next){728 if (req.is('an image')) {729 // do something730 } else {731 next();732 }733 });734735Keep in mind this method is _not_ limited to checking _Content-Type_, you736can perform any request assertion you wish.737738Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:739740 req.is('image/*');741742We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.743744 req.is('*/json');745746### req.param(name[, default])747748Return the value of param _name_ when present or _default_.749750 - Checks route params (_req.params_), ex: /user/:id751 - Checks query string params (_req.query_), ex: ?id=12752 - Checks urlencoded body params (_req.body_), ex: id=12753754To utilize urlencoded request bodies, _req.body_755should be an object. This can be done by using756the _express.bodyParser middleware.757docs for req.get()Tj Holowaychukbefore adoption6bb100d
lines 758–768why, one step back758### req.get(field, param)759760 Get _field_'s _param_ value, defaulting to '' when the _param_761 or _field_ is not present.762763 req.get('content-disposition', 'filename');764 // => "something.png"765766 req.get('Content-Type', 'boundary');767 // => "--foo-bar-baz"768Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 769–874why, one step back769### req.flash(type[, msg])770771Queue flash _msg_ of the given _type_.772773 req.flash('info', 'email sent');774 req.flash('error', 'email delivery failed');775 req.flash('info', 'email re-sent');776 // => 2777778 req.flash('info');779 // => ['email sent', 'email re-sent']780781 req.flash('info');782 // => []783784 req.flash();785 // => { error: ['email delivery failed'], info: [] }786787Flash notification message may also utilize formatters, by default only the %s string formatter is available:788789 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);790791### req.isXMLHttpRequest792793Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header794to see if it was issued by an _XMLHttpRequest_:795796 req.xhr797 req.isXMLHttpRequest798799### res.header(key[, val])800801Get or set the response header _key_.802803 res.header('Content-Length');804 // => undefined805806 res.header('Content-Length', 123);807 // => 123808 809 res.header('Content-Length');810 // => 123811812### res.charset813814Sets 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:815816 res.charset = 'ISO-8859-1';817 res.render('users');818819or before responding with `res.send()`:820821 res.charset = 'ISO-8859-1';822 res.send(str);823824or with node's `res.end()`:825826 res.charset = 'ISO-8859-1';827 res.header('Content-Type', 'text/plain');828 res.end(str);829830### res.contentType(type)831832Sets the _Content-Type_ response header to the given _type_.833834 var filename = 'path/to/image.png';835 res.contentType(filename);836 // Content-Type is now "image/png"837838A literal _Content-Type_ works as well:839840 res.contentType('application/json');841842Or simply the extension without leading `.`:843844 res.contentType('json');845846### res.attachment([filename])847848Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.849850 res.attachment('path/to/my/image.png');851852### res.sendfile(path[, options[, callback]])853854Used by `res.download()` to transfer an arbitrary file. 855856 res.sendfile('path/to/my.file');857858This method accepts an optional callback which is called when859an 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.860861 res.sendfile(path, function(err){862 if (err) {863 next(err);864 } else {865 console.log('transferred %s', path);866 }867 });868869Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:870871 res.sendfile(path, { bufferSize: 1024 }, function(err){872 // handle873 });874docsTj Holowaychukbefore adoption236a412
line 875why, one step back875### res.download(file[, filename[, callback[, callback2]]])Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 876–886why, one step back876877Transfer the given _file_ as an attachment with optional alternative _filename_.878879 res.download('path/to/image.png');880 res.download('path/to/image.png', 'foo.png');881882This is equivalent to:883884 res.attachment(file);885 res.sendfile(file);886docsTj Holowaychukbefore adoption236a412
line 887why, one step back887An 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 888–890why, one step back888889 res.download(path, 'expenses.doc', function(err){890 // handledocsTj Holowaychukbefore adoption236a412
lines 891–898why, one step back891 });892893An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.894895 res.download(path, function(err){896 // error or finished897 }, function(err){898 // connection related errorMerge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 899–919why, one step back899 });900901### res.send(body|status[, headers|status[, status]])902903The _res.send()_ method is a high level response utility allowing you to pass904objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:905906 res.send(); // 204907 res.send(new Buffer('wahoo'));908 res.send({ some: 'json' });909 res.send('<p>some html</p>');910 res.send('Sorry, cant find that', 404);911 res.send('text', { 'Content-Type': 'text/plain' }, 201);912 res.send(404);913914By default the _Content-Type_ response header is set, however if explicitly915assigned through `res.send()` or previously with `res.header()` or `res.contentType()`916it will not be set again.917918Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.919Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 920–931why, one step back920### res.json(obj[, headers|status[, status]])921922 Send a JSON response with optional _headers_ and _status_. This method923 is ideal for JSON-only APIs, however _res.send(obj)_ will send JSON as924 well, though not ideal for cases when you want to send for example a string925 as JSON, since the default for _res.send(string)_ is text/html.926927 res.json(null);928 res.json({ user: 'tj' });929 res.json('oh noes!', 500);930 res.json('I dont have that', 404);931Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 932–947why, one step back932### res.redirect(url[, status])933934Redirect to the given _url_ with a default response _status_ of 302.935936 res.redirect('/', 301);937 res.redirect('/account');938 res.redirect('http://google.com');939 res.redirect('home');940 res.redirect('back');941942Express supports "redirect mapping", which by default provides _home_, and _back_.943The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes944the "home" setting and defaults to "/".945946### res.cookie(name, val[, options])947docsTj Holowaychukbefore adoption6815feb
lines 948–949why, one step back948Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc. The _path_ option defaults to the app's "home" setting, which949is typically "/".Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 950–957why, one step back950951 // "Remember me" for 15 minutes 952 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });953954The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:955956 res.cookie('rememberme', 'yes', { maxAge: 900000 });957doc typoTj Holowaychukbefore adoption62df63d
line 958why, one step back958To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 959–965why, one step back959960 app.use(express.cookieParser());961 962 app.get('/', function(req, res){963 // use req.cookies.rememberme964 });965Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
line 966why, one step back966### res.clearCookie(name[, options])Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
line 967why, one step back967docsTj Holowaychukbefore adoption6815feb
lines 968–969why, one step back968Clear cookie _name_ by setting "expires" far in the past. Much like969_res.cookie()_ the _path_ option also defaults to the "home" setting.Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 970–1225why, one step back970971 res.clearCookie('rememberme');972973### res.render(view[, options[, fn]])974975Render _view_ with the given _options_ and optional callback _fn_.976When a callback function is given a response will _not_ be made977automatically, however otherwise a response of _200_ and _text/html_ is given.978979The _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:980981 var user = { name: 'tj' };982 res.render('index', { layout: false, user: user });983984### res.partial(view[, options])985986Render _view_ partial with the given _options_. This method is always available987to the view as a local variable.988989- _object_ the object named by _as_ or derived from the view name990- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.991 * as: 'something' will add the _something_ local variable992 * as: this will use the collection value as the template context993 * as: global will merge the collection value's properties with _locals_994995- _collection_ Array of objects, the name is derived from the view name itself. 996 For example _video.html_ will have a object _video_ available to it.997998The following are equivalent, and the name of collection value when passed999to the partial will be _movie_ as derived from the name.10001001 partial('theatre/movie.jade', { collection: movies });1002 partial('theatre/movie.jade', movies);1003 partial('movie.jade', { collection: movies });1004 partial('movie.jade', movies);1005 partial('movie', movies);1006 // In view: movie.director10071008To change the local from _movie_ to _video_ we can use the "as" option:10091010 partial('movie', { collection: movies, as: 'video' });1011 // In view: video.director10121013Also we can make our movie the value of _this_ within our view so that instead1014of _movie.director_ we could use _this.director_.10151016 partial('movie', { collection: movies, as: this });1017 // In view: this.director10181019Another alternative is to "expand" the properties of the collection item into1020pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:10211022 partial('movie', { collection: movies, as: global });1023 // In view: director10241025This same logic applies to a single partial object usage:10261027 partial('movie', { object: movie, as: this });1028 // In view: this.director10291030 partial('movie', { object: movie, as: global });1031 // In view: director10321033 partial('movie', { object: movie, as: 'video' });1034 // In view: video.director10351036 partial('movie', { object: movie });1037 // In view: movie.director10381039When 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:10401041 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')1042 partial('movie', movie)1043 // => In view: movie.director10441045The 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:10461047 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1048 partial('movie', movie)10491050For 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:10511052 partial('movie', { locals: { movie: movie }})1053 partial('movie', { movie: movie })1054 partial('movie', { object: movie })10551056This 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:10571058 app.get('/users', function(req, res){1059 if (req.xhr) {1060 // respond with the each user in the collection1061 // passed to the "user" view1062 res.partial('user', users);1063 } else {1064 // respond with layout, and users page1065 // which internally does partial('user', users)1066 // along with other UI1067 res.render('users', { users: users });1068 }1069 });10701071### res.local(name[, val])10721073Get 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()`.10741075 app.all('/movie/:id', function(req, res, next){1076 Movie.get(req.params.id, function(err, movie){1077 // Assigns res.locals.movie = movie1078 res.local('movie', movie);1079 });1080 });1081 1082 app.get('/movie/:id', function(req, res){1083 // movie is already a local, however we1084 // can pass more if we wish1085 res.render('movie', { displayReviews: true });1086 });10871088### res.locals(obj)10891090 Assign several locals with the given _obj_. The following are equivalent:1091 1092 res.local('foo', bar);1093 res.local('bar', baz);10941095 res.locals({ foo: bar, bar, baz });10961097### app.set(name[, val])10981099Apply an application level setting _name_ to _val_, or1100get the value of _name_ when _val_ is not present:11011102 app.set('views', __dirname + '/views');1103 app.set('views');1104 // => ...path...11051106Alternatively you may simply access the settings via _app.settings_:11071108 app.settings.views1109 // => ...path...11101111### app.enable(name)11121113Enable the given setting _name_:11141115 app.enable('some arbitrary setting');1116 app.set('some arbitrary setting');1117 // => true11181119 app.enabled('some arbitrary setting');1120 // => true11211122### app.enabled(name)11231124Check if setting _name_ is enabled:11251126 app.enabled('view cache');1127 // => false11281129 app.enable('view cache');1130 app.enabled('view cache');1131 // => true11321133### app.disable(name)11341135Disable the given setting _name_:11361137 app.disable('some setting');1138 app.set('some setting');1139 // => false1140 1141 app.disabled('some setting');1142 // => false11431144### app.disabled(name)11451146Check if setting _name_ is disabled:11471148 app.enable('view cache');11491150 app.disabled('view cache');1151 // => false11521153 app.disable('view cache');1154 app.disabled('view cache');1155 // => true11561157### app.configure(env|function[, function])11581159Define a callback function for the given _env_ (or all environments) with callback _function_:11601161 app.configure(function(){1162 // executed for each env1163 });11641165 app.configure('development', function(){1166 // executed for 'development' only1167 });11681169### app.redirect(name, val)11701171For use with _res.redirect()_ we can map redirects at the application level as shown below:11721173 app.redirect('google', 'http://google.com');11741175Now in a route we may call:11761177 res.redirect('google');11781179We may also map dynamic redirects:11801181 app.redirect('comments', function(req, res){1182 return '/post/' + req.params.id + '/comments';1183 });11841185So now we may do the following, and the redirect will dynamically adjust to1186the context of the request. If we called this route with _GET /post/12_ our1187redirect _Location_ would be _/post/12/comments_.11881189 app.get('/post/:id', function(req, res){1190 res.redirect('comments');1191 });11921193When 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_:11941195 res.redirect('/posts');11961197### app.error(function)11981199Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1200Note that we may set several error handlers by making several calls to this method, however the handler1201should call _next(err)_ if it does not wish to deal with the exception:12021203 app.error(function(err, req, res, next){1204 res.send(err.message, 500);1205 });12061207### app.helpers(obj)12081209Registers static view helpers.12101211 app.helpers({1212 name: function(first, last){ return first + ', ' + last }1213 , firstName: 'tj'1214 , lastName: 'holowaychuk'1215 });12161217Our view could now utilize the _firstName_ and _lastName_ variables,1218as well as the _name()_ function exposed.12191220 <%= name(firstName, lastName) %>12211222Express also provides a few locals by default:12231224 - `settings` the app's settings object1225 - `filename` the view's filenamedocsTj Holowaychukbefore adoption885fb1f
line 1226why, one step back1226 - `layout(path)` specify the layout from within a viewMerge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 1227–1246why, one step back12271228This method is aliased as _app.locals()_.12291230### app.dynamicHelpers(obj)12311232Registers dynamic view helpers. Dynamic view helpers1233are simply functions which accept _req_, _res_, and are1234evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1235becomes the local variable it is associated with.12361237 app.dynamicHelpers({1238 session: function(req, res){1239 return req.session;1240 }1241 });12421243All views would now have _session_ available so that session data can be accessed via _session.name_ etc:12441245 <%= session.name %>1246docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1247–1251why, one step back1247### app.lookup12481249 The _app.lookup_ http methods returns an array of callback functions1250 associated with the given _path_.1251docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1252why, one step back1252 Suppose we define the following routes:docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1253–1255why, one step back1253 1254 app.get('/user/:id', function(){});1255 app.put('/user/:id', function(){});docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1256why, one step back1256 app.get('/user/:id/:op?', function(){});docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1257–1264why, one step back12571258 We can utilize this lookup functionality to check which routes1259 have been defined, which can be extremely useful for higher level1260 frameworks built on Express.12611262 app.lookup.get('/user/:id');1263 // => [Function]1264docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1265why, one step back1265 app.lookup.get('/user/:id/:op?');docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1266–1282why, one step back1266 // => [Function]12671268 app.lookup.put('/user/:id');1269 // => [Function]12701271 app.lookup.all('/user/:id');1272 // => [Function, Function]12731274 app.lookup.all('/hey');1275 // => []12761277 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1278 without a callback, as a shortcut, for example the following are1279 equivalent:1280 1281 app.lookup.get('/user');1282 app.get('/user');docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1283why, one step back1283more docsTj Holowaychukbefore adoption6230ec5
lines 1284–1299why, one step back1284 Each function returned has the following properties:1285 1286 var fn = app.get('/user/:id/:op?')[0];12871288 fn.regexp1289 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12901291 fn.keys1292 // => ['id', 'op']12931294 fn.path1295 // => '/user/:id/:op?'12961297 fn.method1298 // => 'GET'1299docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
lines 1300–1327why, one step back1300### app.match13011302 The _app.match_ http methods return an array of callback functions1303 which match the given _url_, which may include a query string etc. This1304 is useful when you want reflect on which routes have the opportunity to1305 respond.13061307 Suppose we define the following routes:13081309 app.get('/user/:id', function(){});1310 app.put('/user/:id', function(){});1311 app.get('/user/:id/:op?', function(){});13121313 Our match against __GET__ will return two functions, since the _:op_1314 in our second route is optional.13151316 app.match.get('/user/1');1317 // => [Function, Function]13181319 This second call returns only the callback for _/user/:id/:op?_.13201321 app.match.get('/user/23/edit');1322 // => [Function]13231324 We can also use _all()_ to disregard the http method:13251326 app.match.all('/user/20');1327 // => [Function, Function, Function]more docsTj Holowaychukbefore adoption6230ec5
lines 1328–1340why, one step back13281329 Each function matched has the following properties:1330 1331 var fn = app.match.get('/user/23/edit')[0];13321333 fn.keys1334 // => ['id', 'op']13351336 fn.params1337 // => { id: '23', op: 'edit' }13381339 fn.method1340 // => 'GET'docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
line 1341why, one step back1341Merge branch 'feature/root-partial-lookup'Tj Holowaychukbefore adoption0c32478
lines 1342–1410why, one step back1342### app.mounted(fn)13431344Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.13451346 var app = express.createServer(),1347 blog = express.createServer();1348 1349 blog.mounted(function(parent){1350 // parent is app1351 // "this" is blog1352 });1353 1354 app.use(blog);13551356### app.register(ext, exports)13571358Register the given template engine _exports_1359as _ext_. For example we may wish to map ".html"1360files to jade:13611362 app.register('.html', require('jade'));13631364This is also useful for libraries that may not1365match extensions correctly. For example my haml.js1366library is installed from npm as "hamljs" so instead1367of layout.hamljs, we can register the engine as ".haml":13681369 app.register('.haml', require('haml-js'));13701371For engines that do not comply with the Express1372specification, we can also wrap their api this way. Below1373we map _.md_ to render markdown files, rendering the html once1374since it will not change on subsequent calls, and support local substitution1375in the form of "{name}".13761377 app.register('.md', {1378 compile: function(str, options){1379 var html = md.toHTML(str);1380 return function(locals){1381 return html.replace(/\{([^}]+)\}/g, function(_, name){1382 return locals[name];1383 });1384 };1385 }1386 });13871388### app.listen([port[, host]])13891390Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1391connections will be accepted via _INADDR_ANY_.13921393 app.listen();1394 app.listen(3000);1395 app.listen(3000, 'n.n.n.n');13961397The _port_ argument may also be a string representing the path to a unix domain socket:13981399 app.listen('/tmp/express.sock');14001401Then try it out:14021403 $ telnet /tmp/express.sock1404 GET / HTTP/1.114051406 HTTP/1.1 200 OK1407 Content-Type: text/plain1408 Content-Length: 111409 1410 Hello World