guide.md
This file
Path
docs/guide.md
999 lines · 32.6 KiB · Markdown
Last changed by
Settings docsTj Holowaychukbefore adoptione562adc
History of this fileTake it
The walk stopped after 200 commits: lines older than 706e32c point at it.
Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 1–44why, one step back12### Installation34curl:56 $ curl -# http://expressjs.com/install.sh | sh78npm:910 $ npm install express1112git clone, first update the submodules:1314 $ git submodule update --init15 $ make install16 $ make install-support1718### Creating An Application1920The _express.Server_ now inherits from _http.Server_, however21follows the same idiom by providing _express.createServer()_ as shown below. This means22that you can utilize Express server's transparently with other libraries.2324 var app = require('express').createServer();25 26 app.get('/', function(req, res){27 res.send('hello world');28 });29 30 app.listen(3000);3132### Configuration3334Express supports arbitrary environments, such as _production_ and _development_. Developers35can use the _configure()_ method to setup needs required by the current environment. When36_configure()_ is called without an environment name it will be run in _every_ environment 37prior to the environment specific callback.3839In the example below we only _dumpExceptions_, and respond with exception stack traces40in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.41Note the use of _app.router_, which can (optionally) be used to mount the application routes,42otherwise the first call to _app.{get,put,del,post}()_ will mount the routes.4344 app.configure(function(){Updated docsTj Holowaychukbefore adoption344218f
lines 45–46why, one step back45 app.use(express.methodOverride());46 app.use(express.bodyDecoder());Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 47why, one step back47 app.use(app.router);Updated docsTj Holowaychukbefore adoption344218f
line 48why, one step back48 app.use(express.staticProvider(__dirname + '/public'));Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 49–51why, one step back49 });50 51 app.configure('development', function(){Updated docsTj Holowaychukbefore adoption344218f
line 52why, one step back52 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 53–55why, one step back53 });54 55 app.configure('production', function(){Updated docsTj Holowaychukbefore adoption344218f
line 56why, one step back56 app.use(express.errorHandler());Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 57–72why, one step back57 });5859For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:6061 app.configure(function(){62 app.set('views', __dirname + '/views');63 app.set('views');64 // => "... views directory ..."65 66 app.enable('some feature');67 // same as app.set('some feature', true);68 69 app.disable('some feature');70 // same as app.set('some feature', false);71 });72Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab
line 73why, one step back73To alter the environment we can set the _NODE_ENV_ environment variable, for example:Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 74why, one step back74Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab
line 75why, one step back75 $ NODE_ENV=production node app.jsMerge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 76why, one step back76NODE_ENV=production docs, VERY IMPORTANT do this, or your app will be slow :pTj Holowaychukbefore adoptiond4868f2
lines 77–78why, one step back77This is _very_ important, as many caching mechanisms are _only enabled_ when in production.78Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 79–87why, one step back79### Settings8081Express supports the following settings out of the box:8283 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_84 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.85 * _views_ Root views directory defaulting to **CWD/views**86 * _view engine_ Default view engine name for views rendered without extensions87 * _view options_ An object specifying global view optionsMerge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 88–89why, one step back88 * _partials_ Root view partials directory defaulting to _views_/partials.89 * _stream threshold_ Bytesize indicating when a file should be streamed for _res.sendfile()_ using _fs.ReadStream()_ and _sys.pump()_.Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 90–159why, one step back9091### Routing9293Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.94For example we may want to render a user's account for the path _/user/12_, this95can be done by defining the route below. The values associated to the named placeholders 96are available as `req.params`.9798 app.get('/user/:id', function(req, res){99 res.send('user ' + req.params.id);100 });101102A route is simple a string which is compiled to a _RegExp_ internally. For example103when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:104105 \/user\/([^\/]+)\/?106107Regular expression literals may also be passed for complex uses. Since capture108groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.109110 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){111 res.send(req.params);112 });113114Curl requests against the previously defined route:115116 $ curl http://dev:3000/user117 [null,null]118 $ curl http://dev:3000/users119 [null,null]120 $ curl http://dev:3000/users/1121 ["1",null]122 $ curl http://dev:3000/users/1..15123 ["1","15"]124125Below are some route examples, and the associated paths that they126may consume:127128 "/user/:id"129 /user/12130131 "/users/:id?"132 /users/5133 /users134135 "/files/*"136 /files/jquery.js137 /files/javascripts/jquery.js138139 "/file/*.*"140 /files/jquery.js141 /files/javascripts/jquery.js142 143 "/user/:id/:operation?"144 /user/1145 /user/1/edit146 147 "/products.:format"148 /products.json149 /products.xml150151 "/products.:format?"152 /products.json153 /products.xml154 /products155156### Passing Route Control157158We may pass control to the next _matching_ route, by calling the _third_ argument,159the _next()_ function. When a match cannot be made, control is passed back to Connect,Added route-middleware exampleTj Holowaychukbefore adoption4983e96
line 160why, one step back160and 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()_.Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 161–173why, one step back161162 app.get('/users/:id?', function(req, res, next){163 var id = req.params.id;164 if (id) {165 // do something166 } else {167 next();168 }169 });170 171 app.get('/users', function(req, res){172 // do something else173 });Added route-middleware exampleTj Holowaychukbefore adoption4983e96
line 174why, one step back174Ordering docsTj Holowaychukbefore adoption296f127
lines 175–199why, one step back175### Middleware176177Middleware via [Connect](http://github.com/senchalabs/connect) can be178passed to _express.createServer()_ as you would with a regular Connect server. For example:179180 var express = require('express');181182 var app = express.createServer(183 express.logger(),184 express.bodyDecoder()185 );186187Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:188189 app.use(express.logger({ format: ':method :uri' }));190191Typically with connect middleware you would _require('connect')_ like so:192193 var connect = require('connect');194 app.use(connect.logger());195196This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:197198 app.use(express.logger());199Added route-middleware exampleTj Holowaychukbefore adoption4983e96
lines 200–202why, one step back200### Route Middleware201202Routes 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.Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 203why, one step back203Fixed docsTj Holowaychukbefore adoptioncef14ca
line 204why, one step back204Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
line 205why, one step back205Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 206–207why, one step back206 app.get('/user/:id', function(req, res, next){207 loadUser(req.params.id, function(err, user){Doc cleanupTj Holowaychukbefore adoptionb083aed
lines 208–209why, one step back208 if (err) return next(err);209 res.send('Viewing user ' + user.name);Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 210–211why, one step back210 });211 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 212–214why, one step back212213To 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. 214Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 215–228why, one step back215 function loadUser(req, res, next) {216 // You would fetch your user from the db217 var user = users[req.params.id];218 if (user) {219 req.user = user;220 next();221 } else {222 next(new Error('Failed to load user ' + req.params.id));223 }224 }225 226 app.get('/user/:id', loadUser, function(req, res){227 res.send('Viewing user ' + req.user.name);228 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 229–231why, one step back229230Multiple 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.231Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 232–233why, one step back232 function andRestrictToSelf(req, res, next) {233 req.authenticatedUser.id == req.user.idDoc cleanupTj Holowaychukbefore adoptionb083aed
lines 234–235why, one step back234 ? next()235 : next(new Error('Unauthorized'));Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 236–240why, one step back236 }237 238 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){239 res.send('Editing user ' + req.user.name);240 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
line 241why, one step back241Fixed docsTj Holowaychukbefore adoptioncef14ca
line 242why, one step back242Keeping 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.Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
line 243why, one step back243Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 244–246why, one step back244 function andRestrictTo(role) {245 return function(req, res, next) {246 req.authenticatedUser.role == roleDoc cleanupTj Holowaychukbefore adoptionb083aed
lines 247–248why, one step back247 ? next()248 : next(new Error('Unauthorized'));Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 249–255why, one step back249 }250 }251 252 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){253 res.send('Deleted user ' + req.user.name);254 });255Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 256–257why, one step back256Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.257Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 258–267why, one step back258 var a = [middleware1, middleware2]259 , b = [middleware3, middleware4]260 , all = [a, b];261 262 app.get('/foo', a, function(){});263 app.get('/bar', a, function(){});264 265 app.get('/', a, middleware3, middleware4, function(){});266 app.get('/', a, b, function(){});267 app.get('/', all, function(){});Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 268–270why, one step back268269For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.270HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 271–276why, one step back271### HTTP Methods272273We 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.274275 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.276 Doc typoTj Holowaychukbefore adoptionc9268f2
lines 277–281why, one step back277 <form method="post" action="/">278 <input type="text" name="user[name]" />279 <input type="text" name="user[email]" />280 <input type="submit" value="Submit" />281 </form>HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 282–311why, one step back282283By 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:284285 app.use(express.bodyDecoder());286287Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.288289 app.post('/', function(req, res){290 console.log(req.body.user);291 res.redirect('back');292 });293294When 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.295296 app.use(express.bodyDecoder());297 app.use(express.methodOverride());298299The 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:300301 <form method="post" action="/">302 <input type="hidden" name="_method" value="put" />303 <input type="text" name="user[name]" />304 <input type="text" name="user[email]" />305 <input type="submit" value="Submit" /> 306 </form>307308 app.put('/', function(){309 console.log(req.body.user);310 res.redirect('back');311 });Updated docsTj Holowaychukbefore adoption344218f
line 312why, one step back312Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 313–338why, one step back313### Error Handling314315Express provides the _app.error()_ method which receives exceptions thrown within a route,316or passed to _next(err)_. Below is an example which serves different pages based on our317ad-hoc _NotFound_ exception:318319 function NotFound(msg){320 this.name = 'NotFound';321 Error.call(this, msg);322 Error.captureStackTrace(this, arguments.callee);323 }324325 sys.inherits(NotFound, Error);326327 app.get('/404', function(req, res){328 throw new NotFound;329 });330331 app.get('/500', function(req, res){332 throw new Error('keyboard cat!');333 });334335We can call _app.error()_ several times as shown below.336Here we check for an instanceof _NotFound_ and show the337404 page, or we pass on to the next error handler.338Merge branch 'fix-error'Tj Holowaychukbefore adoption498115d
lines 339–343why, one step back339Note that these handlers can be defined anywhere, as they340will be placed below the route handlers on _listen()_. This 341allows for definition within _configure()_ blocks so we can342handle exceptions in different ways based on the environment.343Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 344–366why, one step back344 app.error(function(err, req, res, next){345 if (err instanceof NotFound) {346 res.render('404.jade');347 } else {348 next(err);349 }350 });351352Here we assume all errors as 500 for the simplicity of353this demo, however you can choose whatever you like354355 app.error(function(err, req, res){356 res.render('500.jade', {357 locals: {358 error: err359 } 360 });361 });362363Our apps could also utilize the Connect _errorHandler_ middleware364to report on exceptions. For example if we wish to output exceptions 365in "development" mode to _stderr_ we can use:366Updated docsTj Holowaychukbefore adoption344218f
line 367why, one step back367 app.use(express.errorHandler({ dumpExceptions: true }));Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 368–371why, one step back368369Also during development we may want fancy html pages to show exceptions370that are passed or thrown, so we can set _showStack_ to true:371Updated docsTj Holowaychukbefore adoption344218f
line 372why, one step back372 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 373–380why, one step back373374The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_375is present, which is useful for developing apps that rely heavily on client-side JavaScript.376377### View Rendering378379View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name380of the module that will be required. For example the view _layout.ejs_ willAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 381–382why, one step back381tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 382_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 383–421why, one step back383384Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,385and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 386the _body_ local variable in _layout.haml_.387388 app.get('/', function(req, res){389 res.render('index.haml', {390 locals: { title: 'My Site' }391 });392 });393394The new _view engine_ setting allows us to specify our default template engine,395so for example when using [Jade](http://github.com/visionmedia/jade) we could set:396397 app.set('view engine', 'jade');398399Allowing us to render with:400401 res.render('index');402403vs:404405 res.render('index.jade');406407When _view engine_ is set, extensions are entirely optional, however we can still408mix and match template engines:409410 res.render('another-page.ejs');411412Express 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:413414 app.set('view options', {415 layout: false416 });417418Which can then be overridden within the `res.render()` call if need be:419420 res.render('myview.ejs', { layout: true });421Docs for layout optionTj Holowaychukbefore adoption0a96621
lines 422–433why, one step back422When 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:423424 res.render('page', { layout: 'mylayout' });425426Otherwise we must specify the extension:427428 res.render('page', { layout: 'mylayout.jade' });429430These paths may also be absolute:431432 res.render('page', { layout: __dirname + '/../../mylayout.jade' });433Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 434–456why, one step back434A good example of this is specifying custom _ejs_ opening and closing tags:435436 app.set('view options', {437 open: '{{',438 close: '}}'439 });440441### View Partials442443The Express view system has built-in support for partials and collections, which are444sort of "mini" views representing a document fragment. For example rather than iterating445in a view to display comments, we would use a partial with collection support:446447 partial('comment.haml', { collection: comments });448449To make things even less verbose we can assume the extension as _.haml_ when omitted,450however if we wished we could use an ejs partial, within a haml view for example.451452 partial('comment', { collection: comments });453454And once again even further, when rendering a collection we can simply pass455an array, if no other options are desired:456More partial() docsTj Holowaychukbefore adoptione87d637
line 457why, one step back457 partial('comment', comments);Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 458–463why, one step back458459When using the partial collection support a few "magic" variables are provided460for free:461462 * _firstInCollection_ True if this is the first object463 * _indexInCollection_ Index of the object in the collectionDoc typosTj Holowaychukbefore adoption02b4ec0
line 464why, one step back464 * _lastInCollection_ True if this is the last objectMore partial() docsTj Holowaychukbefore adoptione87d637
line 465why, one step back465 * _collectionLength_ Length of the collectionMerge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 466why, one step back466More partial() docsTj Holowaychukbefore adoptione87d637
lines 467–468why, one step back467For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).468Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 469–472why, one step back469### Template Engines470471Below are a few template engines commonly used with Express:472Doc typosTj Holowaychukbefore adoption02b4ec0
lines 473–474why, one step back473 * [Jade](http://jade-lang.com) haml.js successor474 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templatesMerge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 475why, one step back475 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScriptAdded CoffeeKup as a suggested template engine (let me know of others please :) )Tj Holowaychukbefore adoption687e435
line 476why, one step back476 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templatingAdded session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe
lines 477–489why, one step back477478### Session Support479480Sessions 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_.481482 app.use(express.cookieDecoder());483 app.use(express.session());484485By 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:486487 var RedisStore = require('connect-redis');488 app.use(express.cookieDecoder());489 app.use(express.session({ store: new RedisStore }));Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 490why, one step back490More session docsTj Holowaychukbefore adoption4bc8a86
lines 491–493why, one step back491Now 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:492493 var RedisStore = require('connect-redis');Doc typoTj Holowaychukbefore adoption7da2743
line 494why, one step back494 app.use(express.bodyDecoder());More session docsTj Holowaychukbefore adoption4bc8a86
lines 495–517why, one step back495 app.use(express.cookieDecoder());496 app.use(express.session({ store: new RedisStore }));497498 app.post('/add-to-cart', function(req, res){499 // Perhaps we posted several items with a form500 // (use the bodyDecoder() middleware for this)501 var items = req.body.items;502 req.session.items = items;503 res.redirect('back');504 });505506 app.get('/add-to-cart', function(req, res){507 // When redirected back to GET /add-to-cart508 // we could check req.session.items && req.session.items.length509 // to print out a message510 if (req.session.items && req.session.items.length) {511 req.flash('info', 'You have %s items in your cart', req.session.items.length);512 }513 res.render('shopping-cart');514 });515516The _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.517Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc
lines 518–521why, one step back518### Migration Guide519520 Pre-beta Express developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.521Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 522–553why, one step back522### req.header(key[, defaultValue])523524Get the case-insensitive request header _key_, with optional _defaultValue_:525526 req.header('Host');527 req.header('host');528 req.header('Accept', '*/*');529530### req.accepts(type)531532Check if the _Accept_ header is present, and includes the given _type_.533534When the _Accept_ header is not present _true_ is returned. Otherwise535the given _type_ is matched by an exact match, and then subtypes. You536may pass the subtype such as "html" which is then converted internally537to "text/html" using the mime lookup table.538539 // Accept: text/html540 req.accepts('html');541 // => true542543 // Accept: text/*; application/json544 req.accepts('html');545 req.accepts('text/html');546 req.accepts('text/plain');547 req.accepts('application/json');548 // => true549550 req.accepts('image/png');551 req.accepts('png');552 // => false553Added req.is() docsTj Holowaychukbefore adoption806aefa
lines 554–591why, one step back554### req.is(type)555556Check if the incoming request contains the _Content-Type_557header field, and it contains the give mime _type_.558 559 // With Content-Type: text/html; charset=utf-8560 req.is('html');561 req.is('text/html');562 // => true563 564 // When Content-Type is application/json565 req.is('json');566 req.is('application/json');567 // => true568 569 req.is('html');570 // => false571 572Ad-hoc callbacks can also be registered with Express, to perform573assertions again the request, for example if we need an expressive574way to check if our incoming request is an image, we can register _"an image"_575callback:576 577 app.is('an image', function(req){578 return 0 == req.headers['content-type'].indexOf('image');579 });580 581Now within our route callbacks, we can use to to assert content types582such as _"image/jpeg"_, _"image/png"_, etc.583 584 app.post('/image/upload', function(req, res, next){585 if (req.is('an image')) {586 // do something587 } else {588 next();589 }590 });591More is() docsTj Holowaychukbefore adoption071ea95
lines 592–594why, one step back592Keep in mind this method is _not_ limited to checking _Content-Type_, you593can perform any request assertion you wish.594Merge branch 'is'Tj Holowaychukbefore adoption7a71380
lines 595–602why, one step back595Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:596597 req.is('image/*');598599We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.600601 req.is('*/json');602Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 603–612why, one step back603### req.param(name)604605Return the value of param _name_ when present.606607 - Checks route placeholders (_req.params_), ex: /user/:id608 - Checks query string params (_req.query_), ex: ?id=12609 - Checks urlencoded body params (_req.body_), ex: id=12610611To utilize urlencoded request bodies, _req.body_612should be an object. This can be done by usingUpdated docsTj Holowaychukbefore adoption344218f
line 613why, one step back613the _express.bodyDecoder_ middleware.Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 614–632why, one step back614615### req.flash(type[, msg])616617Queue flash _msg_ of the given _type_.618619 req.flash('info', 'email sent');620 req.flash('error', 'email delivery failed');621 req.flash('info', 'email re-sent');622 // => 2623624 req.flash('info');625 // => ['email sent', 'email re-sent']626627 req.flash('info');628 // => []629630 req.flash();631 // => { error: ['email delivery failed'], info: [] }632Added flash formatter docsTj Holowaychukbefore adoptionf16978d
lines 633–636why, one step back633Flash notification message may also utilize formatters, by default only the %s string formatter is available:634635 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);636Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 637–677why, one step back637### req.isXMLHttpRequest638639Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header640to see if it was issued by an _XMLHttpRequest_:641642 req.xhr643 req.isXMLHttpRequest644645### res.header(key[, val])646647Get or set the response header _key_.648649 res.header('Content-Length');650 // => undefined651652 res.header('Content-Length', 123);653 // => 123654655 res.header('Content-Length');656 // => 123657658### res.contentType(type)659660Sets the _Content-Type_ response header to the given _type_.661662 var filename = 'path/to/image.png';663 res.contentType(filename);664 // res.headers['Content-Type'] is now "image/png"665666### res.attachment([filename])667668Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.669670 res.attachment('path/to/my/image.png');671672### res.sendfile(path)673674Used by `res.download()` to transfer an arbitrary file. 675676 res.sendfile('path/to/my.file');677Merge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 678–688why, one step back678This 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.679680 res.sendfile(path, function(err, path){681 if (err) {682 // handle the error683 } else {684 console.log('transferred %s', path);685 }686 });687688When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 689–707why, one step back689690### res.download(file[, filename])691692Transfer the given _file_ as an attachment with optional alternative _filename_.693694 res.download('path/to/image.png');695 res.download('path/to/image.png', 'foo.png');696697This is equivalent to:698699 res.attachment(file);700 res.sendfile(file);701702### res.send(body|status[, headers|status[, status]])703704The `res.send()` method is a high level response utility allowing you to pass705objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status706code based responses. The following are all valid uses:707Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
line 708why, one step back708 res.send(); // 204Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 709–733why, one step back709 res.send(new Buffer('wahoo'));710 res.send({ some: 'json' });711 res.send('<p>some html</p>');712 res.send('Sorry, cant find that', 404);713 res.send('text', { 'Content-Type': 'text/plain' }, 201);714 res.send(404);715716By default the _Content-Type_ response header is set, however if explicitly717assigned through `res.send()` or previously with `res.header()` or `res.contentType()`718it will not be set again.719720### res.redirect(url[, status])721722Redirect to the given _url_ with a default response _status_ of 302.723724 res.redirect('/', 301);725 res.redirect('/account');726 res.redirect('http://google.com');727 res.redirect('home');728 res.redirect('back');729730Express supports "redirect mapping", which by default provides _home_, and _back_.731The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes732the "home" setting and defaults to "/".733Cookie docsTj Holowaychukbefore adoptiona89767c
lines 734–754why, one step back734### res.cookie(name, val[, options])735736Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.737738 // "Remember me" for 15 minutes 739 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });740741To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:742743 app.use(express.cookieDecoder());744 745 app.get('/', function(req, res){746 // use req.cookies.rememberme747 });748749### res.clearCookie(name)750751Clear cookie _name_ by setting "expires" far in the past.752753 res.clearCookie('rememberme');754Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 755–763why, one step back755### res.render(view[, options[, fn]])756757Render _view_ with the given _options_ and optional callback _fn_.758When a callback function is given a response will _not_ be made759automatically, however otherwise a response of _200_ and _text/html_ is given.760761 Most engines accept one or more of the following options,762 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:763Updated docsTj Holowaychukbefore adoptionfd4c88d
line 764why, one step back764 - _scope_ Template evaluation context (value of _this_)Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 765–766why, one step back765 - _locals_ Object containing local variables766 - _debug_ Output debugging informationMerge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
lines 767–768why, one step back767 - _status_ Response status code, defaults to 200768 - _headers_ Response headers objectMerge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 769–774why, one step back769770### res.partial(view[, options])771772Render _view_ partial with the given _options_. This method is always available773to the view as a local variable.774New partial() docsTj Holowaychukbefore adoption1c90332
lines 775–776why, one step back775- _object_ the object named by _as_ or derived from the view name776- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 777–786why, one step back777 * as: 'something' will add the _something_ local variable778 * as: this will use the collection value as the template context779 * as: global will merge the collection value's properties with _locals_780781- _collection_ Array of objects, the name is derived from the view name itself. 782 For example _video.html_ will have a object _video_ available to it.783784The following are equivalent, and the name of collection value when passed785to the partial will be _movie_ as derived from the name.786More partial() docsTj Holowaychukbefore adoptione87d637
lines 787–788why, one step back787 partial('theatre/movie.jade', { collection: movies });788 partial('theatre/movie.jade', movies);Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 789–807why, one step back789 partial('movie.jade', { collection: movies });790 partial('movie.jade', movies);791 partial('movie', movies);792 // In view: movie.director793794To change the local from _movie_ to _video_ we can use the "as" option:795796 partial('movie', { collection: movies, as: 'video' });797 // In view: video.director798799Also we can make our movie the value of _this_ within our view so that instead800of _movie.director_ we could use _this.director_.801802 partial('movie', { collection: movies, as: this });803 // In view: this.director804805Another alternative is to "explode" the properties of the collection item into806pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:807New partial() docsTj Holowaychukbefore adoption1c90332
line 808why, one step back808 partial('movie', { collection: movies, as: global });Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 809why, one step back809 // In view: directorNew partial() docsTj Holowaychukbefore adoption1c90332
lines 810–828why, one step back810811This same logic applies to a single partial object usage:812813 partial('movie', { object: movie, as: this });814 // In view: this.director815816 partial('movie', { object: movie, as: global });817 // In view: director818819 partial('movie', { object: movie, as: 'video' });820 // In view: video.director821822 partial('movie', { object: movie });823 // In view: movie.director824825When 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:826827 partial('movie', movie);828 // => In view: movie.directorMerge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 829–838why, one step back829830### app.set(name[, val])831832Apply an application level setting _name_ to _val_, or833get the value of _name_ when _val_ is not present:834835 app.set('views', __dirname + '/views');836 app.set('views');837 // => ...path...838Settings docsTj Holowaychukbefore adoptione562adc
lines 839–843why, one step back839Alternatively you may simply access the settings via _app.settings_:840841 app.settings.views842 // => ...path...843Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 844–950why, one step back844### app.enable(name)845846Enable the given setting _name_:847848 app.enable('some arbitrary setting');849 app.set('some arbitrary setting');850 // => true851852### app.disable(name)853854Disable the given setting _name_:855856 app.disable('some setting');857 app.set('some setting');858 // => false859860### app.configure(env|function[, function])861862Define a callback function for the given _env_ (or all environments) with callback _function_:863864 app.configure(function(){865 // executed for each env866 });867868 app.configure('development', function(){869 // executed for 'development' only870 });871872### app.redirect(name, val)873874For use with `res.redirect()` we can map redirects at the application level as shown below:875876 app.redirect('google', 'http://google.com');877878Now in a route we may call:879880 res.redirect('google');881882We may also map dynamic redirects:883884 app.redirect('comments', function(req, res){885 return '/post/' + req.params.id + '/comments';886 });887888So now we may do the following, and the redirect will dynamically adjust to889the context of the request. If we called this route with _GET /post/12_ our890redirect _Location_ would be _/post/12/comments_.891892 app.get('/post/:id', function(req, res){893 res.redirect('comments');894 });895896### app.error(function)897898Adds an error handler _function_ which will receive the exception as the first parameter as shown below.899Note that we may set several error handlers by making several calls to this method, however the handler900should call _next(err)_ if it does not wish to deal with the exception:901902 app.error(function(err, req, res, next){903 res.send(err.message, 500);904 });905906### app.helpers(obj)907908Registers static view helpers.909910 app.helpers({911 name: function(first, last){ return first + ', ' + last },912 firstName: 'tj',913 lastName: 'holowaychuk'914 });915916Our view could now utilize the _firstName_ and _lastName_ variables,917as well as the _name()_ function exposed.918919 <%= name(firstName, lastName) %>920921### app.dynamicHelpers(obj)922923Registers dynamic view helpers. Dynamic view helpers924are simply functions which accept _req_, _res_, and are925evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function926becomes the local variable it is associated with.927928 app.dynamicHelpers({929 session: function(req, res){930 return req.session;931 }932 });933934All views would now have _session_ available so that session data can be accessed via _session.name_ etc:935936 <%= session.name %>937938### app.mounted(fn)939940Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.941942 var app = express.createServer(),943 blog = express.createServer();944 945 blog.mounted(function(parent){946 // parent is app947 // "this" is blog948 });949 950 app.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 951–972why, one step back951952### app.register(ext, exports)953954Register the given template engine _exports_955as _ext_. For example we may wish to map ".html"956files to jade:957958 app.register('.html', require('jade'));959960This is also useful for libraries that may not961match extensions correctly. For example my haml.js962library is installed from npm as "hamljs" so instead963of layout.hamljs, we can register the engine as ".haml":964965 app.register('.haml', require('haml-js'));966967For engines that do not comply with the Express968specification, we can also wrap their api this way.969970 app.register('.foo', {971 render: function(str, options) {972 // perhaps their api isFix up app.register() docs. Closes #450Tj Holowaychukbefore adoption6ef6ba7
line 973why, one step back973 // return foo.toHTML(str, options);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 974–975why, one step back974 }975 });Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 976–999why, one step back976977### app.listen([port[, host]])978979Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all980connections will be accepted via _INADDR_ANY_.981982 app.listen();983 app.listen(3000);984 app.listen(3000, 'n.n.n.n');985986The _port_ argument may also be a string representing the path to a unix domain socket:987988 app.listen('/tmp/express.sock');989990Then try it out:991992 $ telnet /tmp/express.sock993 GET / HTTP/1.1994995 HTTP/1.1 200 OK996 Content-Type: text/plain997 Content-Length: 11998 999 Hello World