guide.md
This file
Path
docs/guide.md
1,344 lines · 45.6 KiB · Markdown
Last changed by
docs for next("route"). Closes #650Tj Holowaychukbefore adoption2648302
History of this fileTake it
The walk stopped after 200 commits: lines older than 4c274c5 point at it.
Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1–49why, one step back12### Installation34 $ npm install express56### Creating A Server78 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()_.910 var app = require('express').createServer();11 12 app.get('/', function(req, res){13 res.send('hello world');14 });15 16 app.listen(3000);1718### Creating An HTTPS Server1920 To initialize a _express.HTTPSServer_ we do the same as above, however we21 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).22 23 var app = require('express').createServer({ key: ... });2425### Configuration2627Express supports arbitrary environments, such as _production_ and _development_. Developers28can use the _configure()_ method to setup needs required by the current environment. When29_configure()_ is called without an environment name it will be run in _every_ environment 30prior to the environment specific callback.3132In the example below we only _dumpExceptions_, and respond with exception stack traces33in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.34Note the use of _app.router_, which can (optionally) be used to mount the application routes,35otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.3637 app.configure(function(){38 app.use(express.methodOverride());39 app.use(express.bodyParser());40 app.use(app.router);41 });42 43 app.configure('development', function(){44 app.use(express.static(__dirname + '/public'));45 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));46 });47 48 app.configure('production', function(){49 var oneYear = 31557600000;Docs for staticProvider() changesTj Holowaychukbefore adoption3cacf05
line 50why, one step back50 app.use(express.static(__dirname + '/public', { maxAge: oneYear }));Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 51–84why, one step back51 app.use(express.errorHandler());52 });5354For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:5556 app.configure(function(){57 app.set('views', __dirname + '/views');58 app.set('views');59 // => "/absolute/path/to/views"60 61 app.enable('some feature');62 // same as app.set('some feature', true);63 64 app.disable('some feature');65 // same as app.set('some feature', false);66 67 app.enabled('some feature')68 // => false69 });7071To alter the environment we can set the _NODE_ENV_ environment variable, for example:7273 $ NODE_ENV=production node app.js7475This is _very_ important, as many caching mechanisms are _only enabled_ when in production.7677### Settings7879Express supports the following settings out of the box:8081 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.82 * _views_ Root views directory defaulting to **CWD/views**83 * _view engine_ Default view engine name for views rendered without extensions84 * _view options_ An object specifying global view optionsdocs for "view cache" settingTj Holowaychukbefore adoption805b9ac
line 85why, one step back85 * _view cache_ Enable view caching (enabled in production)Added "case sensitive routes" option.Tj Holowaychukbefore adoptiond2adcbd
line 86why, one step back86 * _case sensitive routes_ Enable case-sensitive routingAdded res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 87–169why, one step back8788### Routing8990Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.91For example we may want to render a user's account for the path _/user/12_, this92can be done by defining the route below. The values associated to the named placeholders 93are available as `req.params`.9495 app.get('/user/:id', function(req, res){96 res.send('user ' + req.params.id);97 });9899A route is simple a string which is compiled to a _RegExp_ internally. For example100when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:101102 \/user\/([^\/]+)\/?103104Regular expression literals may also be passed for complex uses. Since capture105groups 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]_.106107 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){108 res.send(req.params);109 });110111Curl requests against the previously defined route:112113 $ curl http://dev:3000/user114 [null,null]115 $ curl http://dev:3000/users116 [null,null]117 $ curl http://dev:3000/users/1118 ["1",null]119 $ curl http://dev:3000/users/1..15120 ["1","15"]121122Below are some route examples, and the associated paths that they123may consume:124125 "/user/:id"126 /user/12127128 "/users/:id?"129 /users/5130 /users131132 "/files/*"133 /files/jquery.js134 /files/javascripts/jquery.js135136 "/file/*.*"137 /files/jquery.js138 /files/javascripts/jquery.js139 140 "/user/:id/:operation?"141 /user/1142 /user/1/edit143 144 "/products.:format"145 /products.json146 /products.xml147148 "/products.:format?"149 /products.json150 /products.xml151 /products152 153 "/user/:id.:format?"154 /user/12155 /user/12.json156157For 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_:158159 var express = require('express')160 , app = express.createServer();161162 app.use(express.bodyParser());163164 app.post('/', function(req, res){165 res.send(req.body);166 });167168 app.listen(3000);169markdown escapingTj Holowaychukbefore adoptionf0df843
line 170why, one step back170Typically 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(\\\\d+)'_ which will _not_ match unless the placeholder value contains only digits.Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 171–322why, one step back171172### Passing Route Control173174We may pass control to the next _matching_ route, by calling the _third_ argument,175the _next()_ function. When a match cannot be made, control is passed back to Connect,176and 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.177178 app.get('/users/:id?', function(req, res, next){179 var id = req.params.id;180 if (id) {181 // do something182 } else {183 next();184 }185 });186 187 app.get('/users', function(req, res){188 // do something else189 });190191The _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_.192193 var express = require('express')194 , app = express.createServer();195196 var users = [{ name: 'tj' }];197198 app.all('/user/:id/:op?', function(req, res, next){199 req.user = users[req.params.id];200 if (req.user) {201 next();202 } else {203 next(new Error('cannot find user ' + req.params.id));204 }205 });206207 app.get('/user/:id', function(req, res){208 res.send('viewing ' + req.user.name);209 });210211 app.get('/user/:id/edit', function(req, res){212 res.send('editing ' + req.user.name);213 });214215 app.put('/user/:id', function(req, res){216 res.send('updating ' + req.user.name);217 });218219 app.get('*', function(req, res){220 res.send('what???', 404);221 });222223 app.listen(3000); 224225### Middleware226227Middleware via [Connect](http://github.com/senchalabs/connect) can be228passed to _express.createServer()_ as you would with a regular Connect server. For example:229230 var express = require('express');231232 var app = express.createServer(233 express.logger()234 , express.bodyParser()235 );236237Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.238239 app.use(express.logger({ format: ':method :uri' }));240241Typically with connect middleware you would _require('connect')_ like so:242243 var connect = require('connect');244 app.use(connect.logger());245 app.use(connect.bodyParser());246247This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:248249 app.use(express.logger());250 app.use(express.bodyParser());251252### Route Middleware253254Routes 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.255256Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 257258 app.get('/user/:id', function(req, res, next){259 loadUser(req.params.id, function(err, user){260 if (err) return next(err);261 res.send('Viewing user ' + user.name);262 });263 });264265To 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. 266267 function loadUser(req, res, next) {268 // You would fetch your user from the db269 var user = users[req.params.id];270 if (user) {271 req.user = user;272 next();273 } else {274 next(new Error('Failed to load user ' + req.params.id));275 }276 }277 278 app.get('/user/:id', loadUser, function(req, res){279 res.send('Viewing user ' + req.user.name);280 });281282Multiple 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.283284 function andRestrictToSelf(req, res, next) {285 req.authenticatedUser.id == req.user.id286 ? next()287 : next(new Error('Unauthorized'));288 }289 290 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){291 res.send('Editing user ' + req.user.name);292 });293294Keeping 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.295296 function andRestrictTo(role) {297 return function(req, res, next) {298 req.authenticatedUser.role == role299 ? next()300 : next(new Error('Unauthorized'));301 }302 }303 304 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){305 res.send('Deleted user ' + req.user.name);306 });307308Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.309310 var a = [middleware1, middleware2]311 , b = [middleware3, middleware4]312 , all = [a, b];313 314 app.get('/foo', a, function(){});315 app.get('/bar', a, function(){});316 317 app.get('/', a, middleware3, middleware4, function(){});318 app.get('/', a, b, function(){});319 app.get('/', all, function(){});320321For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.322docs for next("route"). Closes #650Tj Holowaychukbefore adoption2648302
lines 323–324why, one step back323There 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.324Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 325–378why, one step back325### HTTP Methods326327We 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.328329 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.330 331 <form method="post" action="/">332 <input type="text" name="user[name]" />333 <input type="text" name="user[email]" />334 <input type="submit" value="Submit" />335 </form>336337By 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:338339 app.use(express.bodyParser());340341Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.342343 app.post('/', function(req, res){344 console.log(req.body.user);345 res.redirect('back');346 });347348When 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.349350 app.use(express.bodyParser());351 app.use(express.methodOverride());352353The 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:354355 <form method="post" action="/">356 <input type="hidden" name="_method" value="put" />357 <input type="text" name="user[name]" />358 <input type="text" name="user[email]" />359 <input type="submit" value="Submit" /> 360 </form>361362 app.put('/', function(){363 console.log(req.body.user);364 res.redirect('back');365 });366367### Error Handling368369Express provides the _app.error()_ method which receives exceptions thrown within a route,370or passed to _next(err)_. Below is an example which serves different pages based on our371ad-hoc _NotFound_ exception:372373 function NotFound(msg){374 this.name = 'NotFound';375 Error.call(this, msg);376 Error.captureStackTrace(this, arguments.callee);377 }378 doc typoTj Holowaychukbefore adoptionfae1ba9
line 379why, one step back379 NotFound.prototype.__proto__ = Error.prototype;Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 380–529why, one step back380 381 app.get('/404', function(req, res){382 throw new NotFound;383 });384 385 app.get('/500', function(req, res){386 throw new Error('keyboard cat!');387 });388389We can call _app.error()_ several times as shown below.390Here we check for an instanceof _NotFound_ and show the391404 page, or we pass on to the next error handler.392393Note that these handlers can be defined anywhere, as they394will be placed below the route handlers on _listen()_. This 395allows for definition within _configure()_ blocks so we can396handle exceptions in different ways based on the environment.397398 app.error(function(err, req, res, next){399 if (err instanceof NotFound) {400 res.render('404.jade');401 } else {402 next(err);403 }404 });405406Here we assume all errors as 500 for the simplicity of407this 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.408409 app.error(function(err, req, res){410 res.render('500.jade', {411 error: err412 });413 });414415Our apps could also utilize the Connect _errorHandler_ middleware416to report on exceptions. For example if we wish to output exceptions 417in "development" mode to _stderr_ we can use:418419 app.use(express.errorHandler({ dumpExceptions: true }));420421Also during development we may want fancy html pages to show exceptions422that are passed or thrown, so we can set _showStack_ to true:423424 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));425426The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_427is present, which is useful for developing apps that rely heavily on client-side JavaScript.428429### Route Param Pre-conditions430431Route 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:432433 app.get('/user/:userId', function(req, res, next){434 User.get(req.params.userId, function(err, user){435 if (err) return next(err);436 res.send('user ' + user.name);437 });438 }); 439440With 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.441442 app.param('userId', function(req, res, next, id){443 User.get(id, function(err, user){444 if (err) return next(err);445 if (!user) return next(new Error('failed to find user'));446 req.user = user;447 next();448 });449 });450451Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:452453 app.get('/user/:userId', function(req, res){454 res.send('user ' + req.user.name);455 });456457For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument). Any errors thrown will be passed to _next(err)_.458459 app.param('number', function(n){ return parseInt(n, 10); });460461We may also apply the same callback to several placeholders, for example a route GET _/commits/:from-:to_ are both numbers, so we may define them as an array:462463 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });464465### View Rendering466467View filenames take the form "<name>.<engine>", where <engine> is the name468of the module that will be required. For example the view _layout.ejs_ will469tell 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 behaviour470_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.471472Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,473and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 474the _body_ local variable in _layout.jade_.475476 app.get('/', function(req, res){477 res.render('index.jade', { title: 'My Site' });478 });479480The new _view engine_ setting allows us to specify our default template engine,481so for example when using jade we could set:482483 app.set('view engine', 'jade');484485Allowing us to render with:486487 res.render('index');488489vs:490491 res.render('index.jade');492493When _view engine_ is set, extensions are entirely optional, however we can still494mix and match template engines:495496 res.render('another-page.ejs');497498Express 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:499500 app.set('view options', {501 layout: false502 });503504Which can then be overridden within the _res.render()_ call if need be:505506 res.render('myview.ejs', { layout: true });507508When 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:509510 res.render('page', { layout: 'mylayout' });511512Otherwise we must specify the extension:513514 res.render('page', { layout: 'mylayout.jade' });515516These paths may also be absolute:517518 res.render('page', { layout: __dirname + '/../../mylayout.jade' });519520A good example of this is specifying custom _ejs_ opening and closing tags:521522 app.set('view options', {523 open: '{{',524 close: '}}'525 });526527### View Partials528529The 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 530why, one step back530in a view to display comments, we could use partial collection:Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 531–533why, one step back531532 partial('comment', { collection: comments });533docs for partial changesTj Holowaychukbefore adoption20b8fac
line 534why, one step back534If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 535–537why, one step back535536 partial('comment', comments);537docs for partial changesTj Holowaychukbefore adoption20b8fac
line 538why, one step back538When using the partial collection support a few "magic" locals are providedAdded res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 539–563why, one step back539for free:540541 * _firstInCollection_ true if this is the first object542 * _indexInCollection_ index of the object in the collection543 * _lastInCollection_ true if this is the last object544 * _collectionLength_ length of the collection545546Local 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.547548For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).549550__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.551552### View Lookup553554View 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_.555556The 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_.557558When 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')_.559560### Template Engines561562Below are a few template engines commonly used with Express:563Add haml back in docsTj Holowaychukbefore adoptione85752c
line 564why, one step back564 * [Haml](http://github.com/visionmedia/haml.js) haml implementationAdded res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 565–759why, one step back565 * [Jade](http://jade-lang.com) haml.js successor566 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript567 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating568 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node569570### Session Support571572Sessions 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_.573574 app.use(express.cookieParser());575 app.use(express.session({ secret: "keyboard cat" }));576577By 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:578579 var RedisStore = require('connect-redis');580 app.use(express.cookieParser());581 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));582583Now 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:584585 var RedisStore = require('connect-redis');586 app.use(express.bodyParser());587 app.use(express.cookieParser());588 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));589590 app.post('/add-to-cart', function(req, res){591 // Perhaps we posted several items with a form592 // (use the bodyParser() middleware for this)593 var items = req.body.items;594 req.session.items = items;595 res.redirect('back');596 });597598 app.get('/add-to-cart', function(req, res){599 // When redirected back to GET /add-to-cart600 // we could check req.session.items && req.session.items.length601 // to print out a message602 if (req.session.items && req.session.items.length) {603 req.flash('info', 'You have %s items in your cart', req.session.items.length);604 }605 res.render('shopping-cart');606 });607608The _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.609610### Migration Guide611612 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.613614### req.header(key[, defaultValue])615616Get the case-insensitive request header _key_, with optional _defaultValue_:617618 req.header('Host');619 req.header('host');620 req.header('Accept', '*/*');621622The _Referrer_ and _Referer_ header fields are special-cased, either will work:623624 // sent Referrer: http://google.com625626 req.header('Referer');627 // => "http://google.com"628629 req.header('Referrer');630 // => "http://google.com"631632### req.accepts(type)633634Check if the _Accept_ header is present, and includes the given _type_.635636When the _Accept_ header is not present _true_ is returned. Otherwise637the given _type_ is matched by an exact match, and then subtypes. You638may pass the subtype such as "html" which is then converted internally639to "text/html" using the mime lookup table.640641 // Accept: text/html642 req.accepts('html');643 // => true644645 // Accept: text/*; application/json646 req.accepts('html');647 req.accepts('text/html');648 req.accepts('text/plain');649 req.accepts('application/json');650 // => true651652 req.accepts('image/png');653 req.accepts('png');654 // => false655656### req.is(type)657658Check if the incoming request contains the _Content-Type_659header field, and it contains the give mime _type_.660 661 // With Content-Type: text/html; charset=utf-8662 req.is('html');663 req.is('text/html');664 // => true665 666 // When Content-Type is application/json667 req.is('json');668 req.is('application/json');669 // => true670 671 req.is('html');672 // => false673 674Ad-hoc callbacks can also be registered with Express, to perform675assertions again the request, for example if we need an expressive676way to check if our incoming request is an image, we can register _"an image"_677callback:678 679 app.is('an image', function(req){680 return 0 == req.headers['content-type'].indexOf('image');681 });682 683Now within our route callbacks, we can use to to assert content types684such as _"image/jpeg"_, _"image/png"_, etc.685 686 app.post('/image/upload', function(req, res, next){687 if (req.is('an image')) {688 // do something689 } else {690 next();691 }692 });693694Keep in mind this method is _not_ limited to checking _Content-Type_, you695can perform any request assertion you wish.696697Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:698699 req.is('image/*');700701We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.702703 req.is('*/json');704705### req.param(name[, default])706707Return the value of param _name_ when present or _default_.708709 - Checks route params (_req.params_), ex: /user/:id710 - Checks query string params (_req.query_), ex: ?id=12711 - Checks urlencoded body params (_req.body_), ex: id=12712713To utilize urlencoded request bodies, _req.body_714should be an object. This can be done by using715the _express.bodyParser middleware.716717### req.flash(type[, msg])718719Queue flash _msg_ of the given _type_.720721 req.flash('info', 'email sent');722 req.flash('error', 'email delivery failed');723 req.flash('info', 'email re-sent');724 // => 2725726 req.flash('info');727 // => ['email sent', 'email re-sent']728729 req.flash('info');730 // => []731732 req.flash();733 // => { error: ['email delivery failed'], info: [] }734735Flash notification message may also utilize formatters, by default only the %s string formatter is available:736737 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);738739### req.isXMLHttpRequest740741Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header742to see if it was issued by an _XMLHttpRequest_:743744 req.xhr745 req.isXMLHttpRequest746747### res.header(key[, val])748749Get or set the response header _key_.750751 res.header('Content-Length');752 // => undefined753754 res.header('Content-Length', 123);755 // => 123756 757 res.header('Content-Length');758 // => 123759docs for charsetTj Holowaychukbefore adoptiond12452f
lines 760–777why, one step back760### res.charset761762Sets 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:763764 res.charset = 'ISO-8859-1';765 res.render('users');766767or before responding with `res.send()`:768769 res.charset = 'ISO-8859-1';770 res.send(str);771772or with node's `res.end()`:773774 res.charset = 'ISO-8859-1';775 res.header('Content-Type', 'text/plain');776 res.end(str);777Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 778–785why, one step back778### res.contentType(type)779780Sets the _Content-Type_ response header to the given _type_.781782 var filename = 'path/to/image.png';783 res.contentType(filename);784 // Content-Type is now "image/png"785docs for res.contentType() literalTj Holowaychukbefore adoption3d8400a
lines 786–789why, one step back786A literal _Content-Type_ works as well:787788 res.contentType('application/json');789Release 2.0.0beta3Tj Holowaychukbefore adoption1536d73
lines 790–793why, one step back790Or simply the extension without leading `.`:791792 res.contentType('json');793Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 794–822why, one step back794### res.attachment([filename])795796Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.797798 res.attachment('path/to/my/image.png');799800### res.sendfile(path[, options[, callback]])801802Used by `res.download()` to transfer an arbitrary file. 803804 res.sendfile('path/to/my.file');805806This method accepts an optional callback which is called when807an 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.808809 res.sendfile(path, function(err){810 if (err) {811 next(err);812 } else {813 console.log('transferred %s', path);814 }815 });816817Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:818819 res.sendfile(path, { bufferSize: 1024 }, function(err){820 // handle821 });822docsTj Holowaychukbefore adoption236a412
line 823why, one step back823### res.download(file[, filename[, callback[, callback2]]])Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 824–834why, one step back824825Transfer the given _file_ as an attachment with optional alternative _filename_.826827 res.download('path/to/image.png');828 res.download('path/to/image.png', 'foo.png');829830This is equivalent to:831832 res.attachment(file);833 res.sendfile(file);834docsTj Holowaychukbefore adoption236a412
line 835why, one step back835An 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 res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 836–838why, one step back836837 res.download(path, 'expenses.doc', function(err){838 // handledocsTj Holowaychukbefore adoption236a412
lines 839–846why, one step back839 });840841An optional second callback, _callback2_ may be given to allow you to act on connection related errors, however you should not attempt to respond.842843 res.download(path, function(err){844 // error or finished845 }, function(err){846 // connection related errorAdded res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 847–888why, one step back847 });848849### res.send(body|status[, headers|status[, status]])850851The _res.send()_ method is a high level response utility allowing you to pass852objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:853854 res.send(); // 204855 res.send(new Buffer('wahoo'));856 res.send({ some: 'json' });857 res.send('<p>some html</p>');858 res.send('Sorry, cant find that', 404);859 res.send('text', { 'Content-Type': 'text/plain' }, 201);860 res.send(404);861862By default the _Content-Type_ response header is set, however if explicitly863assigned through `res.send()` or previously with `res.header()` or `res.contentType()`864it will not be set again.865866Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.867868### res.redirect(url[, status])869870Redirect to the given _url_ with a default response _status_ of 302.871872 res.redirect('/', 301);873 res.redirect('/account');874 res.redirect('http://google.com');875 res.redirect('home');876 res.redirect('back');877878Express supports "redirect mapping", which by default provides _home_, and _back_.879The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes880the "home" setting and defaults to "/".881882### res.cookie(name, val[, options])883884Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc.885886 // "Remember me" for 15 minutes 887 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });888docs for res.cookie()Tj Holowaychukbefore adoption00e1dbf
lines 889–892why, one step back889The _maxAge_ property may be used to set _expires_ relative to _Date.now()_ in milliseconds, so our example above can now become:890891 res.cookie('rememberme', 'yes', { maxAge: 900000 });892doc typoTj Holowaychukbefore adoption62df63d
line 893why, one step back893To parse incoming _Cookie_ headers, use the _cookieParser_ middleware, which provides the _req.cookies_ object:Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 894–900why, one step back894895 app.use(express.cookieParser());896 897 app.get('/', function(req, res){898 // use req.cookies.rememberme899 });900Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
line 901why, one step back901### res.clearCookie(name[, options])Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 902–952why, one step back902903Clear cookie _name_ by setting "expires" far in the past.904905 res.clearCookie('rememberme');906907### res.render(view[, options[, fn]])908909Render _view_ with the given _options_ and optional callback _fn_.910When a callback function is given a response will _not_ be made911automatically, however otherwise a response of _200_ and _text/html_ is given.912913The _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:914915 var user = { name: 'tj' };916 res.render('index', { layout: false, user: user });917918### res.partial(view[, options])919920Render _view_ partial with the given _options_. This method is always available921to the view as a local variable.922923- _object_ the object named by _as_ or derived from the view name924- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.925 * as: 'something' will add the _something_ local variable926 * as: this will use the collection value as the template context927 * as: global will merge the collection value's properties with _locals_928929- _collection_ Array of objects, the name is derived from the view name itself. 930 For example _video.html_ will have a object _video_ available to it.931932The following are equivalent, and the name of collection value when passed933to the partial will be _movie_ as derived from the name.934935 partial('theatre/movie.jade', { collection: movies });936 partial('theatre/movie.jade', movies);937 partial('movie.jade', { collection: movies });938 partial('movie.jade', movies);939 partial('movie', movies);940 // In view: movie.director941942To change the local from _movie_ to _video_ we can use the "as" option:943944 partial('movie', { collection: movies, as: 'video' });945 // In view: video.director946947Also we can make our movie the value of _this_ within our view so that instead948of _movie.director_ we could use _this.director_.949950 partial('movie', { collection: movies, as: this });951 // In view: this.director952docs for partial changesTj Holowaychukbefore adoption20b8fac
line 953why, one step back953Another alternative is to "expand" the properties of the collection item intoAdded res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 954–974why, one step back954pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:955956 partial('movie', { collection: movies, as: global });957 // In view: director958959This same logic applies to a single partial object usage:960961 partial('movie', { object: movie, as: this });962 // In view: this.director963964 partial('movie', { object: movie, as: global });965 // In view: director966967 partial('movie', { object: movie, as: 'video' });968 // In view: video.director969970 partial('movie', { object: movie });971 // In view: movie.director972973When 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:974docs for partial changesTj Holowaychukbefore adoption20b8fac
lines 975–976why, one step back975 var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')976 partial('movie', movie)Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
line 977why, one step back977 // => In view: movie.directordocs for partial changesTj Holowaychukbefore adoption20b8fac
lines 978–988why, one step back978979The 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:980981 var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' }; 982 partial('movie', movie)983984For 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:985986 partial('movie', { locals: { movie: movie }})987 partial('movie', { movie: movie })988 partial('movie', { object: movie })Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 989–1021why, one step back989990This 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:991992 app.get('/users', function(req, res){993 if (req.xhr) {994 // respond with the each user in the collection995 // passed to the "user" view996 res.partial('user', users);997 } else {998 // respond with layout, and users page999 // which internally does partial('user', users)1000 // along with other UI1001 res.render('users', { users: users });1002 }1003 });10041005### res.local(name[, val])10061007Get 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()`.10081009 app.all('/movie/:id', function(req, res, next){1010 Movie.get(req.params.id, function(err, movie){1011 // Assigns res.locals.movie = movie1012 res.local('movie', movie);1013 });1014 });1015 1016 app.get('/movie/:id', function(req, res){1017 // movie is already a local, however we1018 // can pass more if we wish1019 res.render('movie', { displayReviews: true });1020 });1021doc typoTj Holowaychukbefore adoptionc3e6326
line 1022why, one step back1022### res.locals(obj)Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a
lines 1023–1030why, one step back10231024 Assign several locals with the given _obj_. The following are equivalent:1025 1026 res.local('foo', bar);1027 res.local('bar', baz);10281029 res.locals({ foo: bar, bar, baz });1030Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1031–1144why, one step back1031### app.set(name[, val])10321033Apply an application level setting _name_ to _val_, or1034get the value of _name_ when _val_ is not present:10351036 app.set('views', __dirname + '/views');1037 app.set('views');1038 // => ...path...10391040Alternatively you may simply access the settings via _app.settings_:10411042 app.settings.views1043 // => ...path...10441045### app.enable(name)10461047Enable the given setting _name_:10481049 app.enable('some arbitrary setting');1050 app.set('some arbitrary setting');1051 // => true10521053 app.enabled('some arbitrary setting');1054 // => true10551056### app.enabled(name)10571058Check if setting _name_ is enabled:10591060 app.enabled('view cache');1061 // => false10621063 app.enable('view cache');1064 app.enabled('view cache');1065 // => true10661067### app.disable(name)10681069Disable the given setting _name_:10701071 app.disable('some setting');1072 app.set('some setting');1073 // => false1074 1075 app.disabled('some setting');1076 // => false10771078### app.disabled(name)10791080Check if setting _name_ is disabled:10811082 app.enable('view cache');10831084 app.disabled('view cache');1085 // => false10861087 app.disable('view cache');1088 app.disabled('view cache');1089 // => true10901091### app.configure(env|function[, function])10921093Define a callback function for the given _env_ (or all environments) with callback _function_:10941095 app.configure(function(){1096 // executed for each env1097 });10981099 app.configure('development', function(){1100 // executed for 'development' only1101 });11021103### app.redirect(name, val)11041105For use with _res.redirect()_ we can map redirects at the application level as shown below:11061107 app.redirect('google', 'http://google.com');11081109Now in a route we may call:11101111 res.redirect('google');11121113We may also map dynamic redirects:11141115 app.redirect('comments', function(req, res){1116 return '/post/' + req.params.id + '/comments';1117 });11181119So now we may do the following, and the redirect will dynamically adjust to1120the context of the request. If we called this route with _GET /post/12_ our1121redirect _Location_ would be _/post/12/comments_.11221123 app.get('/post/:id', function(req, res){1124 res.redirect('comments');1125 });11261127When 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_:11281129 res.redirect('/posts');11301131### app.error(function)11321133Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1134Note that we may set several error handlers by making several calls to this method, however the handler1135should call _next(err)_ if it does not wish to deal with the exception:11361137 app.error(function(err, req, res, next){1138 res.send(err.message, 500);1139 });11401141### app.helpers(obj)11421143Registers static view helpers.1144Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1145–1149why, one step back1145 app.helpers({1146 name: function(first, last){ return first + ', ' + last }1147 , firstName: 'tj'1148 , lastName: 'holowaychuk'1149 });Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1150–1154why, one step back11501151Our view could now utilize the _firstName_ and _lastName_ variables,1152as well as the _name()_ function exposed.11531154 <%= name(firstName, lastName) %>Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1155–1158why, one step back11551156Express also provides a few locals by default:11571158 - `settings` the app's settings objectdocs for "filename" localTj Holowaychukbefore adoptionbf06d90
line 1159why, one step back1159 - `filename` the view's filenamedocsTj Holowaychukbefore adoption885fb1f
line 1160why, one step back1160 - `layout(path)` specify the layout from within a viewAdded 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 1161–1162why, one step back11611162This method is aliased as _app.locals()_.Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1163–1180why, one step back11631164### app.dynamicHelpers(obj)11651166Registers dynamic view helpers. Dynamic view helpers1167are simply functions which accept _req_, _res_, and are1168evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1169becomes the local variable it is associated with.11701171 app.dynamicHelpers({1172 session: function(req, res){1173 return req.session;1174 }1175 });11761177All views would now have _session_ available so that session data can be accessed via _session.name_ etc:11781179 <%= session.name %>1180docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1181–1185why, one step back1181### app.lookup11821183 The _app.lookup_ http methods returns an array of callback functions1184 associated with the given _path_.1185docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1186why, one step back1186 Suppose we define the following routes:docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1187–1189why, one step back1187 1188 app.get('/user/:id', function(){});1189 app.put('/user/:id', function(){});docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1190why, one step back1190 app.get('/user/:id/:op?', function(){});docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1191–1198why, one step back11911192 We can utilize this lookup functionality to check which routes1193 have been defined, which can be extremely useful for higher level1194 frameworks built on Express.11951196 app.lookup.get('/user/:id');1197 // => [Function]1198docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1199why, one step back1199 app.lookup.get('/user/:id/:op?');docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
lines 1200–1216why, one step back1200 // => [Function]12011202 app.lookup.put('/user/:id');1203 // => [Function]12041205 app.lookup.all('/user/:id');1206 // => [Function, Function]12071208 app.lookup.all('/hey');1209 // => []12101211 To alias _app.lookup.VERB()_, we can simply invoke _app.VERB()_1212 without a callback, as a shortcut, for example the following are1213 equivalent:1214 1215 app.lookup.get('/user');1216 app.get('/user');docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
line 1217why, one step back1217more docsTj Holowaychukbefore adoption6230ec5
lines 1218–1233why, one step back1218 Each function returned has the following properties:1219 1220 var fn = app.get('/user/:id/:op?')[0];12211222 fn.regexp1223 // => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i12241225 fn.keys1226 // => ['id', 'op']12271228 fn.path1229 // => '/user/:id/:op?'12301231 fn.method1232 // => 'GET'1233docs for app.match.VERB()Tj Holowaychukbefore adoptionbc244ed
lines 1234–1261why, one step back1234### app.match12351236 The _app.match_ http methods return an array of callback functions1237 which match the given _url_, which may include a query string etc. This1238 is useful when you want reflect on which routes have the opportunity to1239 respond.12401241 Suppose we define the following routes:12421243 app.get('/user/:id', function(){});1244 app.put('/user/:id', function(){});1245 app.get('/user/:id/:op?', function(){});12461247 Our match against __GET__ will return two functions, since the _:op_1248 in our second route is optional.12491250 app.match.get('/user/1');1251 // => [Function, Function]12521253 This second call returns only the callback for _/user/:id/:op?_.12541255 app.match.get('/user/23/edit');1256 // => [Function]12571258 We can also use _all()_ to disregard the http method:12591260 app.match.all('/user/20');1261 // => [Function, Function, Function]more docsTj Holowaychukbefore adoption6230ec5
lines 1262–1274why, one step back12621263 Each function matched has the following properties:1264 1265 var fn = app.match.get('/user/23/edit')[0];12661267 fn.keys1268 // => ['id', 'op']12691270 fn.params1271 // => { id: '23', op: 'edit' }12721273 fn.method1274 // => 'GET'docs for app.lookup.VERB()Tj Holowaychukbefore adoption41266aa
line 1275why, one step back1275Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5
lines 1276–1344why, one step back1276### app.mounted(fn)12771278Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.12791280 var app = express.createServer(),1281 blog = express.createServer();1282 1283 blog.mounted(function(parent){1284 // parent is app1285 // "this" is blog1286 });1287 1288 app.use(blog);12891290### app.register(ext, exports)12911292Register the given template engine _exports_1293as _ext_. For example we may wish to map ".html"1294files to jade:12951296 app.register('.html', require('jade'));12971298This is also useful for libraries that may not1299match extensions correctly. For example my haml.js1300library is installed from npm as "hamljs" so instead1301of layout.hamljs, we can register the engine as ".haml":13021303 app.register('.haml', require('haml-js'));13041305For engines that do not comply with the Express1306specification, we can also wrap their api this way. Below1307we map _.md_ to render markdown files, rendering the html once1308since it will not change on subsequent calls, and support local substitution1309in the form of "{name}".13101311 app.register('.md', {1312 compile: function(str, options){1313 var html = md.toHTML(str);1314 return function(locals){1315 return html.replace(/\{([^}]+)\}/g, function(_, name){1316 return locals[name];1317 });1318 };1319 }1320 });13211322### app.listen([port[, host]])13231324Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1325connections will be accepted via _INADDR_ANY_.13261327 app.listen();1328 app.listen(3000);1329 app.listen(3000, 'n.n.n.n');13301331The _port_ argument may also be a string representing the path to a unix domain socket:13321333 app.listen('/tmp/express.sock');13341335Then try it out:13361337 $ telnet /tmp/express.sock1338 GET / HTTP/1.113391340 HTTP/1.1 200 OK1341 Content-Type: text/plain1342 Content-Length: 111343 1344 Hello World