Skip to content
Myr

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

3 files+170 added−176 removed

modified:docs/guide.1+50 added-52 removed
372 unmodified lines
373.nf374375var connect = require(\'connect\');376app\.use(connect\.logger());377app\.use(connect\.bodyParser());378.379.fi380.381.IP "" 0
5 unmodified lines
387.388.nf389390app\.use(express\.logger());391app\.use(express\.bodyParser());392.393.fi394.395.IP "" 0
8 unmodified lines
404.405.nf406407app\.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 lines
422.423.nf424425function 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}435436app\.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 lines
448.449.nf450451function 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}456457app\.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 lines
469.470.nf471472function 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}479480app\.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 lines
530.531.IP "" 0532.533.P532By 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:534By 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.nf539538app\.use(express\.bodyDecoder());540app\.use(express\.bodyParser());541.542.fi543.544.IP "" 0
5 unmodified lines
550.551.nf552553app\.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.P561When 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\.563When 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.nf568567app\.use(express\.bodyDecoder());569app\.use(express\.bodyParser());570app\.use(express\.methodOverride());571.572.fi573.
29 unmodified lines
603.604.nf605606function 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}611610sys\.inherits(NotFound, Error);612NotFound\.protoype\.__proto__ = Error\.prototype;613614app\.get(\'/404\', function(req, res){613 throw new NotFound;615 throw new NotFound;616});617618app\.get(\'/500\', function(req, res){617 throw new Error(\'keyboard cat!\');619 throw new Error(\'keyboard cat!\');620});621.622.fi623.
21 unmodified lines
645.646.IP "" 0647.648.P647Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like649Here 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.nf654655app\.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 lines
690.691.P692The \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"695Route 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"695Route 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.nf
9 unmodified lines
709.710.IP "" 0711.712.P713With 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\.713With 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.nf
52 unmodified lines
770.771.IP "" 0772.773.SS "View Rendering"774View 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\.774View 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.P777Below 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\.777Below 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.nf782783app\.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.P794The 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:792The 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.nf
50 unmodified lines
847.848.nf849850app\.set(\'view options\', {853 layout: false851 layout: false852});853.854.fi855.856.IP "" 0857.858.P861Which can then be overridden within the \fBres\.render()\fR call if need be:859Which can then be overridden within the \fIres\.render()\fR call if need be:860.861.IP "" 4862.863.nf
1101 unmodified lines
modified:docs/guide.html+55 added-57 removed
188 unmodified lines
189<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 lines
507<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>508509<pre><code>var connect = require('connect');510app.use(connect.logger());511app.use(connect.bodyParser());512</code></pre>513514<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>515516<pre><code>app.use(express.logger());517app.use(express.bodyParser());518</code></pre>519520<h3 id="Route-Middleware">Route Middleware</h3>521
1 unmodified line
523524<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>525526<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>533534<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>535536<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}546547app.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>551552<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>553554<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}559560app.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>564565<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>566567<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}574575app.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>579580<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 lines
605 &lt;input type="submit" value="Submit" /&gt;606 &lt;/form&gt;607</code></pre>608607<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>610609<pre><code>app.use(express.bodyDecoder());611<pre><code>app.use(express.bodyParser());612</code></pre>613614<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>615616<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>621620<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>623622<pre><code>app.use(express.bodyDecoder());624<pre><code>app.use(express.bodyParser());625app.use(express.methodOverride());626</code></pre>627628<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 lines
646or passed to <em>next(err)</em>. Below is an example which serves different pages based on our647ad-hoc <em>NotFound</em> exception:</p>648649<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}654653sys.inherits(NotFound, Error);655NotFound.protoype.__proto__ = Error.prototype;656657app.get('/404', function(req, res){656 throw new NotFound;658 throw new NotFound;659});660661app.get('/500', function(req, res){660 throw new Error('keyboard cat!');662 throw new Error('keyboard cat!');663});664</code></pre>665666<p>We can call <em>app.error()</em> several times as shown below.
14 unmodified lines
681});682</code></pre>683684<p>Here we assume all errors as 500 for the simplicity of683this demo, however you can choose whatever you like</p>685this 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>686687<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>693694<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware
11 unmodified lines
706707<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>708is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>709710<h3 id="Route-Preconditions">Route Preconditions</h3>710<h3 id="Route-Param-Pre-conditions">Route Param Pre-conditions</h3>711712<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>713714<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 line
718 });719}); 720</code></pre>721722<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>723724<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 lines
749</code></pre>750751<h3 id="View-Rendering">View Rendering</h3>752753<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 "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name754of the module that will be required. For example the view <em>layout.ejs</em> will755tell 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>755tell 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>757758<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,759and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as760the <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>,759and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as760the <em>body</em> local variable in <em>layout.jade</em>.</p>761762<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>766767<p>The new <em>view engine</em> setting allows us to specify our default template engine,770so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>768so for example when using jade we could set:</p>769770<pre><code>app.set('view engine', 'jade');771</code></pre>772
15 unmodified lines
788789<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>790791<pre><code>app.set('view options', {794 layout: false792 layout: false793});794</code></pre>795798<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>797798<pre><code>res.render('myview.ejs', { layout: true });799</code></pre>800
687 unmodified lines
modified:docs/guide.md+65 added-67 removed
238 unmodified lines
239Typically with connect middleware you would _require('connect')_ like so:240241 var connect = require('connect');242 app.use(connect.logger());243 app.use(connect.bodyParser());244245This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:246247 app.use(express.logger());248 app.use(express.bodyParser());249250### Route Middleware251252Routes 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.253254Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 255256 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 });262263To 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. 264265 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 });279280Multiple 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.281282 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 });291292Keeping 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.293294 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 });305306Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.307
21 unmodified lines
329 <input type="text" name="user[email]" />330 <input type="submit" value="Submit" />331 </form>332331By 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:333By 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:334333 app.use(express.bodyDecoder());335 app.use(express.bodyParser());336337Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.338339 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 });343342When 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.344When 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.345344 app.use(express.bodyDecoder());346 app.use(express.bodyParser());347 app.use(express.methodOverride());348349The 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 lines
365Express provides the _app.error()_ method which receives exceptions thrown within a route,366or passed to _next(err)_. Below is an example which serves different pages based on our367ad-hoc _NotFound_ exception:368367 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 });384373 sys.inherits(NotFound, Error);374375 app.get('/404', function(req, res){376 throw new NotFound;377 });378379 app.get('/500', function(req, res){380 throw new Error('keyboard cat!');381 });382385We can call _app.error()_ several times as shown below.386Here we check for an instanceof _NotFound_ and show the387404 page, or we pass on to the next error handler.388
10 unmodified lines
399 }400 });401402Here we assume all errors as 500 for the simplicity of401this demo, however you can choose whatever you like403this 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.404403 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 });410411Our apps could also utilize the Connect _errorHandler_ middleware412to report on exceptions. For example if we wish to output exceptions 413in "development" mode to _stderr_ we can use:
7 unmodified lines
421422The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_423is present, which is useful for developing apps that rely heavily on client-side JavaScript.424425### Route Preconditions425### Route Param Pre-conditions426427Route 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:427Route 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:428429 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 }); 435436With 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.436With 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.437438 app.param('userId', function(req, res, next, id){439 User.get(id, function(err, user){440 if (err) return next(err);
18 unmodified lines
459 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });460461### View Rendering462463View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name463View filenames take the form "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name464of the module that will be required. For example the view _layout.ejs_ will465tell 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.465tell 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.467468Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,469and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 470the _body_ local variable in _layout.haml_.468Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,469and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 470the _body_ local variable in _layout.jade_.471472 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 });475476The new _view engine_ setting allows us to specify our default template engine,479so for example when using [Jade](http://github.com/visionmedia/jade) we could set:477so for example when using jade we could set:478479 app.set('view engine', 'jade');480481Allowing us to render with:
11 unmodified lines
493494Express 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:495496 app.set('view options', {499 layout: false497 layout: false498 });499502Which can then be overridden within the `res.render()` call if need be:500Which can then be overridden within the _res.render()_ call if need be:501502 res.render('myview.ejs', { layout: true });503504When 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