guide.md
This file
Path
docs/guide.md
1,108 lines · 37.2 KiB · Markdown
Last changed by
Removed "stream threshold" settingTj Holowaychukbefore adoptionee4c7d3
History of this fileTake it
The walk stopped after 200 commits: lines older than 1a6d245 point at it.
Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 1–38why, one step back12### Installation34curl:56 $ curl -# http://expressjs.com/install.sh | sh78npm:910 $ npm install express1112### Creating An Application1314The _express.Server_ now inherits from _http.Server_, however15follows the same idiom by providing _express.createServer()_ as shown below. This means16that you can utilize Express server's transparently with other libraries.1718 var app = require('express').createServer();19 20 app.get('/', function(req, res){21 res.send('hello world');22 });23 24 app.listen(3000);2526### Configuration2728Express supports arbitrary environments, such as _production_ and _development_. Developers29can use the _configure()_ method to setup needs required by the current environment. When30_configure()_ is called without an environment name it will be run in _every_ environment 31prior to the environment specific callback.3233In the example below we only _dumpExceptions_, and respond with exception stack traces34in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.35Note the use of _app.router_, which can (optionally) be used to mount the application routes,36otherwise the first call to _app.{get,put,del,post}()_ will mount the routes.3738 app.configure(function(){DocsTj Holowaychukbefore adoption5234368
lines 39–42why, one step back39 app.use(express.methodOverride());40 app.use(express.bodyDecoder());41 app.use(app.router);42 });Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
line 43why, one step back43 DocsTj Holowaychukbefore adoption5234368
line 44why, one step back44 app.configure('development', function(){Updated connect submoduleTj Holowaychukbefore adoptiona9db47f
line 45why, one step back45 app.use(express.staticProvider(__dirname + '/public'));DocsTj Holowaychukbefore adoption5234368
lines 46–47why, one step back46 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));47 });Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
line 48why, one step back48 DocsTj Holowaychukbefore adoption5234368
line 49why, one step back49 app.configure('production', function(){Updated connect submoduleTj Holowaychukbefore adoptiona9db47f
lines 50–51why, one step back50 var oneYear = 31557600000;51 app.use(express.staticProvider({ root: __dirname + '/public', maxAge: oneYear }));DocsTj Holowaychukbefore adoption5234368
lines 52–53why, one step back52 app.use(express.errorHandler());53 });Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 54–92why, one step back5455For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:5657 app.configure(function(){58 app.set('views', __dirname + '/views');59 app.set('views');60 // => "... views directory ..."61 62 app.enable('some feature');63 // same as app.set('some feature', true);64 65 app.disable('some feature');66 // same as app.set('some feature', false);67 });6869To alter the environment we can set the _NODE_ENV_ environment variable, for example:7071 $ NODE_ENV=production node app.js7273This is _very_ important, as many caching mechanisms are _only enabled_ when in production.7475### Settings7677Express supports the following settings out of the box:7879 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_80 * _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 options8485### Routing8687Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.88For example we may want to render a user's account for the path _/user/12_, this89can be done by defining the route below. The values associated to the named placeholders 90are available as `req.params`.9192 app.get('/user/:id', function(req, res){DocsTj Holowaychukbefore adoption5234368
lines 93–94why, one step back93 res.send('user ' + req.params.id);94 });Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 95–101why, one step back9596A route is simple a string which is compiled to a _RegExp_ internally. For example97when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:9899 \/user\/([^\/]+)\/?100101Regular expression literals may also be passed for complex uses. Since captureDocsTj Holowaychukbefore adoptionbba049b
line 102why, one step back102groups 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]_.Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 103–148why, one step back103104 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){105 res.send(req.params);106 });107108Curl requests against the previously defined route:109110 $ curl http://dev:3000/user111 [null,null]112 $ curl http://dev:3000/users113 [null,null]114 $ curl http://dev:3000/users/1115 ["1",null]116 $ curl http://dev:3000/users/1..15117 ["1","15"]118119Below are some route examples, and the associated paths that they120may consume:121122 "/user/:id"123 /user/12124125 "/users/:id?"126 /users/5127 /users128129 "/files/*"130 /files/jquery.js131 /files/javascripts/jquery.js132133 "/file/*.*"134 /files/jquery.js135 /files/javascripts/jquery.js136 137 "/user/:id/:operation?"138 /user/1139 /user/1/edit140 141 "/products.:format"142 /products.json143 /products.xml144145 "/products.:format?"146 /products.json147 /products.xml148 /productsDocsTj Holowaychukbefore adoptionbba049b
lines 149–152why, one step back149 150 "/user/:id.:format?"151 /user/12152 /user/12.jsonAdded -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
line 153why, one step back153DocsTj Holowaychukbefore adoption5234368
lines 154–165why, one step back154For example we can __POST__ some json, and echo the json back using the _bodyDecoder_ middleware which will parse json request bodies (as well as others), and place the result in _req.body_:155156 var express = require('express')157 , app = express.createServer();158159 app.use(express.bodyDecoder());160161 app.post('/', function(req, res){162 res.send(req.body);163 });164165 app.listen(3000);DocsTj Holowaychukbefore adoptionbba049b
line 166why, one step back166DocsTj Holowaychukbefore adoption14dce5a
line 167why, one step back167Express 2.0.0-pre also supports named capture groups. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, 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.DocsTj Holowaychukbefore adoption5234368
line 168why, one step back168Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 169–186why, one step back169### Passing Route Control170171We may pass control to the next _matching_ route, by calling the _third_ argument,172the _next()_ function. When a match cannot be made, control is passed back to Connect,173and middleware continue to be invoked. 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()_.174175 app.get('/users/:id?', function(req, res, next){176 var id = req.params.id;177 if (id) {178 // do something179 } else {180 next();181 }182 });183 184 app.get('/users', function(req, res){185 // do something else186 });DocsTj Holowaychukbefore adoption5234368
lines 187–220why, one step back187188Express 1.0 also introduces the _all()_ method, which provides a route callback matching any HTTP method. This is useful in many ways, one example being the loading of resources before executing subsequent routes as shown below:189190 var express = require('express')191 , app = express.createServer();192193 var users = [{ name: 'tj' }];194195 app.all('/user/:id/:op?', function(req, res, next){196 req.user = users[req.params.id];197 if (req.user) {198 next();199 } else {200 next(new Error('cannot find user ' + req.params.id));201 }202 });203204 app.get('/user/:id', function(req, res){205 res.send('viewing ' + req.user.name);206 });207208 app.get('/user/:id/edit', function(req, res){209 res.send('editing ' + req.user.name);210 });211212 app.put('/user/:id', function(req, res){213 res.send('updating ' + req.user.name);214 });215216 app.get('*', function(req, res){217 res.send('what???', 404);218 });219220 app.listen(3000); Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 221–423why, one step back221222### Middleware223224Middleware via [Connect](http://github.com/senchalabs/connect) can be225passed to _express.createServer()_ as you would with a regular Connect server. For example:226227 var express = require('express');228229 var app = express.createServer(230 express.logger(),231 express.bodyDecoder()232 );233234Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:235236 app.use(express.logger({ format: ':method :uri' }));237238Typically with connect middleware you would _require('connect')_ like so:239240 var connect = require('connect');241 app.use(connect.logger());242243This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:244245 app.use(express.logger());246247### Route Middleware248249Routes 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.250251Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 252253 app.get('/user/:id', function(req, res, next){254 loadUser(req.params.id, function(err, user){255 if (err) return next(err);256 res.send('Viewing user ' + user.name);257 });258 });259260To 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. 261262 function loadUser(req, res, next) {263 // You would fetch your user from the db264 var user = users[req.params.id];265 if (user) {266 req.user = user;267 next();268 } else {269 next(new Error('Failed to load user ' + req.params.id));270 }271 }272 273 app.get('/user/:id', loadUser, function(req, res){274 res.send('Viewing user ' + req.user.name);275 });276277Multiple 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.278279 function andRestrictToSelf(req, res, next) {280 req.authenticatedUser.id == req.user.id281 ? next()282 : next(new Error('Unauthorized'));283 }284 285 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){286 res.send('Editing user ' + req.user.name);287 });288289Keeping 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.290291 function andRestrictTo(role) {292 return function(req, res, next) {293 req.authenticatedUser.role == role294 ? next()295 : next(new Error('Unauthorized'));296 }297 }298 299 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){300 res.send('Deleted user ' + req.user.name);301 });302303Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.304305 var a = [middleware1, middleware2]306 , b = [middleware3, middleware4]307 , all = [a, b];308 309 app.get('/foo', a, function(){});310 app.get('/bar', a, function(){});311 312 app.get('/', a, middleware3, middleware4, function(){});313 app.get('/', a, b, function(){});314 app.get('/', all, function(){});315316For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.317318### HTTP Methods319320We 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.321322 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.323 324 <form method="post" action="/">325 <input type="text" name="user[name]" />326 <input type="text" name="user[email]" />327 <input type="submit" value="Submit" />328 </form>329330By default Express does not know what to do with this request body, so we should add the _bodyDecoder_ middleware, which will parse _application/x-www-form-urlencoded_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:331332 app.use(express.bodyDecoder());333334Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.335336 app.post('/', function(req, res){337 console.log(req.body.user);338 res.redirect('back');339 });340341When 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 _bodyDecoder_ so that it can utilize it's _req.body_ containing the form values.342343 app.use(express.bodyDecoder());344 app.use(express.methodOverride());345346The 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:347348 <form method="post" action="/">349 <input type="hidden" name="_method" value="put" />350 <input type="text" name="user[name]" />351 <input type="text" name="user[email]" />352 <input type="submit" value="Submit" /> 353 </form>354355 app.put('/', function(){356 console.log(req.body.user);357 res.redirect('back');358 });359360### Error Handling361362Express provides the _app.error()_ method which receives exceptions thrown within a route,363or passed to _next(err)_. Below is an example which serves different pages based on our364ad-hoc _NotFound_ exception:365366 function NotFound(msg){367 this.name = 'NotFound';368 Error.call(this, msg);369 Error.captureStackTrace(this, arguments.callee);370 }371372 sys.inherits(NotFound, Error);373374 app.get('/404', function(req, res){375 throw new NotFound;376 });377378 app.get('/500', function(req, res){379 throw new Error('keyboard cat!');380 });381382We can call _app.error()_ several times as shown below.383Here we check for an instanceof _NotFound_ and show the384404 page, or we pass on to the next error handler.385386Note that these handlers can be defined anywhere, as they387will be placed below the route handlers on _listen()_. This 388allows for definition within _configure()_ blocks so we can389handle exceptions in different ways based on the environment.390391 app.error(function(err, req, res, next){392 if (err instanceof NotFound) {393 res.render('404.jade');394 } else {395 next(err);396 }397 });398399Here we assume all errors as 500 for the simplicity of400this demo, however you can choose whatever you like401402 app.error(function(err, req, res){403 res.render('500.jade', {404 locals: {405 error: err406 } 407 });408 });409410Our apps could also utilize the Connect _errorHandler_ middleware411to report on exceptions. For example if we wish to output exceptions 412in "development" mode to _stderr_ we can use:413414 app.use(express.errorHandler({ dumpExceptions: true }));415416Also during development we may want fancy html pages to show exceptions417that are passed or thrown, so we can set _showStack_ to true:418419 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));420421The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_422is present, which is useful for developing apps that rely heavily on client-side JavaScript.423Route precondition docsTj Holowaychukbefore adoptionfd2f67b
lines 424–459why, one step back424### Route Preconditions425426Route placeholder 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:427428 app.get('/user/:userId', function(req, res, next){429 User.get(req.params.userId, function(err, user){430 if (err) return next(err);431 res.send('user ' + user.name);432 });433 }); 434435With route preconditions our placeholders 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.436437 app.param('userId', function(req, res, next, id){438 User.get(id, function(err, user){439 if (err) return next(err);440 if (!user) return next(new Error('failed to find user'));441 req.user = user;442 next();443 });444 });445446Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:447448 app.get('/user/:userId', function(req, res){449 res.send('user ' + req.user.name);450 });451452For 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)_.453454 app.param('number', function(n){ return parseInt(n, 10); });455456We 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:457458 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });459Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 460–550why, one step back460### View Rendering461462View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name463of the module that will be required. For example the view _layout.ejs_ will464tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 465_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.466467Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,468and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 469the _body_ local variable in _layout.haml_.470471 app.get('/', function(req, res){472 res.render('index.haml', {473 locals: { title: 'My Site' }474 });475 });476477The new _view engine_ setting allows us to specify our default template engine,478so for example when using [Jade](http://github.com/visionmedia/jade) we could set:479480 app.set('view engine', 'jade');481482Allowing us to render with:483484 res.render('index');485486vs:487488 res.render('index.jade');489490When _view engine_ is set, extensions are entirely optional, however we can still491mix and match template engines:492493 res.render('another-page.ejs');494495Express 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:496497 app.set('view options', {498 layout: false499 });500501Which can then be overridden within the `res.render()` call if need be:502503 res.render('myview.ejs', { layout: true });504505When 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:506507 res.render('page', { layout: 'mylayout' });508509Otherwise we must specify the extension:510511 res.render('page', { layout: 'mylayout.jade' });512513These paths may also be absolute:514515 res.render('page', { layout: __dirname + '/../../mylayout.jade' });516517A good example of this is specifying custom _ejs_ opening and closing tags:518519 app.set('view options', {520 open: '{{',521 close: '}}'522 });523524### View Partials525526The Express view system has built-in support for partials and collections, which are527sort of "mini" views representing a document fragment. For example rather than iterating528in a view to display comments, we would use a partial with collection support:529530 partial('comment.haml', { collection: comments });531532To make things even less verbose we can assume the extension as _.haml_ when omitted,533however if we wished we could use an ejs partial, within a haml view for example.534535 partial('comment', { collection: comments });536537And once again even further, when rendering a collection we can simply pass538an array, if no other options are desired:539540 partial('comment', comments);541542When using the partial collection support a few "magic" variables are provided543for free:544545 * _firstInCollection_ True if this is the first object546 * _indexInCollection_ Index of the object in the collection547 * _lastInCollection_ True if this is the last object548 * _collectionLength_ Length of the collection549550For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).more partial docsTj Holowaychukbefore adoptionf32279d
lines 551–552why, one step back551552NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead. For example do _not_ implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates.Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 553–561why, one step back553554### Template Engines555556Below are a few template engines commonly used with Express:557558 * [Jade](http://jade-lang.com) haml.js successor559 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templates560 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript561 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templatingAdded link to node-jqtpl template engineTj Holowaychukbefore adoptioncccda60
line 562why, one step back562 * [jQuery Templates](https://github.com/kof/node-jqtpl) for nodeAdded -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 563–688why, one step back563564### Session Support565566Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieDecoder_ middleware place above it, which will parse and populate cookie data to _req.cookies_.567568 app.use(express.cookieDecoder());569 app.use(express.session());570571By 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:572573 var RedisStore = require('connect-redis');574 app.use(express.cookieDecoder());575 app.use(express.session({ store: new RedisStore }));576577Now 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:578579 var RedisStore = require('connect-redis');580 app.use(express.bodyDecoder());581 app.use(express.cookieDecoder());582 app.use(express.session({ store: new RedisStore }));583584 app.post('/add-to-cart', function(req, res){585 // Perhaps we posted several items with a form586 // (use the bodyDecoder() middleware for this)587 var items = req.body.items;588 req.session.items = items;589 res.redirect('back');590 });591592 app.get('/add-to-cart', function(req, res){593 // When redirected back to GET /add-to-cart594 // we could check req.session.items && req.session.items.length595 // to print out a message596 if (req.session.items && req.session.items.length) {597 req.flash('info', 'You have %s items in your cart', req.session.items.length);598 }599 res.render('shopping-cart');600 });601602The _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/session.html) documentation.603604### Migration Guide605606 Pre-beta Express developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.607608### req.header(key[, defaultValue])609610Get the case-insensitive request header _key_, with optional _defaultValue_:611612 req.header('Host');613 req.header('host');614 req.header('Accept', '*/*');615616### req.accepts(type)617618Check if the _Accept_ header is present, and includes the given _type_.619620When the _Accept_ header is not present _true_ is returned. Otherwise621the given _type_ is matched by an exact match, and then subtypes. You622may pass the subtype such as "html" which is then converted internally623to "text/html" using the mime lookup table.624625 // Accept: text/html626 req.accepts('html');627 // => true628629 // Accept: text/*; application/json630 req.accepts('html');631 req.accepts('text/html');632 req.accepts('text/plain');633 req.accepts('application/json');634 // => true635636 req.accepts('image/png');637 req.accepts('png');638 // => false639640### req.is(type)641642Check if the incoming request contains the _Content-Type_643header field, and it contains the give mime _type_.644 645 // With Content-Type: text/html; charset=utf-8646 req.is('html');647 req.is('text/html');648 // => true649 650 // When Content-Type is application/json651 req.is('json');652 req.is('application/json');653 // => true654 655 req.is('html');656 // => false657 658Ad-hoc callbacks can also be registered with Express, to perform659assertions again the request, for example if we need an expressive660way to check if our incoming request is an image, we can register _"an image"_661callback:662 663 app.is('an image', function(req){664 return 0 == req.headers['content-type'].indexOf('image');665 });666 667Now within our route callbacks, we can use to to assert content types668such as _"image/jpeg"_, _"image/png"_, etc.669 670 app.post('/image/upload', function(req, res, next){671 if (req.is('an image')) {672 // do something673 } else {674 next();675 }676 });677678Keep in mind this method is _not_ limited to checking _Content-Type_, you679can perform any request assertion you wish.680681Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:682683 req.is('image/*');684685We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.686687 req.is('*/json');688Added default param support to req.param(name, default)Tj Holowaychukbefore adoption0af9126
line 689why, one step back689### req.param(name[, default])Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
line 690why, one step back690Added default param support to req.param(name, default)Tj Holowaychukbefore adoption0af9126
line 691why, one step back691Return the value of param _name_ when present or _default_.Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 692–803why, one step back692693 - Checks route placeholders (_req.params_), ex: /user/:id694 - Checks query string params (_req.query_), ex: ?id=12695 - Checks urlencoded body params (_req.body_), ex: id=12696697To utilize urlencoded request bodies, _req.body_698should be an object. This can be done by using699the _express.bodyDecoder_ middleware.700701### req.flash(type[, msg])702703Queue flash _msg_ of the given _type_.704705 req.flash('info', 'email sent');706 req.flash('error', 'email delivery failed');707 req.flash('info', 'email re-sent');708 // => 2709710 req.flash('info');711 // => ['email sent', 'email re-sent']712713 req.flash('info');714 // => []715716 req.flash();717 // => { error: ['email delivery failed'], info: [] }718719Flash notification message may also utilize formatters, by default only the %s string formatter is available:720721 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);722723### req.isXMLHttpRequest724725Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header726to see if it was issued by an _XMLHttpRequest_:727728 req.xhr729 req.isXMLHttpRequest730731### res.header(key[, val])732733Get or set the response header _key_.734735 res.header('Content-Length');736 // => undefined737738 res.header('Content-Length', 123);739 // => 123740741 res.header('Content-Length');742 // => 123743744### res.contentType(type)745746Sets the _Content-Type_ response header to the given _type_.747748 var filename = 'path/to/image.png';749 res.contentType(filename);750 // res.headers['Content-Type'] is now "image/png"751752### res.attachment([filename])753754Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.755756 res.attachment('path/to/my/image.png');757758### res.sendfile(path)759760Used by `res.download()` to transfer an arbitrary file. 761762 res.sendfile('path/to/my.file');763764This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has __not__ been streamed, _next(err)_ will be called on an exception.765766 res.sendfile(path, function(err, path){767 if (err) {768 // handle the error769 } else {770 console.log('transferred %s', path);771 }772 });773774### res.download(file[, filename])775776Transfer the given _file_ as an attachment with optional alternative _filename_.777778 res.download('path/to/image.png');779 res.download('path/to/image.png', 'foo.png');780781This is equivalent to:782783 res.attachment(file);784 res.sendfile(file);785786### res.send(body|status[, headers|status[, status]])787788The `res.send()` method is a high level response utility allowing you to pass789objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status790code based responses. The following are all valid uses:791792 res.send(); // 204793 res.send(new Buffer('wahoo'));794 res.send({ some: 'json' });795 res.send('<p>some html</p>');796 res.send('Sorry, cant find that', 404);797 res.send('text', { 'Content-Type': 'text/plain' }, 201);798 res.send(404);799800By default the _Content-Type_ response header is set, however if explicitly801assigned through `res.send()` or previously with `res.header()` or `res.contentType()`802it will not be set again.803Make note in docs that res.send() is a convenience method, and should only be called once (ATM)Tj Holowaychukbefore adoptionbed5157
lines 804–805why, one step back804Note that this method _end()_ the response, so you will want to use node's _res.writeHead()_ / _res.write()_ for multiple writes or streaming.805Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 806–860why, one step back806### res.redirect(url[, status])807808Redirect to the given _url_ with a default response _status_ of 302.809810 res.redirect('/', 301);811 res.redirect('/account');812 res.redirect('http://google.com');813 res.redirect('home');814 res.redirect('back');815816Express supports "redirect mapping", which by default provides _home_, and _back_.817The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes818the "home" setting and defaults to "/".819820### res.cookie(name, val[, options])821822Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.823824 // "Remember me" for 15 minutes 825 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });826827To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:828829 app.use(express.cookieDecoder());830 831 app.get('/', function(req, res){832 // use req.cookies.rememberme833 });834835### res.clearCookie(name)836837Clear cookie _name_ by setting "expires" far in the past.838839 res.clearCookie('rememberme');840841### res.render(view[, options[, fn]])842843Render _view_ with the given _options_ and optional callback _fn_.844When a callback function is given a response will _not_ be made845automatically, however otherwise a response of _200_ and _text/html_ is given.846847 Most engines accept one or more of the following options,848 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:849850 - _scope_ Template evaluation context (value of _this_)851 - _locals_ Object containing local variables852 - _debug_ Output debugging information853 - _status_ Response status code, defaults to 200854 - _headers_ Response headers object855856### res.partial(view[, options])857858Render _view_ partial with the given _options_. This method is always available859to the view as a local variable.860New partial() docsTj Holowaychukbefore adoption1c90332
lines 861–862why, one step back861- _object_ the object named by _as_ or derived from the view name862- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 863–893why, one step back863 * as: 'something' will add the _something_ local variable864 * as: this will use the collection value as the template context865 * as: global will merge the collection value's properties with _locals_866867- _collection_ Array of objects, the name is derived from the view name itself. 868 For example _video.html_ will have a object _video_ available to it.869870The following are equivalent, and the name of collection value when passed871to the partial will be _movie_ as derived from the name.872873 partial('theatre/movie.jade', { collection: movies });874 partial('theatre/movie.jade', movies);875 partial('movie.jade', { collection: movies });876 partial('movie.jade', movies);877 partial('movie', movies);878 // In view: movie.director879880To change the local from _movie_ to _video_ we can use the "as" option:881882 partial('movie', { collection: movies, as: 'video' });883 // In view: video.director884885Also we can make our movie the value of _this_ within our view so that instead886of _movie.director_ we could use _this.director_.887888 partial('movie', { collection: movies, as: this });889 // In view: this.director890891Another alternative is to "explode" the properties of the collection item into892pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:893New partial() docsTj Holowaychukbefore adoption1c90332
line 894why, one step back894 partial('movie', { collection: movies, as: global });Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
line 895why, one step back895 // In view: directorNew partial() docsTj Holowaychukbefore adoption1c90332
lines 896–914why, one step back896897This same logic applies to a single partial object usage:898899 partial('movie', { object: movie, as: this });900 // In view: this.director901902 partial('movie', { object: movie, as: global });903 // In view: director904905 partial('movie', { object: movie, as: 'video' });906 // In view: video.director907908 partial('movie', { object: movie });909 // In view: movie.director910911When 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:912913 partial('movie', movie);914 // => In view: movie.directorAdded -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
line 915why, one step back915Added res.local(name[, val]) docsTj Holowaychukbefore adoption5ac0c6d
lines 916–932why, one step back916### res.local(name[, val])917918Get 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()`.919920 app.all('/movie/:id', function(req, res, next){921 Movie.get(req.params.id, function(err, movie){922 // Assigns res.locals.movie = movie923 res.local('movie', movie);924 });925 });926 927 app.get('/movie/:id', function(req, res){928 // movie is already a local, however we929 // can pass more if we wish930 res.render('movie', { displayReviews: true });931 });932Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 933–941why, one step back933### app.set(name[, val])934935Apply an application level setting _name_ to _val_, or936get the value of _name_ when _val_ is not present:937938 app.set('views', __dirname + '/views');939 app.set('views');940 // => ...path...941Settings docsTj Holowaychukbefore adoptione562adc
lines 942–946why, one step back942Alternatively you may simply access the settings via _app.settings_:943944 app.settings.views945 // => ...path...946Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 947–954why, one step back947### app.enable(name)948949Enable the given setting _name_:950951 app.enable('some arbitrary setting');952 app.set('some arbitrary setting');953 // => true954Added docs for app.{disabled,enabled}()Tj Holowaychukbefore adoptiona9253a2
lines 955–957why, one step back955 app.enabled('some arbitrary setting');956 // => true957Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 958–963why, one step back958### app.disable(name)959960Disable the given setting _name_:961962 app.disable('some setting');963 app.set('some setting');Added docs for app.{disabled,enabled}()Tj Holowaychukbefore adoptiona9253a2
lines 964–966why, one step back964 // => false965 966 app.disabled('some setting');Added -s, --session[s] support to express(1)Tj Holowaychukbefore adoption1a6d245
lines 967–1108why, one step back967 // => false968969### app.configure(env|function[, function])970971Define a callback function for the given _env_ (or all environments) with callback _function_:972973 app.configure(function(){974 // executed for each env975 });976977 app.configure('development', function(){978 // executed for 'development' only979 });980981### app.redirect(name, val)982983For use with `res.redirect()` we can map redirects at the application level as shown below:984985 app.redirect('google', 'http://google.com');986987Now in a route we may call:988989 res.redirect('google');990991We may also map dynamic redirects:992993 app.redirect('comments', function(req, res){994 return '/post/' + req.params.id + '/comments';995 });996997So now we may do the following, and the redirect will dynamically adjust to998the context of the request. If we called this route with _GET /post/12_ our999redirect _Location_ would be _/post/12/comments_.10001001 app.get('/post/:id', function(req, res){1002 res.redirect('comments');1003 });10041005### app.error(function)10061007Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1008Note that we may set several error handlers by making several calls to this method, however the handler1009should call _next(err)_ if it does not wish to deal with the exception:10101011 app.error(function(err, req, res, next){1012 res.send(err.message, 500);1013 });10141015### app.helpers(obj)10161017Registers static view helpers.10181019 app.helpers({1020 name: function(first, last){ return first + ', ' + last },1021 firstName: 'tj',1022 lastName: 'holowaychuk'1023 });10241025Our view could now utilize the _firstName_ and _lastName_ variables,1026as well as the _name()_ function exposed.10271028 <%= name(firstName, lastName) %>10291030### app.dynamicHelpers(obj)10311032Registers dynamic view helpers. Dynamic view helpers1033are simply functions which accept _req_, _res_, and are1034evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1035becomes the local variable it is associated with.10361037 app.dynamicHelpers({1038 session: function(req, res){1039 return req.session;1040 }1041 });10421043All views would now have _session_ available so that session data can be accessed via _session.name_ etc:10441045 <%= session.name %>10461047### app.mounted(fn)10481049Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.10501051 var app = express.createServer(),1052 blog = express.createServer();1053 1054 blog.mounted(function(parent){1055 // parent is app1056 // "this" is blog1057 });1058 1059 app.use(blog);10601061### app.register(ext, exports)10621063Register the given template engine _exports_1064as _ext_. For example we may wish to map ".html"1065files to jade:10661067 app.register('.html', require('jade'));10681069This is also useful for libraries that may not1070match extensions correctly. For example my haml.js1071library is installed from npm as "hamljs" so instead1072of layout.hamljs, we can register the engine as ".haml":10731074 app.register('.haml', require('haml-js'));10751076For engines that do not comply with the Express1077specification, we can also wrap their api this way.10781079 app.register('.foo', {1080 render: function(str, options) {1081 // perhaps their api is1082 // return foo.toHTML(str, options);1083 }1084 });10851086### app.listen([port[, host]])10871088Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1089connections will be accepted via _INADDR_ANY_.10901091 app.listen();1092 app.listen(3000);1093 app.listen(3000, 'n.n.n.n');10941095The _port_ argument may also be a string representing the path to a unix domain socket:10961097 app.listen('/tmp/express.sock');10981099Then try it out:11001101 $ telnet /tmp/express.sock1102 GET / HTTP/1.111031104 HTTP/1.1 200 OK1105 Content-Type: text/plain1106 Content-Length: 111107 1108 Hello World