guide.md
This file
Path
docs/guide.md
1,362 lines · 47.6 KiB · Markdown
Last changed by
removed some old invalid docsTj Holowaychukbefore adoption11ec3cc
History of this fileTake it
The walk stopped after 200 commits: lines older than b5579b6 point at it.
Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1–48why, one step back1### Installation23 $ npm install express45### Creating A Server67 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()_.89 var app = require('express').createServer();10 11 app.get('/', function(req, res){12 res.send('hello world');13 });14 15 app.listen(3000);1617### Creating An HTTPS Server1819 To initialize a _express.HTTPSServer_ we do the same as above, however we20 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).21 22 var app = require('express').createServer({ key: ... });2324### Configuration2526Express supports arbitrary environments, such as _production_ and _development_. Developers27can use the _configure()_ method to setup needs required by the current environment. When28_configure()_ is called without an environment name it will be run in _every_ environment 29prior to the environment specific callback.3031In the example below we only _dumpExceptions_, and respond with exception stack traces32in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.33Note the use of _app.router_, which can (optionally) be used to mount the application routes,34otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.3536 app.configure(function(){37 app.use(express.methodOverride());38 app.use(express.bodyParser());39 app.use(app.router);40 });41 42 app.configure('development', function(){43 app.use(express.static(__dirname + '/public'));44 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));45 });46 47 app.configure('production', function(){48 var oneYear = 31557600000;Docs for staticProvider() changesTj Holowaychukbefore adoption3cacf05
line 49why, one step back49 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 50–83why, one step back50 app.use(express.errorHandler());51 });5253For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:5455 app.configure(function(){56 app.set('views', __dirname + '/views');57 app.set('views');58 // => "/absolute/path/to/views"59 60 app.enable('some feature');61 // same as app.set('some feature', true);62 63 app.disable('some feature');64 // same as app.set('some feature', false);65 66 app.enabled('some feature')67 // => false68 });6970To alter the environment we can set the _NODE_ENV_ environment variable, for example:7172 $ NODE_ENV=production node app.js7374This is _very_ important, as many caching mechanisms are _only enabled_ when in production.7576### Settings7778Express supports the following settings out of the box:7980 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.81 * _views_ Root views directory defaulting to **CWD/views**82 * _view engine_ Default view engine name for views rendered without extensions83 * _view options_ An object specifying global view optionsdocs for "view cache" settingTj Holowaychukbefore adoption805b9ac
line 84why, one step back84 * _view cache_ Enable view caching (enabled in production)Added "case sensitive routes" option.Tj Holowaychukbefore adoptiond2adcbd
line 85why, one step back85 * _case sensitive routes_ Enable case-sensitive routingAdded layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 86–168why, one step back8687### Routing8889Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.90For example we may want to render a user's account for the path _/user/12_, this91can be done by defining the route below. The values associated to the named placeholders 92are available as `req.params`.9394 app.get('/user/:id', function(req, res){95 res.send('user ' + req.params.id);96 });9798A route is simple a string which is compiled to a _RegExp_ internally. For example99when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:100101 \/user\/([^\/]+)\/?102103Regular expression literals may also be passed for complex uses. Since capture104groups 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]_.105106 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){107 res.send(req.params);108 });109110Curl requests against the previously defined route:111112 $ curl http://dev:3000/user113 [null,null]114 $ curl http://dev:3000/users115 [null,null]116 $ curl http://dev:3000/users/1117 ["1",null]118 $ curl http://dev:3000/users/1..15119 ["1","15"]120121Below are some route examples, and the associated paths that they122may consume:123124 "/user/:id"125 /user/12126127 "/users/:id?"128 /users/5129 /users130131 "/files/*"132 /files/jquery.js133 /files/javascripts/jquery.js134135 "/file/*.*"136 /files/jquery.js137 /files/javascripts/jquery.js138 139 "/user/:id/:operation?"140 /user/1141 /user/1/edit142 143 "/products.:format"144 /products.json145 /products.xml146147 "/products.:format?"148 /products.json149 /products.xml150 /products151 152 "/user/:id.:format?"153 /user/12154 /user/12.json155156For 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_:157158 var express = require('express')159 , app = express.createServer();160161 app.use(express.bodyParser());162163 app.post('/', function(req, res){164 res.send(req.body);165 });166167 app.listen(3000);168docsTj Holowaychukbefore adoption6106188
line 169why, one step back169Typically 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.Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 170–237why, one step back170171### Passing Route Control172173We may pass control to the next _matching_ route, by calling the _third_ argument,174the _next()_ function. When a match cannot be made, control is passed back to Connect,175and 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.176177 app.get('/users/:id?', function(req, res, next){178 var id = req.params.id;179 if (id) {180 // do something181 } else {182 next();183 }184 });185 186 app.get('/users', function(req, res){187 // do something else188 });189190The _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_.191192 var express = require('express')193 , app = express.createServer();194195 var users = [{ name: 'tj' }];196197 app.all('/user/:id/:op?', function(req, res, next){198 req.user = users[req.params.id];199 if (req.user) {200 next();201 } else {202 next(new Error('cannot find user ' + req.params.id));203 }204 });205206 app.get('/user/:id', function(req, res){207 res.send('viewing ' + req.user.name);208 });209210 app.get('/user/:id/edit', function(req, res){211 res.send('editing ' + req.user.name);212 });213214 app.put('/user/:id', function(req, res){215 res.send('updating ' + req.user.name);216 });217218 app.get('*', function(req, res){219 res.send('what???', 404);220 });221222 app.listen(3000); 223224### Middleware225226Middleware via [Connect](http://github.com/senchalabs/connect) can be227passed to _express.createServer()_ as you would with a regular Connect server. For example:228229 var express = require('express');230231 var app = express.createServer(232 express.logger()233 , express.bodyParser()234 );235236Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.237Merge pull request #671 from jpalardy/patch-1TJ Holowaychukbefore adoptionc24b2fa
line 238why, one step back238 app.use(express.logger({ format: ':method :url' }));Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 239–250why, one step back239240Typically with connect middleware you would _require('connect')_ like so:241242 var connect = require('connect');243 app.use(connect.logger());244 app.use(connect.bodyParser());245246This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:247248 app.use(express.logger());249 app.use(express.bodyParser());250added better middleware docs and use-casesTj Holowaychukbefore adoption8d6f167
lines 251–277why, one step back251Middleware 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()_.252253Many 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 below254255 app.use(express.logger(...));256 app.use(express.bodyParser(...));257 app.use(express.cookieParser(...));258 app.use(express.session(...));259 app.use(app.router);260 app.use(express.static(...));261 app.use(express.errorHandler(...));262263First 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.264265 var downloads = {};266267 app.use(app.router);268 app.use(express.static(__dirname + '/public'));269270 app.get('/*', function(req, res, next){271 var file = req.params[0];272 downloads[file] = downloads[file] || 0;273 downloads[file]++;274 next();275 });276277Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 278–348why, one step back278### Route Middleware279280Routes 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.281282Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 283284 app.get('/user/:id', function(req, res, next){285 loadUser(req.params.id, function(err, user){286 if (err) return next(err);287 res.send('Viewing user ' + user.name);288 });289 });290291To 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. 292293 function loadUser(req, res, next) {294 // You would fetch your user from the db295 var user = users[req.params.id];296 if (user) {297 req.user = user;298 next();299 } else {300 next(new Error('Failed to load user ' + req.params.id));301 }302 }303 304 app.get('/user/:id', loadUser, function(req, res){305 res.send('Viewing user ' + req.user.name);306 });307308Multiple 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.309310 function andRestrictToSelf(req, res, next) {311 req.authenticatedUser.id == req.user.id312 ? next()313 : next(new Error('Unauthorized'));314 }315 316 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){317 res.send('Editing user ' + req.user.name);318 });319320Keeping 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.321322 function andRestrictTo(role) {323 return function(req, res, next) {324 req.authenticatedUser.role == role325 ? next()326 : next(new Error('Unauthorized'));327 }328 }329 330 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){331 res.send('Deleted user ' + req.user.name);332 });333334Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.335336 var a = [middleware1, middleware2]337 , b = [middleware3, middleware4]338 , all = [a, b];339 340 app.get('/foo', a, function(){});341 app.get('/bar', a, function(){});342 343 app.get('/', a, middleware3, middleware4, function(){});344 app.get('/', a, b, function(){});345 app.get('/', all, function(){});346347For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.348docs for next("route"). Closes #650Tj Holowaychukbefore adoption2648302
lines 349–350why, one step back349There 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.350Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 351–404why, one step back351### HTTP Methods352353We 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.354355 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.356 357 <form method="post" action="/">358 <input type="text" name="user[name]" />359 <input type="text" name="user[email]" />360 <input type="submit" value="Submit" />361 </form>362363By 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:364365 app.use(express.bodyParser());366367Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.368369 app.post('/', function(req, res){370 console.log(req.body.user);371 res.redirect('back');372 });373374When 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.375376 app.use(express.bodyParser());377 app.use(express.methodOverride());378379The 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:380381 <form method="post" action="/">382 <input type="hidden" name="_method" value="put" />383 <input type="text" name="user[name]" />384 <input type="text" name="user[email]" />385 <input type="submit" value="Submit" /> 386 </form>387388 app.put('/', function(){389 console.log(req.body.user);390 res.redirect('back');391 });392393### Error Handling394395Express provides the _app.error()_ method which receives exceptions thrown within a route,396or passed to _next(err)_. Below is an example which serves different pages based on our397ad-hoc _NotFound_ exception:398399 function NotFound(msg){400 this.name = 'NotFound';401 Error.call(this, msg);402 Error.captureStackTrace(this, arguments.callee);403 }404 doc typoTj Holowaychukbefore adoptionfae1ba9
line 405why, one step back405 NotFound.prototype.__proto__ = Error.prototype;Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 406–547why, one step back406 407 app.get('/404', function(req, res){408 throw new NotFound;409 });410 411 app.get('/500', function(req, res){412 throw new Error('keyboard cat!');413 });414415We can call _app.error()_ several times as shown below.416Here we check for an instanceof _NotFound_ and show the417404 page, or we pass on to the next error handler.418419Note that these handlers can be defined anywhere, as they420will be placed below the route handlers on _listen()_. This 421allows for definition within _configure()_ blocks so we can422handle exceptions in different ways based on the environment.423424 app.error(function(err, req, res, next){425 if (err instanceof NotFound) {426 res.render('404.jade');427 } else {428 next(err);429 }430 });431432Here we assume all errors as 500 for the simplicity of433this 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.434435 app.error(function(err, req, res){436 res.render('500.jade', {437 error: err438 });439 });440441Our apps could also utilize the Connect _errorHandler_ middleware442to report on exceptions. For example if we wish to output exceptions 443in "development" mode to _stderr_ we can use:444445 app.use(express.errorHandler({ dumpExceptions: true }));446447Also during development we may want fancy html pages to show exceptions448that are passed or thrown, so we can set _showStack_ to true:449450 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));451452The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_453is present, which is useful for developing apps that rely heavily on client-side JavaScript.454455### Route Param Pre-conditions456457Route 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:458459 app.get('/user/:userId', function(req, res, next){460 User.get(req.params.userId, function(err, user){461 if (err) return next(err);462 res.send('user ' + user.name);463 });464 }); 465466With 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.467468 app.param('userId', function(req, res, next, id){469 User.get(id, function(err, user){470 if (err) return next(err);471 if (!user) return next(new Error('failed to find user'));472 req.user = user;473 next();474 });475 });476477Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:478479 app.get('/user/:userId', function(req, res){480 res.send('user ' + req.user.name);481 });482483### View Rendering484485View filenames take the form "<name>.<engine>", where <engine> is the name486of the module that will be required. For example the view _layout.ejs_ will487tell 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 behaviour488_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.489490Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,491and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 492the _body_ local variable in _layout.jade_.493494 app.get('/', function(req, res){495 res.render('index.jade', { title: 'My Site' });496 });497498The new _view engine_ setting allows us to specify our default template engine,499so for example when using jade we could set:500501 app.set('view engine', 'jade');502503Allowing us to render with:504505 res.render('index');506507vs:508509 res.render('index.jade');510511When _view engine_ is set, extensions are entirely optional, however we can still512mix and match template engines:513514 res.render('another-page.ejs');515516Express 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:517518 app.set('view options', {519 layout: false520 });521522Which can then be overridden within the _res.render()_ call if need be:523524 res.render('myview.ejs', { layout: true });525526When 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:527528 res.render('page', { layout: 'mylayout' });529530Otherwise we must specify the extension:531532 res.render('page', { layout: 'mylayout.jade' });533534These paths may also be absolute:535536 res.render('page', { layout: __dirname + '/../../mylayout.jade' });537538A good example of this is specifying custom _ejs_ opening and closing tags:539540 app.set('view options', {541 open: '{{',542 close: '}}'543 });544545### View Partials546547The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iteratingdocs for partial changesTj Holowaychukbefore adoption20b8fac
line 548why, one step back548in a view to display comments, we could use partial collection:Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 549–551why, one step back549550 partial('comment', { collection: comments });551docs for partial changesTj Holowaychukbefore adoption20b8fac
line 552why, one step back552If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 553–555why, one step back553554 partial('comment', comments);555docs for partial changesTj Holowaychukbefore adoption20b8fac
line 556why, one step back556When using the partial collection support a few "magic" locals are providedAdded layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 557–777why, one step back557for free:558559 * _firstInCollection_ true if this is the first object560 * _indexInCollection_ index of the object in the collection561 * _lastInCollection_ true if this is the last object562 * _collectionLength_ length of the collection563564Local 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.565566For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).567568__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.569570### View Lookup571572View 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_.573574The 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_.575576When 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')_.577578### Template Engines579580Below are a few template engines commonly used with Express:581582 * [Haml](http://github.com/visionmedia/haml.js) haml implementation583 * [Jade](http://jade-lang.com) haml.js successor584 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript585 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating586 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node587588### Session Support589590Sessions 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_.591592 app.use(express.cookieParser());593 app.use(express.session({ secret: "keyboard cat" }));594595By 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:596597 var RedisStore = require('connect-redis');598 app.use(express.cookieParser());599 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));600601Now 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:602603 var RedisStore = require('connect-redis');604 app.use(express.bodyParser());605 app.use(express.cookieParser());606 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));607608 app.post('/add-to-cart', function(req, res){609 // Perhaps we posted several items with a form610 // (use the bodyParser() middleware for this)611 var items = req.body.items;612 req.session.items = items;613 res.redirect('back');614 });615616 app.get('/add-to-cart', function(req, res){617 // When redirected back to GET /add-to-cart618 // we could check req.session.items && req.session.items.length619 // to print out a message620 if (req.session.items && req.session.items.length) {621 req.flash('info', 'You have %s items in your cart', req.session.items.length);622 }623 res.render('shopping-cart');624 });625626The _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.627628### Migration Guide629630 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.631632### req.header(key[, defaultValue])633634Get the case-insensitive request header _key_, with optional _defaultValue_:635636 req.header('Host');637 req.header('host');638 req.header('Accept', '*/*');639640The _Referrer_ and _Referer_ header fields are special-cased, either will work:641642 // sent Referrer: http://google.com643644 req.header('Referer');645 // => "http://google.com"646647 req.header('Referrer');648 // => "http://google.com"649650### req.accepts(type)651652Check if the _Accept_ header is present, and includes the given _type_.653654When the _Accept_ header is not present _true_ is returned. Otherwise655the given _type_ is matched by an exact match, and then subtypes. You656may pass the subtype such as "html" which is then converted internally657to "text/html" using the mime lookup table.658659 // Accept: text/html660 req.accepts('html');661 // => true662663 // Accept: text/*; application/json664 req.accepts('html');665 req.accepts('text/html');666 req.accepts('text/plain');667 req.accepts('application/json');668 // => true669670 req.accepts('image/png');671 req.accepts('png');672 // => false673674### req.is(type)675676Check if the incoming request contains the _Content-Type_677header field, and it contains the give mime _type_.678 679 // With Content-Type: text/html; charset=utf-8680 req.is('html');681 req.is('text/html');682 // => true683 684 // When Content-Type is application/json685 req.is('json');686 req.is('application/json');687 // => true688 689 req.is('html');690 // => false691 692Ad-hoc callbacks can also be registered with Express, to perform693assertions again the request, for example if we need an expressive694way to check if our incoming request is an image, we can register _"an image"_695callback:696 697 app.is('an image', function(req){698 return 0 == req.headers['content-type'].indexOf('image');699 });700 701Now within our route callbacks, we can use to to assert content types702such as _"image/jpeg"_, _"image/png"_, etc.703 704 app.post('/image/upload', function(req, res, next){705 if (req.is('an image')) {706 // do something707 } else {708 next();709 }710 });711712Keep in mind this method is _not_ limited to checking _Content-Type_, you713can perform any request assertion you wish.714715Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:716717 req.is('image/*');718719We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.720721 req.is('*/json');722723### req.param(name[, default])724725Return the value of param _name_ when present or _default_.726727 - Checks route params (_req.params_), ex: /user/:id728 - Checks query string params (_req.query_), ex: ?id=12729 - Checks urlencoded body params (_req.body_), ex: id=12730731To utilize urlencoded request bodies, _req.body_732should be an object. This can be done by using733the _express.bodyParser middleware.734735### req.flash(type[, msg])736737Queue flash _msg_ of the given _type_.738739 req.flash('info', 'email sent');740 req.flash('error', 'email delivery failed');741 req.flash('info', 'email re-sent');742 // => 2743744 req.flash('info');745 // => ['email sent', 'email re-sent']746747 req.flash('info');748 // => []749750 req.flash();751 // => { error: ['email delivery failed'], info: [] }752753Flash notification message may also utilize formatters, by default only the %s string formatter is available:754755 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);756757### req.isXMLHttpRequest758759Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header760to see if it was issued by an _XMLHttpRequest_:761762 req.xhr763 req.isXMLHttpRequest764765### res.header(key[, val])766767Get or set the response header _key_.768769 res.header('Content-Length');770 // => undefined771772 res.header('Content-Length', 123);773 // => 123774 775 res.header('Content-Length');776 // => 123777docs for charsetTj Holowaychukbefore adoptiond12452f
lines 778–795why, one step back778### res.charset779780Sets 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:781782 res.charset = 'ISO-8859-1';783 res.render('users');784785or before responding with `res.send()`:786787 res.charset = 'ISO-8859-1';788 res.send(str);789790or with node's `res.end()`:791792 res.charset = 'ISO-8859-1';793 res.header('Content-Type', 'text/plain');794 res.end(str);795Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 796–803why, one step back796### res.contentType(type)797798Sets the _Content-Type_ response header to the given _type_.799800 var filename = 'path/to/image.png';801 res.contentType(filename);802 // Content-Type is now "image/png"803docs for res.contentType() literalTj Holowaychukbefore adoption3d8400a
lines 804–807why, one step back804A literal _Content-Type_ works as well:805806 res.contentType('application/json');807Release 2.0.0beta3Tj Holowaychukbefore adoption1536d73
lines 808–811why, one step back808Or simply the extension without leading `.`:809810 res.contentType('json');811Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 812–840why, one step back812### res.attachment([filename])813814Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.815816 res.attachment('path/to/my/image.png');817818### res.sendfile(path[, options[, callback]])819820Used by `res.download()` to transfer an arbitrary file. 821822 res.sendfile('path/to/my.file');823824This method accepts an optional callback which is called when825an 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.826827 res.sendfile(path, function(err){828 if (err) {829 next(err);830 } else {831 console.log('transferred %s', path);832 }833 });834835Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:836837 res.sendfile(path, { bufferSize: 1024 }, function(err){838 // handle839 });840docsTj Holowaychukbefore adoption236a412
line 841why, one step back841### res.download(file[, filename[, callback[, callback2]]])Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 842–852why, one step back842843Transfer the given _file_ as an attachment with optional alternative _filename_.844845 res.download('path/to/image.png');846 res.download('path/to/image.png', 'foo.png');847848This is equivalent to:849850 res.attachment(file);851 res.sendfile(file);852docsTj Holowaychukbefore adoption236a412
line 853why, one step back853An 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.Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 854–856why, one step back854855 res.download(path, 'expenses.doc', function(err){856 // handledocsTj Holowaychukbefore adoption236a412
lines 857–864why, one step back857 });858859An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.860861 res.download(path, function(err){862 // error or finished863 }, function(err){864 // connection related errorAdded layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 865–910why, one step back865 });866867### res.send(body|status[, headers|status[, status]])868869The _res.send()_ method is a high level response utility allowing you to pass870objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:871872 res.send(); // 204873 res.send(new Buffer('wahoo'));874 res.send({ some: 'json' });875 res.send('<p>some html</p>');876 res.send('Sorry, cant find that', 404);877 res.send('text', { 'Content-Type': 'text/plain' }, 201);878 res.send(404);879880By default the _Content-Type_ response header is set, however if explicitly881assigned through `res.send()` or previously with `res.header()` or `res.contentType()`882it will not be set again.883884Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.885886### res.redirect(url[, status])887888Redirect to the given _url_ with a default response _status_ of 302.889890 res.redirect('/', 301);891 res.redirect('/account');892 res.redirect('http://google.com');893 res.redirect('home');894 res.redirect('back');895896Express supports "redirect mapping", which by default provides _home_, and _back_.897The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes898the "home" setting and defaults to "/".899900### res.cookie(name, val[, options])901902Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc.903904 // "Remember me" for 15 minutes 905 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });906907The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:908909 res.cookie('rememberme', 'yes', { maxAge: 900000 });910doc typoTj Holowaychukbefore adoption62df63d
line 911why, one step back911To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 912–918why, one step back912913 app.use(express.cookieParser());914 915 app.get('/', function(req, res){916 // use req.cookies.rememberme917 });918Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
line 919why, one step back919### res.clearCookie(name[, options])Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 920–970why, one step back920921Clear cookie _name_ by setting "expires" far in the past.922923 res.clearCookie('rememberme');924925### res.render(view[, options[, fn]])926927Render _view_ with the given _options_ and optional callback _fn_.928When a callback function is given a response will _not_ be made929automatically, however otherwise a response of _200_ and _text/html_ is given.930931The _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:932933 var user = { name: 'tj' };934 res.render('index', { layout: false, user: user });935936### res.partial(view[, options])937938Render _view_ partial with the given _options_. This method is always available939to the view as a local variable.940941- _object_ the object named by _as_ or derived from the view name942- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.943 * as: 'something' will add the _something_ local variable944 * as: this will use the collection value as the template context945 * as: global will merge the collection value's properties with _locals_946947- _collection_ Array of objects, the name is derived from the view name itself. 948 For example _video.html_ will have a object _video_ available to it.949950The following are equivalent, and the name of collection value when passed951to the partial will be _movie_ as derived from the name.952953 partial('theatre/movie.jade', { collection: movies });954 partial('theatre/movie.jade', movies);955 partial('movie.jade', { collection: movies });956 partial('movie.jade', movies);957 partial('movie', movies);958 // In view: movie.director959960To change the local from _movie_ to _video_ we can use the "as" option:961962 partial('movie', { collection: movies, as: 'video' });963 // In view: video.director964965Also we can make our movie the value of _this_ within our view so that instead966of _movie.director_ we could use _this.director_.967968 partial('movie', { collection: movies, as: this });969 // In view: this.director970docs for partial changesTj Holowaychukbefore adoption20b8fac
line 971why, one step back971Another alternative is to "expand" the properties of the collection item intoAdded layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 972–992why, one step back972pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:973974 partial('movie', { collection: movies, as: global });975 // In view: director976977This same logic applies to a single partial object usage:978979 partial('movie', { object: movie, as: this });980 // In view: this.director981982 partial('movie', { object: movie, as: global });983 // In view: director984985 partial('movie', { object: movie, as: 'video' });986 // In view: video.director987988 partial('movie', { object: movie });989 // In view: movie.director990991When 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:992docs for partial changesTj Holowaychukbefore adoption20b8fac
lines 993–994why, one step back993 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')994 partial('movie', movie)Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
line 995why, one step back995 // => In view: movie.directordocs for partial changesTj Holowaychukbefore adoption20b8fac
lines 996–1006why, one step back996997The 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:998999 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 1000 partial('movie', movie)10011002For 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:10031004 partial('movie', { locals: { movie: movie }})1005 partial('movie', { movie: movie })1006 partial('movie', { object: movie })Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1007–1039why, one step back10071008This 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:10091010 app.get('/users', function(req, res){1011 if (req.xhr) {1012 // respond with the each user in the collection1013 // passed to the "user" view1014 res.partial('user', users);1015 } else {1016 // respond with layout, and users page1017 // which internally does partial('user', users)1018 // along with other UI1019 res.render('users', { users: users });1020 }1021 });10221023### res.local(name[, val])10241025Get 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()`.10261027 app.all('/movie/:id', function(req, res, next){1028 Movie.get(req.params.id, function(err, movie){1029 // Assigns res.locals.movie = movie1030 res.local('movie', movie);1031 });1032 });1033 1034 app.get('/movie/:id', function(req, res){1035 // movie is already a local, however we1036 // can pass more if we wish1037 res.render('movie', { displayReviews: true });1038 });1039doc typoTj Holowaychukbefore adoptionc3e6326
line 1040why, one step back1040### res.locals(obj)Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a
lines 1041–1048why, one step back10411042 Assign several locals with the given _obj_. The following are equivalent:1043 1044 res.local('foo', bar);1045 res.local('bar', baz);10461047 res.locals({ foo: bar, bar, baz });1048Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1049–1162why, one step back1049### app.set(name[, val])10501051Apply an application level setting _name_ to _val_, or1052get the value of _name_ when _val_ is not present:10531054 app.set('views', __dirname + '/views');1055 app.set('views');1056 // => ...path...10571058Alternatively you may simply access the settings via _app.settings_:10591060 app.settings.views1061 // => ...path...10621063### app.enable(name)10641065Enable the given setting _name_:10661067 app.enable('some arbitrary setting');1068 app.set('some arbitrary setting');1069 // => true10701071 app.enabled('some arbitrary setting');1072 // => true10731074### app.enabled(name)10751076Check if setting _name_ is enabled:10771078 app.enabled('view cache');1079 // => false10801081 app.enable('view cache');1082 app.enabled('view cache');1083 // => true10841085### app.disable(name)10861087Disable the given setting _name_:10881089 app.disable('some setting');1090 app.set('some setting');1091 // => false1092 1093 app.disabled('some setting');1094 // => false10951096### app.disabled(name)10971098Check if setting _name_ is disabled:10991100 app.enable('view cache');11011102 app.disabled('view cache');1103 // => false11041105 app.disable('view cache');1106 app.disabled('view cache');1107 // => true11081109### app.configure(env|function[, function])11101111Define a callback function for the given _env_ (or all environments) with callback _function_:11121113 app.configure(function(){1114 // executed for each env1115 });11161117 app.configure('development', function(){1118 // executed for 'development' only1119 });11201121### app.redirect(name, val)11221123For use with _res.redirect()_ we can map redirects at the application level as shown below:11241125 app.redirect('google', 'http://google.com');11261127Now in a route we may call:11281129 res.redirect('google');11301131We may also map dynamic redirects:11321133 app.redirect('comments', function(req, res){1134 return '/post/' + req.params.id + '/comments';1135 });11361137So now we may do the following, and the redirect will dynamically adjust to1138the context of the request. If we called this route with _GET /post/12_ our1139redirect _Location_ would be _/post/12/comments_.11401141 app.get('/post/:id', function(req, res){1142 res.redirect('comments');1143 });11441145When 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_:11461147 res.redirect('/posts');11481149### app.error(function)11501151Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1152Note that we may set several error handlers by making several calls to this method, however the handler1153should call _next(err)_ if it does not wish to deal with the exception:11541155 app.error(function(err, req, res, next){1156 res.send(err.message, 500);1157 });11581159### app.helpers(obj)11601161Registers static view helpers.1162Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1163–1167why, one step back1163 app.helpers({1164 name: function(first, last){ return first + ', ' + last }1165 , firstName: 'tj'1166 , lastName: 'holowaychuk'1167 });Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1168–1172why, one step back11681169Our view could now utilize the _firstName_ and _lastName_ variables,1170as well as the _name()_ function exposed.11711172 <%= name(firstName, lastName) %>Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1173–1176why, one step back11731174Express also provides a few locals by default:11751176 - `settings` the app's settings objectdocs for "filename" localTj Holowaychukbefore adoptionbf06d90
line 1177why, one step back1177 - `filename` the view's filenamedocsTj Holowaychukbefore adoption885fb1f
line 1178why, one step back1178 - `layout(path)` specify the layout from within a viewAdded 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1179–1180why, one step back11791180This method is aliased as _app.locals()_.Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1181–1198why, one step back11811182### app.dynamicHelpers(obj)11831184Registers dynamic view helpers. Dynamic view helpers1185are simply functions which accept _req_, _res_, and are1186evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1187becomes the local variable it is associated with.11881189 app.dynamicHelpers({1190 session: function(req, res){1191 return req.session;1192 }1193 });11941195All views would now have _session_ available so that session data can be accessed via _session.name_ etc:11961197 <%= session.name %>1198docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1199–1203why, one step back1199### app.lookup12001201 The _app.lookup_ http methods returns an array of callback functions1202 associated with the given _path_.1203docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1204why, one step back1204 Suppose we define the following routes:docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1205–1207why, one step back1205 1206 app.get('/user/:id', function(){});1207 app.put('/user/:id', function(){});docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1208why, one step back1208 app.get('/user/:id/:op?', function(){});docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1209–1216why, one step back12091210 We can utilize this lookup functionality to check which routes1211 have been defined, which can be extremely useful for higher level1212 frameworks built on Express.12131214 app.lookup.get('/user/:id');1215 // => [Function]1216docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1217why, one step back1217 app.lookup.get('/user/:id/:op?');docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1218–1234why, one step back1218 // => [Function]12191220 app.lookup.put('/user/:id');1221 // => [Function]12221223 app.lookup.all('/user/:id');1224 // => [Function, Function]12251226 app.lookup.all('/hey');1227 // => []12281229 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1230 without a callback, as a shortcut, for example the following are1231 equivalent:1232 1233 app.lookup.get('/user');1234 app.get('/user');docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1235why, one step back1235more docsTj Holowaychukbefore adoption6230ec5
lines 1236–1251why, one step back1236 Each function returned has the following properties:1237 1238 var fn = app.get('/user/:id/:op?')[0];12391240 fn.regexp1241 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12421243 fn.keys1244 // => ['id', 'op']12451246 fn.path1247 // => '/user/:id/:op?'12481249 fn.method1250 // => 'GET'1251docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
lines 1252–1279why, one step back1252### app.match12531254 The _app.match_ http methods return an array of callback functions1255 which match the given _url_, which may include a query string etc. This1256 is useful when you want reflect on which routes have the opportunity to1257 respond.12581259 Suppose we define the following routes:12601261 app.get('/user/:id', function(){});1262 app.put('/user/:id', function(){});1263 app.get('/user/:id/:op?', function(){});12641265 Our match against __GET__ will return two functions, since the _:op_1266 in our second route is optional.12671268 app.match.get('/user/1');1269 // => [Function, Function]12701271 This second call returns only the callback for _/user/:id/:op?_.12721273 app.match.get('/user/23/edit');1274 // => [Function]12751276 We can also use _all()_ to disregard the http method:12771278 app.match.all('/user/20');1279 // => [Function, Function, Function]more docsTj Holowaychukbefore adoption6230ec5
lines 1280–1292why, one step back12801281 Each function matched has the following properties:1282 1283 var fn = app.match.get('/user/23/edit')[0];12841285 fn.keys1286 // => ['id', 'op']12871288 fn.params1289 // => { id: '23', op: 'edit' }12901291 fn.method1292 // => 'GET'docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
line 1293why, one step back1293Added layout lookup support relative to the page viewTj Holowaychukbefore adoptionb5579b6
lines 1294–1362why, one step back1294### app.mounted(fn)12951296Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.12971298 var app = express.createServer(),1299 blog = express.createServer();1300 1301 blog.mounted(function(parent){1302 // parent is app1303 // "this" is blog1304 });1305 1306 app.use(blog);13071308### app.register(ext, exports)13091310Register the given template engine _exports_1311as _ext_. For example we may wish to map ".html"1312files to jade:13131314 app.register('.html', require('jade'));13151316This is also useful for libraries that may not1317match extensions correctly. For example my haml.js1318library is installed from npm as "hamljs" so instead1319of layout.hamljs, we can register the engine as ".haml":13201321 app.register('.haml', require('haml-js'));13221323For engines that do not comply with the Express1324specification, we can also wrap their api this way. Below1325we map _.md_ to render markdown files, rendering the html once1326since it will not change on subsequent calls, and support local substitution1327in the form of "{name}".13281329 app.register('.md', {1330 compile: function(str, options){1331 var html = md.toHTML(str);1332 return function(locals){1333 return html.replace(/\{([^}]+)\}/g, function(_, name){1334 return locals[name];1335 });1336 };1337 }1338 });13391340### app.listen([port[, host]])13411342Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1343connections will be accepted via _INADDR_ANY_.13441345 app.listen();1346 app.listen(3000);1347 app.listen(3000, 'n.n.n.n');13481349The _port_ argument may also be a string representing the path to a unix domain socket:13501351 app.listen('/tmp/express.sock');13521353Then try it out:13541355 $ telnet /tmp/express.sock1356 GET / HTTP/1.113571358 HTTP/1.1 200 OK1359 Content-Type: text/plain1360 Content-Length: 111361 1362 Hello World