guide.md
This file
Path
docs/guide.md
1,047 lines · 34.0 KiB · Markdown
Last changed by
DocsTj Holowaychukbefore adoption5234368
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–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(){DocsTj Holowaychukbefore adoption5234368
lines 45–49why, one step back45 app.use(express.methodOverride());46 app.use(express.bodyDecoder());47 app.use(app.router);48 app.use(express.staticProvider(__dirname + '/public'));49 });Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
line 50why, one step back50 DocsTj Holowaychukbefore adoption5234368
lines 51–53why, one step back51 app.configure('development', function(){52 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));53 });Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
line 54why, one step back54 DocsTj Holowaychukbefore adoption5234368
lines 55–57why, one step back55 app.configure('production', function(){56 app.use(express.errorHandler());57 });Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 58–72why, one step back5859For 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–98why, 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){DocsTj Holowaychukbefore adoption5234368
lines 99–100why, one step back99 res.send('user ' + req.params.id);100 });Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 101–155why, one step back101102A 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 /products155DocsTj Holowaychukbefore adoption5234368
lines 156–168why, one step back156For 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_:157158 var express = require('express')159 , app = express.createServer();160161 app.use(express.bodyDecoder());162163 app.post('/', function(req, res){164 res.send(req.body);165 });166167 app.listen(3000);168Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 169–172why, 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,Added route-middleware exampleTj Holowaychukbefore adoption4983e96
line 173why, one step back173and 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 174–186why, one step back174175 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 route-middleware exampleTj Holowaychukbefore adoption4983e96
line 221why, one step back221Ordering docsTj Holowaychukbefore adoption296f127
lines 222–246why, one step back222### 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());246Added route-middleware exampleTj Holowaychukbefore adoption4983e96
lines 247–249why, one step back247### 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.Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
line 250why, one step back250Fixed docsTj Holowaychukbefore adoptioncef14ca
line 251why, one step back251Typically 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 252why, one step back252Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 253–254why, one step back253 app.get('/user/:id', function(req, res, next){254 loadUser(req.params.id, function(err, user){Doc cleanupTj Holowaychukbefore adoptionb083aed
lines 255–256why, one step back255 if (err) return next(err);256 res.send('Viewing user ' + user.name);Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 257–258why, one step back257 });258 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 259–261why, one step back259260To 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. 261Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 262–275why, one step back262 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 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 276–278why, one step back276277Multiple 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.278Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 279–280why, one step back279 function andRestrictToSelf(req, res, next) {280 req.authenticatedUser.id == req.user.idDoc cleanupTj Holowaychukbefore adoptionb083aed
lines 281–282why, one step back281 ? next()282 : next(new Error('Unauthorized'));Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 283–287why, one step back283 }284 285 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){286 res.send('Editing user ' + req.user.name);287 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
line 288why, one step back288Fixed docsTj Holowaychukbefore adoptioncef14ca
line 289why, one step back289Keeping 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 290why, one step back290Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 291–293why, one step back291 function andRestrictTo(role) {292 return function(req, res, next) {293 req.authenticatedUser.role == roleDoc cleanupTj Holowaychukbefore adoptionb083aed
lines 294–295why, one step back294 ? next()295 : next(new Error('Unauthorized'));Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 296–302why, one step back296 }297 }298 299 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){300 res.send('Deleted user ' + req.user.name);301 });302Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 303–304why, one step back303Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.304Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 305–314why, one step back305 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(){});Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 315–317why, one step back315316For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.317HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 318–323why, one step back318### 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 Doc typoTj Holowaychukbefore adoptionc9268f2
lines 324–328why, one step back324 <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>HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 329–358why, one step back329330By 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 });Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 359–427why, one step back359360### 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.423424### View Rendering425426View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name427of the module that will be required. For example the view _layout.ejs_ willAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 428–429why, one step back428tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 429_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 430–468why, one step back430431Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,432and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 433the _body_ local variable in _layout.haml_.434435 app.get('/', function(req, res){436 res.render('index.haml', {437 locals: { title: 'My Site' }438 });439 });440441The new _view engine_ setting allows us to specify our default template engine,442so for example when using [Jade](http://github.com/visionmedia/jade) we could set:443444 app.set('view engine', 'jade');445446Allowing us to render with:447448 res.render('index');449450vs:451452 res.render('index.jade');453454When _view engine_ is set, extensions are entirely optional, however we can still455mix and match template engines:456457 res.render('another-page.ejs');458459Express 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:460461 app.set('view options', {462 layout: false463 });464465Which can then be overridden within the `res.render()` call if need be:466467 res.render('myview.ejs', { layout: true });468Docs for layout optionTj Holowaychukbefore adoption0a96621
lines 469–480why, one step back469When 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:470471 res.render('page', { layout: 'mylayout' });472473Otherwise we must specify the extension:474475 res.render('page', { layout: 'mylayout.jade' });476477These paths may also be absolute:478479 res.render('page', { layout: __dirname + '/../../mylayout.jade' });480Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 481–503why, one step back481A good example of this is specifying custom _ejs_ opening and closing tags:482483 app.set('view options', {484 open: '{{',485 close: '}}'486 });487488### View Partials489490The Express view system has built-in support for partials and collections, which are491sort of "mini" views representing a document fragment. For example rather than iterating492in a view to display comments, we would use a partial with collection support:493494 partial('comment.haml', { collection: comments });495496To make things even less verbose we can assume the extension as _.haml_ when omitted,497however if we wished we could use an ejs partial, within a haml view for example.498499 partial('comment', { collection: comments });500501And once again even further, when rendering a collection we can simply pass502an array, if no other options are desired:503More partial() docsTj Holowaychukbefore adoptione87d637
line 504why, one step back504 partial('comment', comments);Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 505–510why, one step back505506When using the partial collection support a few "magic" variables are provided507for free:508509 * _firstInCollection_ True if this is the first object510 * _indexInCollection_ Index of the object in the collectionDoc typosTj Holowaychukbefore adoption02b4ec0
line 511why, one step back511 * _lastInCollection_ True if this is the last objectMore partial() docsTj Holowaychukbefore adoptione87d637
line 512why, one step back512 * _collectionLength_ Length of the collectionFixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
line 513why, one step back513More partial() docsTj Holowaychukbefore adoptione87d637
lines 514–515why, one step back514For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).515Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 516–519why, one step back516### Template Engines517518Below are a few template engines commonly used with Express:519Doc typosTj Holowaychukbefore adoption02b4ec0
lines 520–521why, one step back520 * [Jade](http://jade-lang.com) haml.js successor521 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templatesFixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
line 522why, one step back522 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScriptAdded CoffeeKup as a suggested template engine (let me know of others please :) )Tj Holowaychukbefore adoption687e435
line 523why, one step back523 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templatingAdded link to node-jqtpl template engineTj Holowaychukbefore adoptioncccda60
line 524why, one step back524 * [jQuery Templates](https://github.com/kof/node-jqtpl) for nodeAdded session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe
lines 525–537why, one step back525526### Session Support527528Sessions 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_.529530 app.use(express.cookieDecoder());531 app.use(express.session());532533By 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:534535 var RedisStore = require('connect-redis');536 app.use(express.cookieDecoder());537 app.use(express.session({ store: new RedisStore }));Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
line 538why, one step back538More session docsTj Holowaychukbefore adoption4bc8a86
lines 539–541why, one step back539Now 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:540541 var RedisStore = require('connect-redis');Doc typoTj Holowaychukbefore adoption7da2743
line 542why, one step back542 app.use(express.bodyDecoder());More session docsTj Holowaychukbefore adoption4bc8a86
lines 543–565why, one step back543 app.use(express.cookieDecoder());544 app.use(express.session({ store: new RedisStore }));545546 app.post('/add-to-cart', function(req, res){547 // Perhaps we posted several items with a form548 // (use the bodyDecoder() middleware for this)549 var items = req.body.items;550 req.session.items = items;551 res.redirect('back');552 });553554 app.get('/add-to-cart', function(req, res){555 // When redirected back to GET /add-to-cart556 // we could check req.session.items && req.session.items.length557 // to print out a message558 if (req.session.items && req.session.items.length) {559 req.flash('info', 'You have %s items in your cart', req.session.items.length);560 }561 res.render('shopping-cart');562 });563564The _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.565Merge branch 'apps'Tj Holowaychukbefore adoption4e67efc
lines 566–569why, one step back566### Migration Guide567568 Pre-beta Express developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.569Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 570–601why, one step back570### req.header(key[, defaultValue])571572Get the case-insensitive request header _key_, with optional _defaultValue_:573574 req.header('Host');575 req.header('host');576 req.header('Accept', '*/*');577578### req.accepts(type)579580Check if the _Accept_ header is present, and includes the given _type_.581582When the _Accept_ header is not present _true_ is returned. Otherwise583the given _type_ is matched by an exact match, and then subtypes. You584may pass the subtype such as "html" which is then converted internally585to "text/html" using the mime lookup table.586587 // Accept: text/html588 req.accepts('html');589 // => true590591 // Accept: text/*; application/json592 req.accepts('html');593 req.accepts('text/html');594 req.accepts('text/plain');595 req.accepts('application/json');596 // => true597598 req.accepts('image/png');599 req.accepts('png');600 // => false601Added req.is() docsTj Holowaychukbefore adoption806aefa
lines 602–639why, one step back602### req.is(type)603604Check if the incoming request contains the _Content-Type_605header field, and it contains the give mime _type_.606 607 // With Content-Type: text/html; charset=utf-8608 req.is('html');609 req.is('text/html');610 // => true611 612 // When Content-Type is application/json613 req.is('json');614 req.is('application/json');615 // => true616 617 req.is('html');618 // => false619 620Ad-hoc callbacks can also be registered with Express, to perform621assertions again the request, for example if we need an expressive622way to check if our incoming request is an image, we can register _"an image"_623callback:624 625 app.is('an image', function(req){626 return 0 == req.headers['content-type'].indexOf('image');627 });628 629Now within our route callbacks, we can use to to assert content types630such as _"image/jpeg"_, _"image/png"_, etc.631 632 app.post('/image/upload', function(req, res, next){633 if (req.is('an image')) {634 // do something635 } else {636 next();637 }638 });639More is() docsTj Holowaychukbefore adoption071ea95
lines 640–642why, one step back640Keep in mind this method is _not_ limited to checking _Content-Type_, you641can perform any request assertion you wish.642Merge branch 'is'Tj Holowaychukbefore adoption7a71380
lines 643–650why, one step back643Wildcard matches can also be made, simplifying our example above for _"an image"_, by asserting the _subtype_ only:644645 req.is('image/*');646647We may also assert the _type_ as shown below, which would return true for _"application/json"_, and _"text/json"_.648649 req.is('*/json');650Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 651–680why, one step back651### req.param(name)652653Return the value of param _name_ when present.654655 - Checks route placeholders (_req.params_), ex: /user/:id656 - Checks query string params (_req.query_), ex: ?id=12657 - Checks urlencoded body params (_req.body_), ex: id=12658659To utilize urlencoded request bodies, _req.body_660should be an object. This can be done by using661the _express.bodyDecoder_ middleware.662663### req.flash(type[, msg])664665Queue flash _msg_ of the given _type_.666667 req.flash('info', 'email sent');668 req.flash('error', 'email delivery failed');669 req.flash('info', 'email re-sent');670 // => 2671672 req.flash('info');673 // => ['email sent', 'email re-sent']674675 req.flash('info');676 // => []677678 req.flash();679 // => { error: ['email delivery failed'], info: [] }680Added flash formatter docsTj Holowaychukbefore adoptionf16978d
lines 681–684why, one step back681Flash notification message may also utilize formatters, by default only the %s string formatter is available:682683 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);684Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 685–725why, one step back685### req.isXMLHttpRequest686687Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header688to see if it was issued by an _XMLHttpRequest_:689690 req.xhr691 req.isXMLHttpRequest692693### res.header(key[, val])694695Get or set the response header _key_.696697 res.header('Content-Length');698 // => undefined699700 res.header('Content-Length', 123);701 // => 123702703 res.header('Content-Length');704 // => 123705706### res.contentType(type)707708Sets the _Content-Type_ response header to the given _type_.709710 var filename = 'path/to/image.png';711 res.contentType(filename);712 // res.headers['Content-Type'] is now "image/png"713714### res.attachment([filename])715716Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.717718 res.attachment('path/to/my/image.png');719720### res.sendfile(path)721722Used by `res.download()` to transfer an arbitrary file. 723724 res.sendfile('path/to/my.file');725Merge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 726–736why, one step back726This 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.727728 res.sendfile(path, function(err, path){729 if (err) {730 // handle the error731 } else {732 console.log('transferred %s', path);733 }734 });735736When 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 737–755why, one step back737738### res.download(file[, filename])739740Transfer the given _file_ as an attachment with optional alternative _filename_.741742 res.download('path/to/image.png');743 res.download('path/to/image.png', 'foo.png');744745This is equivalent to:746747 res.attachment(file);748 res.sendfile(file);749750### res.send(body|status[, headers|status[, status]])751752The `res.send()` method is a high level response utility allowing you to pass753objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status754code based responses. The following are all valid uses:755Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
line 756why, one step back756 res.send(); // 204Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 757–781why, one step back757 res.send(new Buffer('wahoo'));758 res.send({ some: 'json' });759 res.send('<p>some html</p>');760 res.send('Sorry, cant find that', 404);761 res.send('text', { 'Content-Type': 'text/plain' }, 201);762 res.send(404);763764By default the _Content-Type_ response header is set, however if explicitly765assigned through `res.send()` or previously with `res.header()` or `res.contentType()`766it will not be set again.767768### res.redirect(url[, status])769770Redirect to the given _url_ with a default response _status_ of 302.771772 res.redirect('/', 301);773 res.redirect('/account');774 res.redirect('http://google.com');775 res.redirect('home');776 res.redirect('back');777778Express supports "redirect mapping", which by default provides _home_, and _back_.779The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes780the "home" setting and defaults to "/".781Cookie docsTj Holowaychukbefore adoptiona89767c
lines 782–802why, one step back782### res.cookie(name, val[, options])783784Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.785786 // "Remember me" for 15 minutes 787 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });788789To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:790791 app.use(express.cookieDecoder());792 793 app.get('/', function(req, res){794 // use req.cookies.rememberme795 });796797### res.clearCookie(name)798799Clear cookie _name_ by setting "expires" far in the past.800801 res.clearCookie('rememberme');802Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 803–811why, one step back803### res.render(view[, options[, fn]])804805Render _view_ with the given _options_ and optional callback _fn_.806When a callback function is given a response will _not_ be made807automatically, however otherwise a response of _200_ and _text/html_ is given.808809 Most engines accept one or more of the following options,810 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:811Updated docsTj Holowaychukbefore adoptionfd4c88d
line 812why, one step back812 - _scope_ Template evaluation context (value of _this_)Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 813–814why, one step back813 - _locals_ Object containing local variables814 - _debug_ Output debugging informationMerge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
lines 815–816why, one step back815 - _status_ Response status code, defaults to 200816 - _headers_ Response headers objectFixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 817–822why, one step back817818### res.partial(view[, options])819820Render _view_ partial with the given _options_. This method is always available821to the view as a local variable.822New partial() docsTj Holowaychukbefore adoption1c90332
lines 823–824why, one step back823- _object_ the object named by _as_ or derived from the view name824- _as_ Variable name for each _collection_ or _object_ value, defaults to the view name.Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 825–834why, one step back825 * as: 'something' will add the _something_ local variable826 * as: this will use the collection value as the template context827 * as: global will merge the collection value's properties with _locals_828829- _collection_ Array of objects, the name is derived from the view name itself. 830 For example _video.html_ will have a object _video_ available to it.831832The following are equivalent, and the name of collection value when passed833to the partial will be _movie_ as derived from the name.834More partial() docsTj Holowaychukbefore adoptione87d637
lines 835–836why, one step back835 partial('theatre/movie.jade', { collection: movies });836 partial('theatre/movie.jade', movies);Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 837–855why, one step back837 partial('movie.jade', { collection: movies });838 partial('movie.jade', movies);839 partial('movie', movies);840 // In view: movie.director841842To change the local from _movie_ to _video_ we can use the "as" option:843844 partial('movie', { collection: movies, as: 'video' });845 // In view: video.director846847Also we can make our movie the value of _this_ within our view so that instead848of _movie.director_ we could use _this.director_.849850 partial('movie', { collection: movies, as: this });851 // In view: this.director852853Another alternative is to "explode" the properties of the collection item into854pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:855New partial() docsTj Holowaychukbefore adoption1c90332
line 856why, one step back856 partial('movie', { collection: movies, as: global });Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
line 857why, one step back857 // In view: directorNew partial() docsTj Holowaychukbefore adoption1c90332
lines 858–876why, one step back858859This same logic applies to a single partial object usage:860861 partial('movie', { object: movie, as: this });862 // In view: this.director863864 partial('movie', { object: movie, as: global });865 // In view: director866867 partial('movie', { object: movie, as: 'video' });868 // In view: video.director869870 partial('movie', { object: movie });871 // In view: movie.director872873When 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:874875 partial('movie', movie);876 // => In view: movie.directorFixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 877–886why, one step back877878### app.set(name[, val])879880Apply an application level setting _name_ to _val_, or881get the value of _name_ when _val_ is not present:882883 app.set('views', __dirname + '/views');884 app.set('views');885 // => ...path...886Settings docsTj Holowaychukbefore adoptione562adc
lines 887–891why, one step back887Alternatively you may simply access the settings via _app.settings_:888889 app.settings.views890 // => ...path...891Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 892–998why, one step back892### app.enable(name)893894Enable the given setting _name_:895896 app.enable('some arbitrary setting');897 app.set('some arbitrary setting');898 // => true899900### app.disable(name)901902Disable the given setting _name_:903904 app.disable('some setting');905 app.set('some setting');906 // => false907908### app.configure(env|function[, function])909910Define a callback function for the given _env_ (or all environments) with callback _function_:911912 app.configure(function(){913 // executed for each env914 });915916 app.configure('development', function(){917 // executed for 'development' only918 });919920### app.redirect(name, val)921922For use with `res.redirect()` we can map redirects at the application level as shown below:923924 app.redirect('google', 'http://google.com');925926Now in a route we may call:927928 res.redirect('google');929930We may also map dynamic redirects:931932 app.redirect('comments', function(req, res){933 return '/post/' + req.params.id + '/comments';934 });935936So now we may do the following, and the redirect will dynamically adjust to937the context of the request. If we called this route with _GET /post/12_ our938redirect _Location_ would be _/post/12/comments_.939940 app.get('/post/:id', function(req, res){941 res.redirect('comments');942 });943944### app.error(function)945946Adds an error handler _function_ which will receive the exception as the first parameter as shown below.947Note that we may set several error handlers by making several calls to this method, however the handler948should call _next(err)_ if it does not wish to deal with the exception:949950 app.error(function(err, req, res, next){951 res.send(err.message, 500);952 });953954### app.helpers(obj)955956Registers static view helpers.957958 app.helpers({959 name: function(first, last){ return first + ', ' + last },960 firstName: 'tj',961 lastName: 'holowaychuk'962 });963964Our view could now utilize the _firstName_ and _lastName_ variables,965as well as the _name()_ function exposed.966967 <%= name(firstName, lastName) %>968969### app.dynamicHelpers(obj)970971Registers dynamic view helpers. Dynamic view helpers972are simply functions which accept _req_, _res_, and are973evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function974becomes the local variable it is associated with.975976 app.dynamicHelpers({977 session: function(req, res){978 return req.session;979 }980 });981982All views would now have _session_ available so that session data can be accessed via _session.name_ etc:983984 <%= session.name %>985986### app.mounted(fn)987988Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.989990 var app = express.createServer(),991 blog = express.createServer();992 993 blog.mounted(function(parent){994 // parent is app995 // "this" is blog996 });997 998 app.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 999–1020why, one step back9991000### app.register(ext, exports)10011002Register the given template engine _exports_1003as _ext_. For example we may wish to map ".html"1004files to jade:10051006 app.register('.html', require('jade'));10071008This is also useful for libraries that may not1009match extensions correctly. For example my haml.js1010library is installed from npm as "hamljs" so instead1011of layout.hamljs, we can register the engine as ".haml":10121013 app.register('.haml', require('haml-js'));10141015For engines that do not comply with the Express1016specification, we can also wrap their api this way.10171018 app.register('.foo', {1019 render: function(str, options) {1020 // perhaps their api isFix up app.register() docs. Closes #450Tj Holowaychukbefore adoption6ef6ba7
line 1021why, one step back1021 // return foo.toHTML(str, options);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 1022–1023why, one step back1022 }1023 });Fixed flash example. Closes #392Tj Holowaychukbefore adoptionae1c20f
lines 1024–1047why, one step back10241025### app.listen([port[, host]])10261027Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all1028connections will be accepted via _INADDR_ANY_.10291030 app.listen();1031 app.listen(3000);1032 app.listen(3000, 'n.n.n.n');10331034The _port_ argument may also be a string representing the path to a unix domain socket:10351036 app.listen('/tmp/express.sock');10371038Then try it out:10391040 $ telnet /tmp/express.sock1041 GET / HTTP/1.110421043 HTTP/1.1 200 OK1044 Content-Type: text/plain1045 Content-Length: 111046 1047 Hello World