docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent 14bd50e · Browse files · 3 files·+170 added−176 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+170 added−176 removed
- other:+170 added−176 removed
Provenance
- Commit
9d1b3f5- Tree
4ee78c8- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
14bd50e
3 files changed+170 added−176 removed
modified:docs/guide.1+50 added-52 removed
372 unmodified lines373 .nf374 375 var connect = require(\'connect\');376 app\.use(connect\.logger());377+app\.use(connect\.bodyParser());378 .379 .fi380 .381 .IP "" 05 unmodified lines387 .388 .nf389 390 app\.use(express\.logger());391+app\.use(express\.bodyParser());392 .393 .fi394 .395 .IP "" 08 unmodified lines404 .405 .nf406 407 app\.get(\'/user/:id\', function(req, res, next){406- loadUser(req\.params\.id, function(err, user){407- if (err) return next(err);408- res\.send(\'Viewing user \' + user\.name);409- });408+ loadUser(req\.params\.id, function(err, user){409+ if (err) return next(err);410+ res\.send(\'Viewing user \' + user\.name);411+ });412 });413 .414 .fi415 .6 unmodified lines422 .423 .nf424 425 function loadUser(req, res, next) {424- // You would fetch your user from the db425- var user = users[req\.params\.id];426- if (user) {427- req\.user = user;428- next();429- } else {430- next(new Error(\'Failed to load user \' + req\.params\.id));431- }426+ // You would fetch your user from the db427+ var user = users[req\.params\.id];428+ if (user) {429+ req\.user = user;430+ next();431+ } else {432+ next(new Error(\'Failed to load user \' + req\.params\.id));433+ }434 }435 436 app\.get(\'/user/:id\', loadUser, function(req, res){435- res\.send(\'Viewing user \' + req\.user\.name);437+ res\.send(\'Viewing user \' + req\.user\.name);438 });439 .440 .fi441 .6 unmodified lines448 .449 .nf450 451 function andRestrictToSelf(req, res, next) {450- req\.authenticatedUser\.id == req\.user\.id451- ? next()452- : next(new Error(\'Unauthorized\'));452+ req\.authenticatedUser\.id == req\.user\.id453+ ? next()454+ : next(new Error(\'Unauthorized\'));455 }456 457 app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){456- res\.send(\'Editing user \' + req\.user\.name);458+ res\.send(\'Editing user \' + req\.user\.name);459 });460 .461 .fi462 .6 unmodified lines469 .470 .nf471 472 function andRestrictTo(role) {471- return function(req, res, next) {472- req\.authenticatedUser\.role == role473- ? next()474- : next(new Error(\'Unauthorized\'));475- }473+ return function(req, res, next) {474+ req\.authenticatedUser\.role == role475+ ? next()476+ : next(new Error(\'Unauthorized\'));477+ }478 }479 480 app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){479- res\.send(\'Deleted user \' + req\.user\.name);481+ res\.send(\'Deleted user \' + req\.user\.name);482 });483 .484 .fi485 .44 unmodified lines530 .531 .IP "" 0532 .533 .P532-By default Express does not know what to do with this request body, so we should add the \fIbodyDecoder\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:534+By default Express does not know what to do with this request body, so we should add the \fIbodyParser\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR and \fIapplication/json\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:535 .536 .IP "" 4537 .538 .nf539 538-app\.use(express\.bodyDecoder());540+app\.use(express\.bodyParser());541 .542 .fi543 .544 .IP "" 05 unmodified lines550 .551 .nf552 553 app\.post(\'/\', function(req, res){552- console\.log(req\.body\.user);553- res\.redirect(\'back\');554+ console\.log(req\.body\.user);555+ res\.redirect(\'back\');556 });557 .558 .fi559 .560 .IP "" 0561 .562 .P561-When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyDecoder\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.563+When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyParser\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.564 .565 .IP "" 4566 .567 .nf568 567-app\.use(express\.bodyDecoder());569+app\.use(express\.bodyParser());570 app\.use(express\.methodOverride());571 .572 .fi573 .29 unmodified lines603 .604 .nf605 606 function NotFound(msg){605- this\.name = \'NotFound\';606- Error\.call(this, msg);607- Error\.captureStackTrace(this, arguments\.callee);607+ this\.name = \'NotFound\';608+ Error\.call(this, msg);609+ Error\.captureStackTrace(this, arguments\.callee);610 }611 610-sys\.inherits(NotFound, Error);612+NotFound\.protoype\.__proto__ = Error\.prototype;613 614 app\.get(\'/404\', function(req, res){613- throw new NotFound;615+ throw new NotFound;616 });617 618 app\.get(\'/500\', function(req, res){617- throw new Error(\'keyboard cat!\');619+ throw new Error(\'keyboard cat!\');620 });621 .622 .fi623 .21 unmodified lines645 .646 .IP "" 0647 .648 .P647-Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like649+Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like\. For example when node performs filesystem syscalls, you may receive an error object with the \fIerror\.code\fR of \fIENOENT\fR, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired\.650 .651 .IP "" 4652 .653 .nf654 655 app\.error(function(err, req, res){654- res\.render(\'500\.jade\', {655- locals: {656- error: err657- }658- });656+ res\.render(\'500\.jade\', {657+ error: err658+ });659 });660 .661 .fi662 .27 unmodified lines690 .691 .P692 The \fIerrorHandler\fR middleware also responds with \fIjson\fR if \fIAccept: application/json\fR is present, which is useful for developing apps that rely heavily on client\-side JavaScript\.693 .694-.SS "Route Preconditions"695-Route placeholder pre\-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls\. For example if you are constantly fetching common data for several routes, such as loading a user for \fI/user/:id\fR,we might typically do something like below:694+.SS "Route Param Pre\-conditions"695+Route param pre\-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls\. For example if you are constantly fetching common data for several routes, such as loading a user for \fI/user/:id\fR, we might typically do something like below:696 .697 .IP "" 4698 .699 .nf9 unmodified lines709 .710 .IP "" 0711 .712 .P713-With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database\. Below we invoke \fIapp\.param()\fR with the parameter name we wish to map to some middleware, as you can see we receive the \fIid\fR argument which contains the placeholder value\. Using this we load the user and perform error handling as usual, and simple call \fInext()\fR to pass control to the next precondition or route handler\.713+With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database\. Below we invoke \fIapp\.param()\fR with the parameter name we wish to map to some middleware, as you can see we receive the \fIid\fR argument which contains the placeholder value\. Using this we load the user and perform error handling as usual, and simple call \fInext()\fR to pass control to the next precondition or route handler\.714 .715 .IP "" 4716 .717 .nf52 unmodified lines770 .771 .IP "" 0772 .773 .SS "View Rendering"774-View filenames take the form \fINAME\fR\.\fIENGINE\fR, where \fIENGINE\fR is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.render(str, options)\fR to comply with Express, however \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by jade\.774+View filenames take the form "<name>\.<engine>", where <engine> is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.compile(str, options)\fR, and return a \fIFunction\fR to comply with Express\. To alter this behaviour \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by ejs\.775 .776 .P777-Below is an example using Haml\.js \fIhttp://github\.com/visionmedia/haml\.js\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.html\fR will be passed as the \fIbody\fR local variable in \fIlayout\.haml\fR\.777+Below is an example using Jade \fIhttp://github\.com/visionmedia/jade\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.jade\fR will be passed as the \fIbody\fR local variable in \fIlayout\.jade\fR\.778 .779 .IP "" 4780 .781 .nf782 783 app\.get(\'/\', function(req, res){784- res\.render(\'index\.haml\', {785- locals: { title: \'My Site\' }786- });784+ res\.render(\'index\.jade\', { title: \'My Site\' });785 });786 .787 .fi788 .789 .IP "" 0790 .791 .P794-The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using Jade \fIhttp://github\.com/visionmedia/jade\fR we could set:792+The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using jade we could set:793 .794 .IP "" 4795 .796 .nf50 unmodified lines847 .848 .nf849 850 app\.set(\'view options\', {853- layout: false851+ layout: false852 });853 .854 .fi855 .856 .IP "" 0857 .858 .P861-Which can then be overridden within the \fBres\.render()\fR call if need be:859+Which can then be overridden within the \fIres\.render()\fR call if need be:860 .861 .IP "" 4862 .863 .nf1101 unmodified linesmodified:docs/guide.html+55 added-57 removed
188 unmodified lines189 <li><a href="#Middleware">Middleware</a></li>190 <li><a href="#Route-Middleware">Route Middleware</a></li>191 <li><a href="#HTTP-Methods">HTTP Methods</a></li>192 <li><a href="#Error-Handling">Error Handling</a></li>193-<li><a href="#Route-Preconditions">Route Preconditions</a></li>193+<li><a href="#Route-Param-Pre-conditions">Route Param Pre-conditions</a></li>194 <li><a href="#View-Rendering">View Rendering</a></li>195 <li><a href="#View-Partials">View Partials</a></li>196 <li><a href="#Template-Engines">Template Engines</a></li>197 <li><a href="#Session-Support">Session Support</a></li>309 unmodified lines507 <p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>508 509 <pre><code>var connect = require('connect');510 app.use(connect.logger());511+app.use(connect.bodyParser());512 </code></pre>513 514 <p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>515 516 <pre><code>app.use(express.logger());517+app.use(express.bodyParser());518 </code></pre>519 520 <h3 id="Route-Middleware">Route Middleware</h3>521 1 unmodified line523 524 <p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>525 526 <pre><code>app.get('/user/:id', function(req, res, next){525- loadUser(req.params.id, function(err, user){526- if (err) return next(err);527- res.send('Viewing user ' + user.name);528- });527+ loadUser(req.params.id, function(err, user){528+ if (err) return next(err);529+ res.send('Viewing user ' + user.name);530+ });531 });532 </code></pre>533 534 <p>To 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.</p>535 536 <pre><code>function loadUser(req, res, next) {535- // You would fetch your user from the db536- var user = users[req.params.id];537- if (user) {538- req.user = user;539- next();540- } else {541- next(new Error('Failed to load user ' + req.params.id));542- }537+ // You would fetch your user from the db538+ var user = users[req.params.id];539+ if (user) {540+ req.user = user;541+ next();542+ } else {543+ next(new Error('Failed to load user ' + req.params.id));544+ }545 }546 547 app.get('/user/:id', loadUser, function(req, res){546- res.send('Viewing user ' + req.user.name);548+ res.send('Viewing user ' + req.user.name);549 });550 </code></pre>551 552 <p>Multiple 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.</p>553 554 <pre><code>function andRestrictToSelf(req, res, next) {553- req.authenticatedUser.id == req.user.id554- ? next()555- : next(new Error('Unauthorized'));555+ req.authenticatedUser.id == req.user.id556+ ? next()557+ : next(new Error('Unauthorized'));558 }559 560 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){559- res.send('Editing user ' + req.user.name);561+ res.send('Editing user ' + req.user.name);562 });563 </code></pre>564 565 <p>Keeping in mind that middleware are simply functions, we can define function that <em>returns</em> the middleware in order to create a more expressive and flexible solution as shown below.</p>566 567 <pre><code>function andRestrictTo(role) {566- return function(req, res, next) {567- req.authenticatedUser.role == role568- ? next()569- : next(new Error('Unauthorized'));570- }568+ return function(req, res, next) {569+ req.authenticatedUser.role == role570+ ? next()571+ : next(new Error('Unauthorized'));572+ }573 }574 575 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){574- res.send('Deleted user ' + req.user.name);576+ res.send('Deleted user ' + req.user.name);577 });578 </code></pre>579 580 <p>Commonly used "stacks" of middleware can be passed as an array (<em>applied recursively</em>), which can be mixed and matched to any degree.</p>24 unmodified lines605 <input type="submit" value="Submit" />606 </form>607 </code></pre>608 607-<p>By default Express does not know what to do with this request body, so we should add the <em>bodyDecoder</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>609+<p>By default Express does not know what to do with this request body, so we should add the <em>bodyParser</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> and <em>application/json</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>610 609-<pre><code>app.use(express.bodyDecoder());611+<pre><code>app.use(express.bodyParser());612 </code></pre>613 614 <p>Our route below will now have access to the <em>req.body.user</em> object which will contain the <em>name</em> and <em>email</em> properties when defined.</p>615 616 <pre><code>app.post('/', function(req, res){615- console.log(req.body.user);616- res.redirect('back');617+ console.log(req.body.user);618+ res.redirect('back');619 });620 </code></pre>621 620-<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyDecoder</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>622+<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyParser</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>623 622-<pre><code>app.use(express.bodyDecoder());624+<pre><code>app.use(express.bodyParser());625 app.use(express.methodOverride());626 </code></pre>627 628 <p>The 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 <em>PUT</em> and <em>DELETE</em> can still be accessed by clients which can use them directly, although <em>methodOverride</em> provides a great solution for forms. Below shows what the usage of <em>PUT</em> might look like:</p>17 unmodified lines646 or passed to <em>next(err)</em>. Below is an example which serves different pages based on our647 ad-hoc <em>NotFound</em> exception:</p>648 649 <pre><code>function NotFound(msg){648- this.name = 'NotFound';649- Error.call(this, msg);650- Error.captureStackTrace(this, arguments.callee);650+ this.name = 'NotFound';651+ Error.call(this, msg);652+ Error.captureStackTrace(this, arguments.callee);653 }654 653-sys.inherits(NotFound, Error);655+NotFound.protoype.__proto__ = Error.prototype;656 657 app.get('/404', function(req, res){656- throw new NotFound;658+ throw new NotFound;659 });660 661 app.get('/500', function(req, res){660- throw new Error('keyboard cat!');662+ throw new Error('keyboard cat!');663 });664 </code></pre>665 666 <p>We can call <em>app.error()</em> several times as shown below.14 unmodified lines681 });682 </code></pre>683 684 <p>Here we assume all errors as 500 for the simplicity of683-this demo, however you can choose whatever you like</p>685+this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the <em>error.code</em> of <em>ENOENT</em>, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.</p>686 687 <pre><code>app.error(function(err, req, res){686- res.render('500.jade', {687- locals: {688- error: err689- } 690- });688+ res.render('500.jade', {689+ error: err690+ });691 });692 </code></pre>693 694 <p>Our apps could also utilize the Connect <em>errorHandler</em> middleware11 unmodified lines706 707 <p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>708 is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>709 710-<h3 id="Route-Preconditions">Route Preconditions</h3>710+<h3 id="Route-Param-Pre-conditions">Route Param Pre-conditions</h3>711 712-<p>Route placeholder pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for <em>/user/:id</em>,we might typically do something like below:</p>712+<p>Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for <em>/user/:id</em>, we might typically do something like below:</p>713 714 <pre><code>app.get('/user/:userId', function(req, res, next){715 User.get(req.params.userId, function(err, user){716 if (err) return next(err);1 unmodified line718 });719 }); 720 </code></pre>721 722-<p>With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>722+<p>With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>723 724 <pre><code>app.param('userId', function(req, res, next, id){725 User.get(id, function(err, user){726 if (err) return next(err);22 unmodified lines749 </code></pre>750 751 <h3 id="View-Rendering">View Rendering</h3>752 753-<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name753+<p>View filenames take the form "<name>.<engine>", where <engine> is the name754 of the module that will be required. For example the view <em>layout.ejs</em> will755-tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.render(str, options)</em> to comply with Express, however756-<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.</p>755+tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.compile(str, options)</em>, and return a <em>Function</em> to comply with Express. To alter this behaviour756+<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.</p>757 758-<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,759-and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as760-the <em>body</em> local variable in <em>layout.haml</em>.</p>758+<p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,759+and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as760+the <em>body</em> local variable in <em>layout.jade</em>.</p>761 762 <pre><code>app.get('/', function(req, res){763- res.render('index.haml', {764- locals: { title: 'My Site' }765- });763+ res.render('index.jade', { title: 'My Site' });764 });765 </code></pre>766 767 <p>The new <em>view engine</em> setting allows us to specify our default template engine,770-so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>768+so for example when using jade we could set:</p>769 770 <pre><code>app.set('view engine', 'jade');771 </code></pre>772 15 unmodified lines788 789 <p>Express also provides the <em>view options</em> setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:</p>790 791 <pre><code>app.set('view options', {794- layout: false792+ layout: false793 });794 </code></pre>795 798-<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>796+<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>797 798 <pre><code>res.render('myview.ejs', { layout: true });799 </code></pre>800 687 unmodified linesmodified:docs/guide.md+65 added-67 removed
238 unmodified lines239 Typically with connect middleware you would _require('connect')_ like so:240 241 var connect = require('connect');242 app.use(connect.logger());243+ app.use(connect.bodyParser());244 245 This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:246 247 app.use(express.logger());248+ app.use(express.bodyParser());249 250 ### Route Middleware251 252 Routes 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.253 254 Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 255 256 app.get('/user/:id', function(req, res, next){255- loadUser(req.params.id, function(err, user){256- if (err) return next(err);257- res.send('Viewing user ' + user.name);258- });257+ loadUser(req.params.id, function(err, user){258+ if (err) return next(err);259+ res.send('Viewing user ' + user.name);260+ });261 });262 263 To 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. 264 265 function loadUser(req, res, next) {264- // You would fetch your user from the db265- var user = users[req.params.id];266- if (user) {267- req.user = user;268- next();269- } else {270- next(new Error('Failed to load user ' + req.params.id));271- }266+ // You would fetch your user from the db267+ var user = users[req.params.id];268+ if (user) {269+ req.user = user;270+ next();271+ } else {272+ next(new Error('Failed to load user ' + req.params.id));273+ }274 }275 276 app.get('/user/:id', loadUser, function(req, res){275- res.send('Viewing user ' + req.user.name);277+ res.send('Viewing user ' + req.user.name);278 });279 280 Multiple 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.281 282 function andRestrictToSelf(req, res, next) {281- req.authenticatedUser.id == req.user.id282- ? next()283- : next(new Error('Unauthorized'));283+ req.authenticatedUser.id == req.user.id284+ ? next()285+ : next(new Error('Unauthorized'));286 }287 288 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){287- res.send('Editing user ' + req.user.name);289+ res.send('Editing user ' + req.user.name);290 });291 292 Keeping 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.293 294 function andRestrictTo(role) {293- return function(req, res, next) {294- req.authenticatedUser.role == role295- ? next()296- : next(new Error('Unauthorized'));297- }295+ return function(req, res, next) {296+ req.authenticatedUser.role == role297+ ? next()298+ : next(new Error('Unauthorized'));299+ }300 }301 302 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){301- res.send('Deleted user ' + req.user.name);303+ res.send('Deleted user ' + req.user.name);304 });305 306 Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.307 21 unmodified lines329 <input type="text" name="user[email]" />330 <input type="submit" value="Submit" />331 </form>332 331-By 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:333+By default Express does not know what to do with this request body, so we should add the _bodyParser_ middleware, which will parse _application/x-www-form-urlencoded_ and _application/json_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:334 333- app.use(express.bodyDecoder());335+ app.use(express.bodyParser());336 337 Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.338 339 app.post('/', function(req, res){338- console.log(req.body.user);339- res.redirect('back');340+ console.log(req.body.user);341+ res.redirect('back');342 });343 342-When 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.344+When 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 _bodyParser_ so that it can utilize it's _req.body_ containing the form values.345 344- app.use(express.bodyDecoder());346+ app.use(express.bodyParser());347 app.use(express.methodOverride());348 349 The 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:350 14 unmodified lines365 Express provides the _app.error()_ method which receives exceptions thrown within a route,366 or passed to _next(err)_. Below is an example which serves different pages based on our367 ad-hoc _NotFound_ exception:368 367- function NotFound(msg){368- this.name = 'NotFound';369- Error.call(this, msg);370- Error.captureStackTrace(this, arguments.callee);371- }369+ function NotFound(msg){370+ this.name = 'NotFound';371+ Error.call(this, msg);372+ Error.captureStackTrace(this, arguments.callee);373+ }374+ 375+ NotFound.protoype.__proto__ = Error.prototype;376+ 377+ app.get('/404', function(req, res){378+ throw new NotFound;379+ });380+ 381+ app.get('/500', function(req, res){382+ throw new Error('keyboard cat!');383+ });384 373- sys.inherits(NotFound, Error);374-375- app.get('/404', function(req, res){376- throw new NotFound;377- });378-379- app.get('/500', function(req, res){380- throw new Error('keyboard cat!');381- });382-385 We can call _app.error()_ several times as shown below.386 Here we check for an instanceof _NotFound_ and show the387 404 page, or we pass on to the next error handler.388 10 unmodified lines399 }400 });401 402 Here we assume all errors as 500 for the simplicity of401-this demo, however you can choose whatever you like403+this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the _error.code_ of _ENOENT_, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.404 403- app.error(function(err, req, res){404- res.render('500.jade', {405- locals: {406- error: err407- } 408- });409- });405+ app.error(function(err, req, res){406+ res.render('500.jade', {407+ error: err408+ });409+ });410 411 Our apps could also utilize the Connect _errorHandler_ middleware412 to report on exceptions. For example if we wish to output exceptions 413 in "development" mode to _stderr_ we can use:7 unmodified lines421 422 The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_423 is present, which is useful for developing apps that rely heavily on client-side JavaScript.424 425-### Route Preconditions425+### Route Param Pre-conditions426 427-Route placeholder pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_,we might typically do something like below:427+Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_, we might typically do something like below:428 429 app.get('/user/:userId', function(req, res, next){430 User.get(req.params.userId, function(err, user){431 if (err) return next(err);432 res.send('user ' + user.name);433 });434 }); 435 436-With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.436+With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.437 438 app.param('userId', function(req, res, next, id){439 User.get(id, function(err, user){440 if (err) return next(err);18 unmodified lines459 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });460 461 ### View Rendering462 463-View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name463+View filenames take the form "<name>.<engine>", where <engine> is the name464 of the module that will be required. For example the view _layout.ejs_ will465-tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 466-_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.465+tell the view system to _require('ejs')_, the module being loaded must export the method _exports.compile(str, options)_, and return a _Function_ to comply with Express. To alter this behaviour466+_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.467 468-Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,469-and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 470-the _body_ local variable in _layout.haml_.468+Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,469+and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 470+the _body_ local variable in _layout.jade_.471 472 app.get('/', function(req, res){473- res.render('index.haml', {474- locals: { title: 'My Site' }475- });473+ res.render('index.jade', { title: 'My Site' });474 });475 476 The new _view engine_ setting allows us to specify our default template engine,479-so for example when using [Jade](http://github.com/visionmedia/jade) we could set:477+so for example when using jade we could set:478 479 app.set('view engine', 'jade');480 481 Allowing us to render with:11 unmodified lines493 494 Express 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:495 496 app.set('view options', {499- layout: false497+ layout: false498 });499 502-Which can then be overridden within the `res.render()` call if need be:500+Which can then be overridden within the _res.render()_ call if need be:501 502 res.render('myview.ejs', { layout: true });503 504 When 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:603 unmodified lines