guide.md
This file
Path
docs/guide.md
913 lines · 29.7 KiB · Markdown
Last changed by
Fixed docsTj Holowaychukbefore adoptioncef14ca
History of this fileTake it
The walk stopped after 200 commits: lines older than 699e6e1 point at it.
Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 1–40why, 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_.Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
lines 41–42why, one step back41Note 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.Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 43–44why, one step back4344 app.configure(function(){Updated docsTj Holowaychukbefore adoption344218f
lines 45–46why, one step back45 app.use(express.methodOverride());46 app.use(express.bodyDecoder());Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
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 'render-next'Tj Holowaychukbefore adoption699e6e1
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 'render-next'Tj Holowaychukbefore adoption699e6e1
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 'render-next'Tj Holowaychukbefore adoption699e6e1
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 'render-next'Tj Holowaychukbefore adoption699e6e1
line 74why, one step back74Updated docs to use NODE_ENVTj Holowaychukbefore adoptiond9d30ab
line 75why, one step back75 $ NODE_ENV=production node app.jsMerge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 76–81why, one step back7677### Settings7879Express supports the following settings out of the box:8081 * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_New "home" docsTj Holowaychukbefore adoption1e7a12f
line 82why, one step back82 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 83–84why, one step back83 * _views_ Root views directory defaulting to **CWD/views**84 * _view engine_ Default view engine name for views rendered without extensionsMerge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
line 85why, one step back85 * _view options_ An object specifying global view optionsMerge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 86–87why, one step back86 * _partials_ Root view partials directory defaulting to _views_/partials.87 * _stream threshold_ Bytesize indicating when a file should be streamed for _res.sendfile()_ using _fs.ReadStream()_ and _sys.pump()_.Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 88–92why, one step back8889### Routing9091Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.92For example we may want to render a user's account for the path _/user/12_, thisUpdated docsTj Holowaychukbefore adoptiond691ecb
lines 93–94why, one step back93can be done by defining the route below. The values associated to the named placeholders 94are available as `req.params`.Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
line 95why, one step back95Updated docsTj Holowaychukbefore adoptiond691ecb
lines 96–97why, one step back96 app.get('/user/:id', function(req, res){97 res.send('user ' + req.params.id);Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 98–105why, one step back98 });99100A route is simple a string which is compiled to a _RegExp_ internally. For example101when _/user/:id_ is compiled, a simplified version of the regexp may look similar to:102103 \/user\/([^\/]+)\/?104105Regular expression literals may also be passed for complex uses. Since captureUpdated docsTj Holowaychukbefore adoptiond691ecb
line 106why, one step back106groups with literal _RegExp_'s are anonymous we can access them directly `req.params`.Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
line 107why, one step back107Updated docsTj Holowaychukbefore adoptiond691ecb
lines 108–109why, one step back108 app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){109 res.send(req.params);Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 110–155why, one step back110 });111112Curl requests against the previously defined route:113114 $ curl http://dev:3000/user115 [null,null]116 $ curl http://dev:3000/users117 [null,null]118 $ curl http://dev:3000/users/1119 ["1",null]120 $ curl http://dev:3000/users/1..15121 ["1","15"]122123Below are some route examples, and the associated paths that they124may consume:125126 "/user/:id"127 /user/12128129 "/users/:id?"130 /users/5131 /users132133 "/files/*"134 /files/jquery.js135 /files/javascripts/jquery.js136137 "/file/*.*"138 /files/jquery.js139 /files/javascripts/jquery.js140 141 "/user/:id/:operation?"142 /user/1143 /user/1/edit144 145 "/products.:format"146 /products.json147 /products.xml148149 "/products.:format?"150 /products.json151 /products.xml152 /products153154### Passing Route Control155Updated docsTj Holowaychukbefore adoptiond691ecb
lines 156–157why, one step back156We may pass control to the next _matching_ route, by calling the _third_ argument,157the _next()_ function. When a match cannot be made, control is passed back to Connect,Added route-middleware exampleTj Holowaychukbefore adoption4983e96
line 158why, one step back158and 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 'render-next'Tj Holowaychukbefore adoption699e6e1
line 159why, one step back159Fixed doc typoTj Holowaychukbefore adoption47ff7d9
line 160why, one step back160 app.get('/users/:id?', function(req, res, next){Updated docsTj Holowaychukbefore adoptiond691ecb
lines 161–162why, one step back161 var id = req.params.id;162 if (id) {Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 163–168why, one step back163 // do something164 } else {165 next();166 }167 });168 Updated docsTj Holowaychukbefore adoptiond691ecb
line 169why, one step back169 app.get('/users', function(req, res){Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 170–171why, one step back170 // do something else171 });Added route-middleware exampleTj Holowaychukbefore adoption4983e96
line 172why, one step back172Ordering docsTj Holowaychukbefore adoption296f127
lines 173–197why, one step back173### Middleware174175Middleware via [Connect](http://github.com/senchalabs/connect) can be176passed to _express.createServer()_ as you would with a regular Connect server. For example:177178 var express = require('express');179180 var app = express.createServer(181 express.logger(),182 express.bodyDecoder()183 );184185Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:186187 app.use(express.logger({ format: ':method :uri' }));188189Typically with connect middleware you would _require('connect')_ like so:190191 var connect = require('connect');192 app.use(connect.logger());193194This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:195196 app.use(express.logger());197Added route-middleware exampleTj Holowaychukbefore adoption4983e96
lines 198–200why, one step back198### Route Middleware199200Routes 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 'render-next'Tj Holowaychukbefore adoption699e6e1
line 201why, one step back201Fixed docsTj Holowaychukbefore adoptioncef14ca
line 202why, one step back202Typically 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 203why, one step back203Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 204–209why, one step back204 app.get('/user/:id', function(req, res, next){205 loadUser(req.params.id, function(err, user){206 if (err) return next(err);207 res.send('Viewing user ' + user.name);208 });209 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 210–212why, one step back210211To 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. 212Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 213–226why, one step back213 function loadUser(req, res, next) {214 // You would fetch your user from the db215 var user = users[req.params.id];216 if (user) {217 req.user = user;218 next();219 } else {220 next(new Error('Failed to load user ' + req.params.id));221 }222 }223 224 app.get('/user/:id', loadUser, function(req, res){225 res.send('Viewing user ' + req.user.name);226 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 227–229why, one step back227228Multiple 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.229Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 230–231why, one step back230 function andRestrictToSelf(req, res, next) {231 req.authenticatedUser.id == req.user.idAdded route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 232–233why, one step back232 ? next()233 : next(new Error('Unauthorized'));Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 234–238why, one step back234 }235 236 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){237 res.send('Editing user ' + req.user.name);238 });Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
line 239why, one step back239Fixed docsTj Holowaychukbefore adoptioncef14ca
line 240why, one step back240Keeping 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 241why, one step back241Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 242–253why, one step back242 function andRestrictTo(role) {243 return function(req, res, next) {244 req.authenticatedUser.role == role245 ? next()246 : next(new Error('Unauthorized'));247 }248 }249 250 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){251 res.send('Deleted user ' + req.user.name);252 });253Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 254–255why, one step back254Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.255Fixed docsTj Holowaychukbefore adoptioncef14ca
lines 256–265why, one step back256 var a = [middleware1, middleware2]257 , b = [middleware3, middleware4]258 , all = [a, b];259 260 app.get('/foo', a, function(){});261 app.get('/bar', a, function(){});262 263 app.get('/', a, middleware3, middleware4, function(){});264 app.get('/', a, b, function(){});265 app.get('/', all, function(){});Added route middleware docsTj Holowaychukbefore adoptiondd4ddae
lines 266–268why, one step back266267For this example in full, view the [route middleware example](http://github.com/visionmedia/express/blob/master/examples/route-middleware/app.js) in the repository.268HTTP verb docs. Closes #415Tj Holowaychukbefore adoptiond89b951
lines 269–309why, one step back269### HTTP Methods270271We 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.272273 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.274 275 <form method="post" action="/">276 <input type="text" name="user[name]" />277 <input type="text" name="user[email]" />278 <input type="submit" value="Submit" />279 </form>280281By 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:282283 app.use(express.bodyDecoder());284285Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.286287 app.post('/', function(req, res){288 console.log(req.body.user);289 res.redirect('back');290 });291292When 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.293294 app.use(express.bodyDecoder());295 app.use(express.methodOverride());296297The 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:298299 <form method="post" action="/">300 <input type="hidden" name="_method" value="put" />301 <input type="text" name="user[name]" />302 <input type="text" name="user[email]" />303 <input type="submit" value="Submit" /> 304 </form>305306 app.put('/', function(){307 console.log(req.body.user);308 res.redirect('back');309 });Updated docsTj Holowaychukbefore adoption344218f
line 310why, one step back310Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 311–336why, one step back311### Error Handling312313Express provides the _app.error()_ method which receives exceptions thrown within a route,314or passed to _next(err)_. Below is an example which serves different pages based on our315ad-hoc _NotFound_ exception:316317 function NotFound(msg){318 this.name = 'NotFound';319 Error.call(this, msg);320 Error.captureStackTrace(this, arguments.callee);321 }322323 sys.inherits(NotFound, Error);324325 app.get('/404', function(req, res){326 throw new NotFound;327 });328329 app.get('/500', function(req, res){330 throw new Error('keyboard cat!');331 });332333We can call _app.error()_ several times as shown below.334Here we check for an instanceof _NotFound_ and show the335404 page, or we pass on to the next error handler.336Merge branch 'fix-error'Tj Holowaychukbefore adoption498115d
lines 337–341why, one step back337Note that these handlers can be defined anywhere, as they338will be placed below the route handlers on _listen()_. This 339allows for definition within _configure()_ blocks so we can340handle exceptions in different ways based on the environment.341Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 342–364why, one step back342 app.error(function(err, req, res, next){343 if (err instanceof NotFound) {344 res.render('404.jade');345 } else {346 next(err);347 }348 });349350Here we assume all errors as 500 for the simplicity of351this demo, however you can choose whatever you like352353 app.error(function(err, req, res){354 res.render('500.jade', {355 locals: {356 error: err357 } 358 });359 });360361Our apps could also utilize the Connect _errorHandler_ middleware362to report on exceptions. For example if we wish to output exceptions 363in "development" mode to _stderr_ we can use:364Updated docsTj Holowaychukbefore adoption344218f
line 365why, one step back365 app.use(express.errorHandler({ dumpExceptions: true }));Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 366–369why, one step back366367Also during development we may want fancy html pages to show exceptions368that are passed or thrown, so we can set _showStack_ to true:369Updated docsTj Holowaychukbefore adoption344218f
line 370why, one step back370 app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 371–378why, one step back371372The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_373is present, which is useful for developing apps that rely heavily on client-side JavaScript.374375### View Rendering376377View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name378of the module that will be required. For example the view _layout.ejs_ willAdded app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 379–380why, one step back379tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 380_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 381–408why, one step back381382Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,383and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 384the _body_ local variable in _layout.haml_.385386 app.get('/', function(req, res){387 res.render('index.haml', {388 locals: { title: 'My Site' }389 });390 });391392The new _view engine_ setting allows us to specify our default template engine,393so for example when using [Jade](http://github.com/visionmedia/jade) we could set:394395 app.set('view engine', 'jade');396397Allowing us to render with:398399 res.render('index');400401vs:402403 res.render('index.jade');404405When _view engine_ is set, extensions are entirely optional, however we can still406mix and match template engines:407408 res.render('another-page.ejs');Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 409–419why, one step back409410Express 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:411412 app.set('view options', {413 layout: false414 });415416Which can then be overridden within the `res.render()` call if need be:417418 res.render('myview.ejs', { layout: true });419Docs for layout optionTj Holowaychukbefore adoption0a96621
lines 420–431why, one step back420When 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:421422 res.render('page', { layout: 'mylayout' });423424Otherwise we must specify the extension:425426 res.render('page', { layout: 'mylayout.jade' });427428These paths may also be absolute:429430 res.render('page', { layout: __dirname + '/../../mylayout.jade' });431Merge branch 'app-level-view-options'Tj Holowaychukbefore adoption706e32c
lines 432–437why, one step back432A good example of this is specifying custom _ejs_ opening and closing tags:433434 app.set('view options', {435 open: '{{',436 close: '}}'437 });Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 438–461why, one step back438439### View Partials440441The Express view system has built-in support for partials and collections, which are442sort of "mini" views representing a document fragment. For example rather than iterating443in a view to display comments, we would use a partial with collection support:444445 partial('comment.haml', { collection: comments });446447To make things even less verbose we can assume the extension as _.haml_ when omitted,448however if we wished we could use an ejs partial, within a haml view for example.449450 partial('comment', { collection: comments });451452And once again even further, when rendering a collection we can simply pass453an array, if no other options are desired:454455 partial('comments', comments);456457When using the partial collection support a few "magic" variables are provided458for free:459460 * _firstInCollection_ True if this is the first object461 * _indexInCollection_ Index of the object in the collectionDoc typosTj Holowaychukbefore adoption02b4ec0
line 462why, one step back462 * _lastInCollection_ True if this is the last objectMerge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 463–467why, one step back463464### Template Engines465466Below are a few template engines commonly used with Express:467Doc typosTj Holowaychukbefore adoption02b4ec0
lines 468–469why, one step back468 * [Jade](http://jade-lang.com) haml.js successor469 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templatesMerge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
line 470why, one step back470 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScriptAdded session usage docs. Closes #443Tj Holowaychukbefore adoption89f7cbe
lines 471–483why, one step back471472### Session Support473474Sessions 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_.475476 app.use(express.cookieDecoder());477 app.use(express.session());478479By 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:480481 var RedisStore = require('connect-redis');482 app.use(express.cookieDecoder());483 app.use(express.session({ store: new RedisStore }));Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
line 484why, one step back484More session docsTj Holowaychukbefore adoption4bc8a86
lines 485–511why, one step back485Now 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:486487 var RedisStore = require('connect-redis');488 app.use(express.cookieDecoder());489 app.use(express.session({ store: new RedisStore }));490 app.use(express.bodyDecoder());491492 app.post('/add-to-cart', function(req, res){493 // Perhaps we posted several items with a form494 // (use the bodyDecoder() middleware for this)495 var items = req.body.items;496 req.session.items = items;497 res.redirect('back');498 });499500 app.get('/add-to-cart', function(req, res){501 // When redirected back to GET /add-to-cart502 // we could check req.session.items && req.session.items.length503 // to print out a message504 if (req.session.items && req.session.items.length) {505 req.flash('info', 'You have %s items in your cart', req.session.items.length);506 }507 res.render('shopping-cart');508 });509510The _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.511Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 512–547why, one step back512### req.header(key[, defaultValue])513514Get the case-insensitive request header _key_, with optional _defaultValue_:515516 req.header('Host');517 req.header('host');518 req.header('Accept', '*/*');519520### req.accepts(type)521522Check if the _Accept_ header is present, and includes the given _type_.523524When the _Accept_ header is not present _true_ is returned. Otherwise525the given _type_ is matched by an exact match, and then subtypes. You526may pass the subtype such as "html" which is then converted internally527to "text/html" using the mime lookup table.528529 // Accept: text/html530 req.accepts('html');531 // => true532533 // Accept: text/*; application/json534 req.accepts('html');535 req.accepts('text/html');536 req.accepts('text/plain');537 req.accepts('application/json');538 // => true539540 req.accepts('image/png');541 req.accepts('png');542 // => false543544### req.param(name)545546Return the value of param _name_ when present.547Updated docsTj Holowaychukbefore adoptiond691ecb
lines 548–550why, one step back548 - Checks route placeholders (_req.params_), ex: /user/:id549 - Checks query string params (_req.query_), ex: ?id=12550 - Checks urlencoded body params (_req.body_), ex: id=12Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 551–553why, one step back551552To utilize urlencoded request bodies, _req.body_553should be an object. This can be done by usingUpdated docsTj Holowaychukbefore adoption344218f
line 554why, one step back554the _express.bodyDecoder_ middleware.Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 555–573why, one step back555556### req.flash(type[, msg])557558Queue flash _msg_ of the given _type_.559560 req.flash('info', 'email sent');561 req.flash('error', 'email delivery failed');562 req.flash('info', 'email re-sent');563 // => 2564565 req.flash('info');566 // => ['email sent', 'email re-sent']567568 req.flash('info');569 // => []570571 req.flash();572 // => { error: ['email delivery failed'], info: [] }573Added flash formatter docsTj Holowaychukbefore adoptionf16978d
lines 574–577why, one step back574Flash notification message may also utilize formatters, by default only the %s string formatter is available:575576 req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);577Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 578–618why, one step back578### req.isXMLHttpRequest579580Also aliased as _req.xhr_, this getter checks the _X-Requested-With_ header581to see if it was issued by an _XMLHttpRequest_:582583 req.xhr584 req.isXMLHttpRequest585586### res.header(key[, val])587588Get or set the response header _key_.589590 res.header('Content-Length');591 // => undefined592593 res.header('Content-Length', 123);594 // => 123595596 res.header('Content-Length');597 // => 123598599### res.contentType(type)600601Sets the _Content-Type_ response header to the given _type_.602603 var filename = 'path/to/image.png';604 res.contentType(filename);605 // res.headers['Content-Type'] is now "image/png"606607### res.attachment([filename])608609Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.610611 res.attachment('path/to/my/image.png');612613### res.sendfile(path)614615Used by `res.download()` to transfer an arbitrary file. 616617 res.sendfile('path/to/my.file');618Merge branch 'downloads'Tj Holowaychukbefore adoption949803d
lines 619–629why, one step back619This 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.620621 res.sendfile(path, function(err, path){622 if (err) {623 // handle the error624 } else {625 console.log('transferred %s', path);626 }627 });628629When the filesize exceeds the _stream threshold_ (defaulting to 32k), the file will be streamed using _fs.ReadStream_ and _sys.pump()_.Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 630–648why, one step back630631### res.download(file[, filename])632633Transfer the given _file_ as an attachment with optional alternative _filename_.634635 res.download('path/to/image.png');636 res.download('path/to/image.png', 'foo.png');637638This is equivalent to:639640 res.attachment(file);641 res.sendfile(file);642643### res.send(body|status[, headers|status[, status]])644645The `res.send()` method is a high level response utility allowing you to pass646objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status647code based responses. The following are all valid uses:648Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
line 649why, one step back649 res.send(); // 204Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 650–674why, one step back650 res.send(new Buffer('wahoo'));651 res.send({ some: 'json' });652 res.send('<p>some html</p>');653 res.send('Sorry, cant find that', 404);654 res.send('text', { 'Content-Type': 'text/plain' }, 201);655 res.send(404);656657By default the _Content-Type_ response header is set, however if explicitly658assigned through `res.send()` or previously with `res.header()` or `res.contentType()`659it will not be set again.660661### res.redirect(url[, status])662663Redirect to the given _url_ with a default response _status_ of 302.664665 res.redirect('/', 301);666 res.redirect('/account');667 res.redirect('http://google.com');668 res.redirect('home');669 res.redirect('back');670671Express supports "redirect mapping", which by default provides _home_, and _back_.672The _back_ map checks the _Referrer_ and _Referer_ headers, while _home_ utilizes673the "home" setting and defaults to "/".674Cookie docsTj Holowaychukbefore adoptiona89767c
lines 675–695why, one step back675### res.cookie(name, val[, options])676677Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.678679 // "Remember me" for 15 minutes 680 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });681682To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:683684 app.use(express.cookieDecoder());685 686 app.get('/', function(req, res){687 // use req.cookies.rememberme688 });689690### res.clearCookie(name)691692Clear cookie _name_ by setting "expires" far in the past.693694 res.clearCookie('rememberme');695Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 696–704why, one step back696### res.render(view[, options[, fn]])697698Render _view_ with the given _options_ and optional callback _fn_.699When a callback function is given a response will _not_ be made700automatically, however otherwise a response of _200_ and _text/html_ is given.701702 Most engines accept one or more of the following options,703 both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:704Updated docsTj Holowaychukbefore adoptionfd4c88d
line 705why, one step back705 - _scope_ Template evaluation context (value of _this_)Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 706–707why, one step back706 - _locals_ Object containing local variables707 - _debug_ Output debugging informationMerge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption838a51d
lines 708–709why, one step back708 - _status_ Response status code, defaults to 200709 - _headers_ Response headers objectMerge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 710–753why, one step back710711### res.partial(view[, options])712713Render _view_ partial with the given _options_. This method is always available714to the view as a local variable.715716- _as_ Variable name for each _collection_ value, defaults to the view name.717 * as: 'something' will add the _something_ local variable718 * as: this will use the collection value as the template context719 * as: global will merge the collection value's properties with _locals_720721- _collection_ Array of objects, the name is derived from the view name itself. 722 For example _video.html_ will have a object _video_ available to it.723724The following are equivalent, and the name of collection value when passed725to the partial will be _movie_ as derived from the name.726727 partial('movie.jade', { collection: movies });728 partial('movie.jade', movies);729 partial('movie', movies);730 // In view: movie.director731732To change the local from _movie_ to _video_ we can use the "as" option:733734 partial('movie', { collection: movies, as: 'video' });735 // In view: video.director736737Also we can make our movie the value of _this_ within our view so that instead738of _movie.director_ we could use _this.director_.739740 partial('movie', { collection: movies, as: this });741 // In view: this.director742743Another alternative is to "explode" the properties of the collection item into744pseudo globals (local variables) by using _as: global_, which again is syntactic sugar:745746 partials('movie', { collection: movies, as: global });747 // In view: director748749### app.set(name[, val])750751Apply an application level setting _name_ to _val_, or752get the value of _name_ when _val_ is not present:753Removed "reload views" setting and support codeTj Holowaychukbefore adoption262b110
lines 754–756why, one step back754 app.set('views', __dirname + '/views');755 app.set('views');756 // => ...path...Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 757–797why, one step back757758### app.enable(name)759760Enable the given setting _name_:761762 app.enable('some arbitrary setting');763 app.set('some arbitrary setting');764 // => true765766### app.disable(name)767768Disable the given setting _name_:769770 app.disable('some setting');771 app.set('some setting');772 // => false773774### app.configure(env|function[, function])775776Define a callback function for the given _env_ (or all environments) with callback _function_:777778 app.configure(function(){779 // executed for each env780 });781782 app.configure('development', function(){783 // executed for 'development' only784 });785786### app.redirect(name, val)787788For use with `res.redirect()` we can map redirects at the application level as shown below:789790 app.redirect('google', 'http://google.com');791792Now in a route we may call:793794 res.redirect('google');795796We may also map dynamic redirects:797Updated docsTj Holowaychukbefore adoptiond691ecb
lines 798–799why, one step back798 app.redirect('comments', function(req, res){799 return '/post/' + req.params.id + '/comments';Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 800–837why, one step back800 });801802So now we may do the following, and the redirect will dynamically adjust to803the context of the request. If we called this route with _GET /post/12_ our804redirect _Location_ would be _/post/12/comments_.805806 app.get('/post/:id', function(req, res){807 res.redirect('comments');808 });809810### app.error(function)811812Adds an error handler _function_ which will receive the exception as the first parameter as shown below.813Note that we may set several error handlers by making several calls to this method, however the handler814should call _next(err)_ if it does not wish to deal with the exception:815816 app.error(function(err, req, res, next){817 res.send(err.message, 500);818 });819820### app.helpers(obj)821822Registers static view helpers.823824 app.helpers({825 name: function(first, last){ return first + ', ' + last },826 firstName: 'tj',827 lastName: 'holowaychuk'828 });829830Our view could now utilize the _firstName_ and _lastName_ variables,831as well as the _name()_ function exposed.832833 <%= name(firstName, lastName) %>834835### app.dynamicHelpers(obj)836837Registers dynamic view helpers. Dynamic view helpersUpdated docsTj Holowaychukbefore adoptiond691ecb
line 838why, one step back838are simply functions which accept _req_, _res_, and areMerge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 839–842why, one step back839evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function840becomes the local variable it is associated with.841842 app.dynamicHelpers({Updated docsTj Holowaychukbefore adoptiond691ecb
line 843why, one step back843 session: function(req, res){Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 844–850why, one step back844 return req.session;845 }846 });847848All views would now have _session_ available so that session data can be accessed via _session.name_ etc:849850 <%= session.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 851–864why, one step back851852### app.mounted(fn)853854Assign a callback _fn_ which is called when this _Server_ is passed to _Server#use()_.855856 var app = express.createServer(),857 blog = express.createServer();858 859 blog.mounted(function(parent){860 // parent is app861 // "this" is blog862 });863 864 app.use(blog);Added app.register() docsTj Holowaychukbefore adoption77e5d8e
lines 865–889why, one step back865866### app.register(ext, exports)867868Register the given template engine _exports_869as _ext_. For example we may wish to map ".html"870files to jade:871872 app.register('.html', require('jade'));873874This is also useful for libraries that may not875match extensions correctly. For example my haml.js876library is installed from npm as "hamljs" so instead877of layout.hamljs, we can register the engine as ".haml":878879 app.register('.haml', require('haml-js'));880881For engines that do not comply with the Express882specification, we can also wrap their api this way.883884 app.register('.foo', {885 render: function(str, options) {886 // perhaps their api is887 // foo.toHTML(str, options);888 }889 });Merge branch 'render-next'Tj Holowaychukbefore adoption699e6e1
lines 890–913why, one step back890891### app.listen([port[, host]])892893Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all894connections will be accepted via _INADDR_ANY_.895896 app.listen();897 app.listen(3000);898 app.listen(3000, 'n.n.n.n');899900The _port_ argument may also be a string representing the path to a unix domain socket:901902 app.listen('/tmp/express.sock');903904Then try it out:905906 $ telnet /tmp/express.sock907 GET / HTTP/1.1908909 HTTP/1.1 200 OK910 Content-Type: text/plain911 Content-Length: 11912 913 Hello World