guide.md
This file
Path
docs/guide.md
1,000 lines · 32.6 KiB · Markdown
Last changed by
Added link to node-jqtpl template engineTj Holowaychukbefore adoptioncccda60
History of this fileTake it
The walk stopped after 200 commits: lines older than ae1c20f point at it.
Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 1–72why, 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(){45 app.use(express.methodOverride());46 app.use(express.bodyDecoder());47 app.use(app.router);48 app.use(express.staticProvider(__dirname + '/public'));49 });50 51 app.configure('development', function(){52 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));53 });54 55 app.configure('production', function(){56 app.use(express.errorHandler());57 });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:Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
line 74why, one step back74Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab
line 75why, one step back75 $ NODE_ENV=production node app.jsFixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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.78Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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()_.Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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()_.Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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.Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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 });Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 312–380why, one step back312313### 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.338339Note 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.343344 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:366367 app.use(express.errorHandler({ dumpExceptions: true }));368369Also during development we may want fancy html pages to show exceptions370that are passed or thrown, so we can set _showStack_ to true:371372 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));373374The _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.Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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' });433Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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);Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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 collectionFixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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-).468Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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 templatesFixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
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 link to node-jqtpl template engineTj Holowaychukbefore adoptioncccda60
line 477why, one step back477 * [jQuery Templates](https://github.com/kof/node-jqtpl) for nodeAdded session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe
lines 478–490why, one step back478479### Session Support480481Sessions 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_.482483 app.use(express.cookieDecoder());484 app.use(express.session());485486By 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:487488 var RedisStore = require('connect-redis');489 app.use(express.cookieDecoder());490 app.use(express.session({ store: new RedisStore }));Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
line 491why, one step back491More session docsTj Holowaychukbefore adoption4bc8a86
lines 492–494why, one step back492Now 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:493494 var RedisStore = require('connect-redis');Doc typoTj Holowaychukbefore adoption7da2743
line 495why, one step back495 app.use(express.bodyDecoder());More session docsTj Holowaychukbefore adoption4bc8a86
lines 496–518why, one step back496 app.use(express.cookieDecoder());497 app.use(express.session({ store: new RedisStore }));498499 app.post('/add-to-cart', function(req, res){500 // Perhaps we posted several items with a form501 // (use the bodyDecoder() middleware for this)502 var items = req.body.items;503 req.session.items = items;504 res.redirect('back');505 });506507 app.get('/add-to-cart', function(req, res){508 // When redirected back to GET /add-to-cart509 // we could check req.session.items && req.session.items.length510 // to print out a message511 if (req.session.items && req.session.items.length) {512 req.flash('info', 'You have %s items in your cart', req.session.items.length);513 }514 res.render('shopping-cart');515 });516517The _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.518Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc
lines 519–522why, one step back519### Migration Guide520521 Pre-beta Express developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.522Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 523–554why, one step back523### req.header(key[, defaultValue])524525Get the case-insensitive request header _key_, with optional _defaultValue_:526527 req.header('Host');528 req.header('host');529 req.header('Accept', '*/*');530531### req.accepts(type)532533Check if the _Accept_ header is present, and includes the given _type_.534535When the _Accept_ header is not present _true_ is returned. Otherwise536the given _type_ is matched by an exact match, and then subtypes. You537may pass the subtype such as "html" which is then converted internally538to "text/html" using the mime lookup table.539540 // Accept: text/html541 req.accepts('html');542 // => true543544 // Accept: text/*; application/json545 req.accepts('html');546 req.accepts('text/html');547 req.accepts('text/plain');548 req.accepts('application/json');549 // => true550551 req.accepts('image/png');552 req.accepts('png');553 // => false554Added req.is() docsTj Holowaychukbefore adoption806aefa
lines 555–592why, one step back555### req.is(type)556557Check if the incoming request contains the _Content-Type_558header field, and it contains the give mime _type_.559 560 // With Content-Type: text/html; charset=utf-8561 req.is('html');562 req.is('text/html');563 // => true564 565 // When Content-Type is application/json566 req.is('json');567 req.is('application/json');568 // => true569 570 req.is('html');571 // => false572 573Ad-hoc callbacks can also be registered with Express, to perform574assertions again the request, for example if we need an expressive575way to check if our incoming request is an image, we can register _"an image"_576callback:577 578 app.is('an image', function(req){579 return 0 == req.headers['content-type'].indexOf('image');580 });581 582Now within our route callbacks, we can use to to assert content types583such as _"image/jpeg"_, _"image/png"_, etc.584 585 app.post('/image/upload', function(req, res, next){586 if (req.is('an image')) {587 // do something588 } else {589 next();590 }591 });592More is() docsTj Holowaychukbefore adoption071ea95
lines 593–595why, one step back593Keep in mind this method is _not_ limited to checking _Content-Type_, you594can perform any request assertion you wish.595Merge branch 'is'Tj Holowaychukbefore adoption7a71380
lines 596–603why, one step back596Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:597598 req.is('image/*');599600We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.601602 req.is('*/json');603Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 604–633why, one step back604### req.param(name)605606Return the value of param _name_ when present.607608 - Checks route placeholders (_req.params_), ex: /user/:id609 - Checks query string params (_req.query_), ex: ?id=12610 - Checks urlencoded body params (_req.body_), ex: id=12611612To utilize urlencoded request bodies, _req.body_613should be an object. This can be done by using614the _express.bodyDecoder_ middleware.615616### req.flash(type[, msg])617618Queue flash _msg_ of the given _type_.619620 req.flash('info', 'email sent');621 req.flash('error', 'email delivery failed');622 req.flash('info', 'email re-sent');623 // => 2624625 req.flash('info');626 // => ['email sent', 'email re-sent']627628 req.flash('info');629 // => []630631 req.flash();632 // => { error: ['email delivery failed'], info: [] }633Added flash formatter docsTj Holowaychukbefore adoptionf16978d
lines 634–637why, one step back634Flash notification message may also utilize formatters, by default only the %s string formatter is available:635636 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);637Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 638–678why, one step back638### req.isXMLHttpRequest639640Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header641to see if it was issued by an _XMLHttpRequest_:642643 req.xhr644 req.isXMLHttpRequest645646### res.header(key[, val])647648Get or set the response header _key_.649650 res.header('Content-Length');651 // => undefined652653 res.header('Content-Length', 123);654 // => 123655656 res.header('Content-Length');657 // => 123658659### res.contentType(type)660661Sets the _Content-Type_ response header to the given _type_.662663 var filename = 'path/to/image.png';664 res.contentType(filename);665 // res.headers['Content-Type'] is now "image/png"666667### res.attachment([filename])668669Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.670671 res.attachment('path/to/my/image.png');672673### res.sendfile(path)674675Used by `res.download()` to transfer an arbitrary file. 676677 res.sendfile('path/to/my.file');678Merge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 679–689why, one step back679This 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.680681 res.sendfile(path, function(err, path){682 if (err) {683 // handle the error684 } else {685 console.log('transferred %s', path);686 }687 });688689When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 690–708why, one step back690691### res.download(file[, filename])692693Transfer the given _file_ as an attachment with optional alternative _filename_.694695 res.download('path/to/image.png');696 res.download('path/to/image.png', 'foo.png');697698This is equivalent to:699700 res.attachment(file);701 res.sendfile(file);702703### res.send(body|status[, headers|status[, status]])704705The `res.send()` method is a high level response utility allowing you to pass706objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status707code based responses. The following are all valid uses:708Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
line 709why, one step back709 res.send(); // 204Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 710–734why, one step back710 res.send(new Buffer('wahoo'));711 res.send({ some: 'json' });712 res.send('<p>some html</p>');713 res.send('Sorry, cant find that', 404);714 res.send('text', { 'Content-Type': 'text/plain' }, 201);715 res.send(404);716717By default the _Content-Type_ response header is set, however if explicitly718assigned through `res.send()` or previously with `res.header()` or `res.contentType()`719it will not be set again.720721### res.redirect(url[, status])722723Redirect to the given _url_ with a default response _status_ of 302.724725 res.redirect('/', 301);726 res.redirect('/account');727 res.redirect('http://google.com');728 res.redirect('home');729 res.redirect('back');730731Express supports "redirect mapping", which by default provides _home_, and _back_.732The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes733the "home" setting and defaults to "/".734Cookie docsTj Holowaychukbefore adoptiona89767c
lines 735–755why, one step back735### res.cookie(name, val[, options])736737Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.738739 // "Remember me" for 15 minutes 740 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });741742To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:743744 app.use(express.cookieDecoder());745 746 app.get('/', function(req, res){747 // use req.cookies.rememberme748 });749750### res.clearCookie(name)751752Clear cookie _name_ by setting "expires" far in the past.753754 res.clearCookie('rememberme');755Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 756–764why, one step back756### res.render(view[, options[, fn]])757758Render _view_ with the given _options_ and optional callback _fn_.759When a callback function is given a response will _not_ be made760automatically, however otherwise a response of _200_ and _text/html_ is given.761762 Most engines accept one or more of the following options,763 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:764Updated docsTj Holowaychukbefore adoptionfd4c88d
line 765why, one step back765 - _scope_ Template evaluation context (value of _this_)Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 766–767why, one step back766 - _locals_ Object containing local variables767 - _debug_ Output debugging informationMerge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
lines 768–769why, one step back768 - _status_ Response status code, defaults to 200769 - _headers_ Response headers objectFixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 770–775why, one step back770771### res.partial(view[, options])772773Render _view_ partial with the given _options_. This method is always available774to the view as a local variable.775New partial() docsTj Holowaychukbefore adoption1c90332
lines 776–777why, one step back776- _object_ the object named by _as_ or derived from the view name777- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 778–787why, one step back778 * as: 'something' will add the _something_ local variable779 * as: this will use the collection value as the template context780 * as: global will merge the collection value's properties with _locals_781782- _collection_ Array of objects, the name is derived from the view name itself. 783 For example _video.html_ will have a object _video_ available to it.784785The following are equivalent, and the name of collection value when passed786to the partial will be _movie_ as derived from the name.787More partial() docsTj Holowaychukbefore adoptione87d637
lines 788–789why, one step back788 partial('theatre/movie.jade', { collection: movies });789 partial('theatre/movie.jade', movies);Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 790–808why, one step back790 partial('movie.jade', { collection: movies });791 partial('movie.jade', movies);792 partial('movie', movies);793 // In view: movie.director794795To change the local from _movie_ to _video_ we can use the "as" option:796797 partial('movie', { collection: movies, as: 'video' });798 // In view: video.director799800Also we can make our movie the value of _this_ within our view so that instead801of _movie.director_ we could use _this.director_.802803 partial('movie', { collection: movies, as: this });804 // In view: this.director805806Another alternative is to "explode" the properties of the collection item into807pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:808New partial() docsTj Holowaychukbefore adoption1c90332
line 809why, one step back809 partial('movie', { collection: movies, as: global });Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
line 810why, one step back810 // In view: directorNew partial() docsTj Holowaychukbefore adoption1c90332
lines 811–829why, one step back811812This same logic applies to a single partial object usage:813814 partial('movie', { object: movie, as: this });815 // In view: this.director816817 partial('movie', { object: movie, as: global });818 // In view: director819820 partial('movie', { object: movie, as: 'video' });821 // In view: video.director822823 partial('movie', { object: movie });824 // In view: movie.director825826When 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:827828 partial('movie', movie);829 // => In view: movie.directorFixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 830–839why, one step back830831### app.set(name[, val])832833Apply an application level setting _name_ to _val_, or834get the value of _name_ when _val_ is not present:835836 app.set('views', __dirname + '/views');837 app.set('views');838 // => ...path...839Settings docsTj Holowaychukbefore adoptione562adc
lines 840–844why, one step back840Alternatively you may simply access the settings via _app.settings_:841842 app.settings.views843 // => ...path...844Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 845–951why, one step back845### app.enable(name)846847Enable the given setting _name_:848849 app.enable('some arbitrary setting');850 app.set('some arbitrary setting');851 // => true852853### app.disable(name)854855Disable the given setting _name_:856857 app.disable('some setting');858 app.set('some setting');859 // => false860861### app.configure(env|function[, function])862863Define a callback function for the given _env_ (or all environments) with callback _function_:864865 app.configure(function(){866 // executed for each env867 });868869 app.configure('development', function(){870 // executed for 'development' only871 });872873### app.redirect(name, val)874875For use with `res.redirect()` we can map redirects at the application level as shown below:876877 app.redirect('google', 'http://google.com');878879Now in a route we may call:880881 res.redirect('google');882883We may also map dynamic redirects:884885 app.redirect('comments', function(req, res){886 return '/post/' + req.params.id + '/comments';887 });888889So now we may do the following, and the redirect will dynamically adjust to890the context of the request. If we called this route with _GET /post/12_ our891redirect _Location_ would be _/post/12/comments_.892893 app.get('/post/:id', function(req, res){894 res.redirect('comments');895 });896897### app.error(function)898899Adds an error handler _function_ which will receive the exception as the first parameter as shown below.900Note that we may set several error handlers by making several calls to this method, however the handler901should call _next(err)_ if it does not wish to deal with the exception:902903 app.error(function(err, req, res, next){904 res.send(err.message, 500);905 });906907### app.helpers(obj)908909Registers static view helpers.910911 app.helpers({912 name: function(first, last){ return first + ', ' + last },913 firstName: 'tj',914 lastName: 'holowaychuk'915 });916917Our view could now utilize the _firstName_ and _lastName_ variables,918as well as the _name()_ function exposed.919920 <%= name(firstName, lastName) %>921922### app.dynamicHelpers(obj)923924Registers dynamic view helpers. Dynamic view helpers925are simply functions which accept _req_, _res_, and are926evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function927becomes the local variable it is associated with.928929 app.dynamicHelpers({930 session: function(req, res){931 return req.session;932 }933 });934935All views would now have _session_ available so that session data can be accessed via _session.name_ etc:936937 <%= session.name %>938939### app.mounted(fn)940941Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.942943 var app = express.createServer(),944 blog = express.createServer();945 946 blog.mounted(function(parent){947 // parent is app948 // "this" is blog949 });950 951 app.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 952–973why, one step back952953### app.register(ext, exports)954955Register the given template engine _exports_956as _ext_. For example we may wish to map ".html"957files to jade:958959 app.register('.html', require('jade'));960961This is also useful for libraries that may not962match extensions correctly. For example my haml.js963library is installed from npm as "hamljs" so instead964of layout.hamljs, we can register the engine as ".haml":965966 app.register('.haml', require('haml-js'));967968For engines that do not comply with the Express969specification, we can also wrap their api this way.970971 app.register('.foo', {972 render: function(str, options) {973 // perhaps their api isFix up app.register() docs. Closes #450Tj Holowaychukbefore adoption6ef6ba7
line 974why, one step back974 // return foo.toHTML(str, options);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 975–976why, one step back975 }976 });Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 977–1000why, one step back977978### app.listen([port[, host]])979980Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all981connections will be accepted via _INADDR_ANY_.982983 app.listen();984 app.listen(3000);985 app.listen(3000, 'n.n.n.n');986987The _port_ argument may also be a string representing the path to a unix domain socket:988989 app.listen('/tmp/express.sock');990991Then try it out:992993 $ telnet /tmp/express.sock994 GET / HTTP/1.1995996 HTTP/1.1 200 OK997 Content-Type: text/plain998 Content-Length: 11999 1000 Hello World