Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,975 lines · 42.4 KiB

Last changed by

Re-built docsTj Holowaychukbefore adoption8e63d04

History of this file

Take it

The walk stopped after 200 commits: lines older than e562adc point at it.

Settings docsTj Holowaychukbefore adoptione562adc

lines 1–3why, one step back
1.\" generated with Ronn/v0.7.3
2.\" http://github.com/rtomayko/ronn/tree/0.7.33.

Added screencasts pageTj Holowaychukbefore adoption4144af3

line 4why, one step back
4.TH "GUIDE" "" "December 2010" "" ""

Settings docsTj Holowaychukbefore adoptione562adc

lines 5–173why, one step back
5.
6.SH "NAME"7\fBguide\fR8.9.SS "Installation"10curl:11.12.IP "" 413.14.nf1516$ curl \-# http://expressjs\.com/install\.sh | sh17.18.fi19.20.IP "" 021.22.P23npm:24.25.IP "" 426.27.nf2829$ npm install express30.31.fi32.33.IP "" 034.35.SS "Creating An Application"36The \fIexpress\.Server\fR now inherits from \fIhttp\.Server\fR, however follows the same idiom by providing \fIexpress\.createServer()\fR as shown below\. This means that you can utilize Express server\'s transparently with other libraries\.37.38.IP "" 439.40.nf4142var app = require(\'express\')\.createServer();4344app\.get(\'/\', function(req, res){45 res\.send(\'hello world\');46});4748app\.listen(3000);49.50.fi51.52.IP "" 053.54.SS "Configuration"55Express supports arbitrary environments, such as \fIproduction\fR and \fIdevelopment\fR\. Developers can use the \fIconfigure()\fR method to setup needs required by the current environment\. When \fIconfigure()\fR is called without an environment name it will be run in \fIevery\fR environment prior to the environment specific callback\.56.57.P58In the example below we only \fIdumpExceptions\fR, and respond with exception stack traces in \fIdevelopment\fR mode, however for both environments we utilize \fImethodOverride\fR and \fIbodyDecoder\fR\. Note the use of \fIapp\.router\fR, which can (optionally) be used to mount the application routes, otherwise the first call to \fIapp\.{get,put,del,post}()\fR will mount the routes\.59.60.IP "" 461.62.nf6364app\.configure(function(){65 app\.use(express\.methodOverride());66 app\.use(express\.bodyDecoder());67 app\.use(app\.router);68 app\.use(express\.staticProvider(__dirname + \'/public\'));69});7071app\.configure(\'development\', function(){72 app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));73});7475app\.configure(\'production\', function(){76 app\.use(express\.errorHandler());77});78.79.fi80.81.IP "" 082.83.P84For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:85.86.IP "" 487.88.nf8990app\.configure(function(){91 app\.set(\'views\', __dirname + \'/views\');92 app\.set(\'views\');93 // => "\.\.\. views directory \.\.\."9495 app\.enable(\'some feature\');96 // same as app\.set(\'some feature\', true);9798 app\.disable(\'some feature\');99 // same as app\.set(\'some feature\', false);100});101.102.fi103.104.IP "" 0105.106.P107To alter the environment we can set the \fINODE_ENV\fR environment variable, for example:108.109.IP "" 4110.111.nf112113$ NODE_ENV=production node app\.js114.115.fi116.117.IP "" 0118.119.P120This is \fIvery\fR important, as many caching mechanisms are \fIonly enabled\fR when in production\.121.122.SS "Settings"123Express supports the following settings out of the box:124.125.IP "\(bu" 4126\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR127.128.IP "\(bu" 4129\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.130.131.IP "\(bu" 4132\fIviews\fR Root views directory defaulting to \fBCWD/views\fR133.134.IP "\(bu" 4135\fIview engine\fR Default view engine name for views rendered without extensions136.137.IP "\(bu" 4138\fIview options\fR An object specifying global view options139.140.IP "\(bu" 4141\fIstream threshold\fR Bytesize indicating when a file should be streamed for \fIres\.sendfile()\fR using \fIfs\.ReadStream()\fR and \fIsys\.pump()\fR\.142.143.IP "" 0144.145.SS "Routing"146Express utilizes the HTTP verbs to provide a meaningful, expressive routing API\. For example we may want to render a user\'s account for the path \fI/user/12\fR, this can be done by defining the route below\. The values associated to the named placeholders are available as \fBreq\.params\fR\.147.148.IP "" 4149.150.nf151152app\.get(\'/user/:id\', function(req, res){153 res\.send(\'user \' + req\.params\.id);154});155.156.fi157.158.IP "" 0159.160.P161A route is simple a string which is compiled to a \fIRegExp\fR internally\. For example when \fI/user/:id\fR is compiled, a simplified version of the regexp may look similar to:162.163.IP "" 4164.165.nf166167\e/user\e/([^\e/]+)\e/?168.169.fi170.171.IP "" 0172.173.P

Regenerated docsTj Holowaychukbefore adoptiond3abcaf

line 174why, one step back
174Regular expression literals may also be passed for complex uses\. Since capture groups with literal \fIRegExp\fR\'s are anonymous we can access them directly \fBreq\.params\fR\. So our first capture group would be \fIreq\.params[0]\fR and the second would follow as \fIreq\.params[1]\fR\.

Settings docsTj Holowaychukbefore adoptione562adc

lines 175–241why, one step back
175.
176.IP "" 4177.178.nf179180app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){181 res\.send(req\.params);182});183.184.fi185.186.IP "" 0187.188.P189Curl requests against the previously defined route:190.191.IP "" 4192.193.nf194195 $ curl http://dev:3000/user196 [null,null]197 $ curl http://dev:3000/users198 [null,null]199 $ curl http://dev:3000/users/1200 ["1",null]201 $ curl http://dev:3000/users/1\.\.15202 ["1","15"]203.204.fi205.206.IP "" 0207.208.P209Below are some route examples, and the associated paths that they may consume:210.211.IP "" 4212.213.nf214215 "/user/:id"216 /user/12217218 "/users/:id?"219 /users/5220 /users221222 "/files/*"223 /files/jquery\.js224 /files/javascripts/jquery\.js225226 "/file/*\.*"227 /files/jquery\.js228 /files/javascripts/jquery\.js229230 "/user/:id/:operation?"231 /user/1232 /user/1/edit233234 "/products\.:format"235 /products\.json236 /products\.xml237238 "/products\.:format?"239 /products\.json240 /products\.xml241 /products

Regenerated docsTj Holowaychukbefore adoptiond3abcaf

lines 242–245why, one step back
242
243 "/user/:id\.:format?"244 /user/12245 /user/12\.json

Settings docsTj Holowaychukbefore adoptione562adc

lines 246–250why, one step back
246.
247.fi248.249.IP "" 0250.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 251–271why, one step back
251.P
252For example we can \fBPOST\fR some json, and echo the json back using the \fIbodyDecoder\fR middleware which will parse json request bodies (as well as others), and place the result in \fIreq\.body\fR:253.254.IP "" 4255.256.nf257258var express = require(\'express\')259 , app = express\.createServer();260261app\.use(express\.bodyDecoder());262263app\.post(\'/\', function(req, res){264 res\.send(req\.body);265});266267app\.listen(3000);268.269.fi270.271.IP "" 0

Regenerated docsTj Holowaychukbefore adoptiond3abcaf

lines 272–274why, one step back
272.
273.P274Express 2\.0\.0\-pre also supports named capture groups\. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, however say for example we are limiting a user id to digits, we may use \fI\'/user/:id(\ed+)\'\fR which will \fInot\fR match unless the placeholder value contains only digits\.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

line 275why, one step back
275.

Settings docsTj Holowaychukbefore adoptione562adc

lines 276–299why, one step back
276.SS "Passing Route Control"
277We may pass control to the next \fImatching\fR route, by calling the \fIthird\fR argument, the \fInext()\fR function\. When a match cannot be made, control is passed back to Connect, and 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 \fInot\fR call \fInext()\fR\.278.279.IP "" 4280.281.nf282283app\.get(\'/users/:id?\', function(req, res, next){284 var id = req\.params\.id;285 if (id) {286 // do something287 } else {288 next();289 }290});291292app\.get(\'/users\', function(req, res){293 // do something else294});295.296.fi297.298.IP "" 0299.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 300–342why, one step back
300.P
301Express 1\.0 also introduces the \fIall()\fR method, which provides a route callback matching any HTTP method\. This is useful in many ways, one example being the loading of resources before executing subsequent routes as shown below:302.303.IP "" 4304.305.nf306307var express = require(\'express\')308 , app = express\.createServer();309310var users = [{ name: \'tj\' }];311312app\.all(\'/user/:id/:op?\', function(req, res, next){313 req\.user = users[req\.params\.id];314 if (req\.user) {315 next();316 } else {317 next(new Error(\'cannot find user \' + req\.params\.id));318 }319});320321app\.get(\'/user/:id\', function(req, res){322 res\.send(\'viewing \' + req\.user\.name);323});324325app\.get(\'/user/:id/edit\', function(req, res){326 res\.send(\'editing \' + req\.user\.name);327});328329app\.put(\'/user/:id\', function(req, res){330 res\.send(\'updating \' + req\.user\.name);331});332333app\.get(\'*\', function(req, res){334 res\.send(\'what???\', 404);335});336337app\.listen(3000);338.339.fi340.341.IP "" 0342.

Settings docsTj Holowaychukbefore adoptione562adc

lines 343–699why, one step back
343.SS "Middleware"
344Middleware via Connect \fIhttp://github\.com/senchalabs/connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:345.346.IP "" 4347.348.nf349350 var express = require(\'express\');351352var app = express\.createServer(353 express\.logger(),354 express\.bodyDecoder()355 );356.357.fi358.359.IP "" 0360.361.P362Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:363.364.IP "" 4365.366.nf367368app\.use(express\.logger({ format: \':method :uri\' }));369.370.fi371.372.IP "" 0373.374.P375Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:376.377.IP "" 4378.379.nf380381var connect = require(\'connect\');382app\.use(connect\.logger());383.384.fi385.386.IP "" 0387.388.P389This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:390.391.IP "" 4392.393.nf394395app\.use(express\.logger());396.397.fi398.399.IP "" 0400.401.SS "Route Middleware"402Routes 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\.403.404.P405Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.406.407.IP "" 4408.409.nf410411app\.get(\'/user/:id\', function(req, res, next){412 loadUser(req\.params\.id, function(err, user){413 if (err) return next(err);414 res\.send(\'Viewing user \' + user\.name);415 });416});417.418.fi419.420.IP "" 0421.422.P423To 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\.424.425.IP "" 4426.427.nf428429function loadUser(req, res, next) {430 // You would fetch your user from the db431 var user = users[req\.params\.id];432 if (user) {433 req\.user = user;434 next();435 } else {436 next(new Error(\'Failed to load user \' + req\.params\.id));437 }438}439440app\.get(\'/user/:id\', loadUser, function(req, res){441 res\.send(\'Viewing user \' + req\.user\.name);442});443.444.fi445.446.IP "" 0447.448.P449Multiple 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\.450.451.IP "" 4452.453.nf454455function andRestrictToSelf(req, res, next) {456 req\.authenticatedUser\.id == req\.user\.id457 ? next()458 : next(new Error(\'Unauthorized\'));459}460461app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){462 res\.send(\'Editing user \' + req\.user\.name);463});464.465.fi466.467.IP "" 0468.469.P470Keeping in mind that middleware are simply functions, we can define function that \fIreturns\fR the middleware in order to create a more expressive and flexible solution as shown below\.471.472.IP "" 4473.474.nf475476function andRestrictTo(role) {477 return function(req, res, next) {478 req\.authenticatedUser\.role == role479 ? next()480 : next(new Error(\'Unauthorized\'));481 }482}483484app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){485 res\.send(\'Deleted user \' + req\.user\.name);486});487.488.fi489.490.IP "" 0491.492.P493Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.494.495.IP "" 4496.497.nf498499var a = [middleware1, middleware2]500 , b = [middleware3, middleware4]501 , all = [a, b];502503app\.get(\'/foo\', a, function(){});504app\.get(\'/bar\', a, function(){});505506app\.get(\'/\', a, middleware3, middleware4, function(){});507app\.get(\'/\', a, b, function(){});508app\.get(\'/\', all, function(){});509.510.fi511.512.IP "" 0513.514.P515For this example in full, view the route middleware example \fIhttp://github\.com/visionmedia/express/blob/master/examples/route\-middleware/app\.js\fR in the repository\.516.517.SS "HTTP Methods"518We have seen \fIapp\.get()\fR a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as \fIapp\.post()\fR, \fIapp\.del()\fR, etc\.519.520.P521A common example for \fIPOST\fR 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\.522.523.IP "" 4524.525.nf526527 <form method="post" action="/">528 <input type="text" name="user[name]" />529 <input type="text" name="user[email]" />530 <input type="submit" value="Submit" />531 </form>532.533.fi534.535.IP "" 0536.537.P538By 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:539.540.IP "" 4541.542.nf543544app\.use(express\.bodyDecoder());545.546.fi547.548.IP "" 0549.550.P551Our route below will now have access to the \fIreq\.body\.user\fR object which will contain the \fIname\fR and \fIemail\fR properties when defined\.552.553.IP "" 4554.555.nf556557app\.post(\'/\', function(req, res){558 console\.log(req\.body\.user);559 res\.redirect(\'back\');560});561.562.fi563.564.IP "" 0565.566.P567When 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\.568.569.IP "" 4570.571.nf572573app\.use(express\.bodyDecoder());574app\.use(express\.methodOverride());575.576.fi577.578.IP "" 0579.580.P581The 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 \fIPUT\fR and \fIDELETE\fR can still be accessed by clients which can use them directly, although \fImethodOverride\fR provides a great solution for forms\. Below shows what the usage of \fIPUT\fR might look like:582.583.IP "" 4584.585.nf586587<form method="post" action="/">588 <input type="hidden" name="_method" value="put" />589 <input type="text" name="user[name]" />590 <input type="text" name="user[email]" />591 <input type="submit" value="Submit" />592</form>593594app\.put(\'/\', function(){595 console\.log(req\.body\.user);596 res\.redirect(\'back\');597});598.599.fi600.601.IP "" 0602.603.SS "Error Handling"604Express provides the \fIapp\.error()\fR method which receives exceptions thrown within a route, or passed to \fInext(err)\fR\. Below is an example which serves different pages based on our ad\-hoc \fINotFound\fR exception:605.606.IP "" 4607.608.nf609610function NotFound(msg){611 this\.name = \'NotFound\';612 Error\.call(this, msg);613 Error\.captureStackTrace(this, arguments\.callee);614}615616sys\.inherits(NotFound, Error);617618app\.get(\'/404\', function(req, res){619 throw new NotFound;620});621622app\.get(\'/500\', function(req, res){623 throw new Error(\'keyboard cat!\');624});625.626.fi627.628.IP "" 0629.630.P631We can call \fIapp\.error()\fR several times as shown below\. Here we check for an instanceof \fINotFound\fR and show the 404 page, or we pass on to the next error handler\.632.633.P634Note that these handlers can be defined anywhere, as they will be placed below the route handlers on \fIlisten()\fR\. This allows for definition within \fIconfigure()\fR blocks so we can handle exceptions in different ways based on the environment\.635.636.IP "" 4637.638.nf639640app\.error(function(err, req, res, next){641 if (err instanceof NotFound) {642 res\.render(\'404\.jade\');643 } else {644 next(err);645 }646});647.648.fi649.650.IP "" 0651.652.P653Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like654.655.IP "" 4656.657.nf658659app\.error(function(err, req, res){660 res\.render(\'500\.jade\', {661 locals: {662 error: err663 }664 });665});666.667.fi668.669.IP "" 0670.671.P672Our apps could also utilize the Connect \fIerrorHandler\fR middleware to report on exceptions\. For example if we wish to output exceptions in "development" mode to \fIstderr\fR we can use:673.674.IP "" 4675.676.nf677678app\.use(express\.errorHandler({ dumpExceptions: true }));679.680.fi681.682.IP "" 0683.684.P685Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:686.687.IP "" 4688.689.nf690691app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));692.693.fi694.695.IP "" 0696.697.P698The \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\.699.

Route precondition docsTj Holowaychukbefore adoptionfd2f67b

lines 700–778why, one step back
700.SS "Route Preconditions"
701Route 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:702.703.IP "" 4704.705.nf706707app\.get(\'/user/:userId\', function(req, res, next){708 User\.get(req\.params\.userId, function(err, user){709 if (err) return next(err);710 res\.send(\'user \' + user\.name);711 });712});713.714.fi715.716.IP "" 0717.718.P719With 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\.720.721.IP "" 4722.723.nf724725app\.param(\'userId\', function(req, res, next, id){726 User\.get(id, function(err, user){727 if (err) return next(err);728 if (!user) return next(new Error(\'failed to find user\'));729 req\.user = user;730 next();731 });732});733.734.fi735.736.IP "" 0737.738.P739Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:740.741.IP "" 4742.743.nf744745app\.get(\'/user/:userId\', function(req, res){746 res\.send(\'user \' + req\.user\.name);747});748.749.fi750.751.IP "" 0752.753.P754For simple cases such as route placeholder validation and coercion we can simple pass a callback which has an arity of 1 (accepts one argument)\. Any errors thrown will be passed to \fInext(err)\fR\.755.756.IP "" 4757.758.nf759760app\.param(\'number\', function(n){ return parseInt(n, 10); });761.762.fi763.764.IP "" 0765.766.P767We may also apply the same callback to several placeholders, for example a route GET \fI/commits/:from\-:to\fR are both numbers, so we may define them as an array:768.769.IP "" 4770.771.nf772773app\.param([\'from\', \'to\'], function(n){ return parseInt(n, 10); });774.775.fi776.777.IP "" 0778.

Settings docsTj Holowaychukbefore adoptione562adc

lines 779–992why, one step back
779.SS "View Rendering"
780View 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\.781.782.P783Below 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\.784.785.IP "" 4786.787.nf788789app\.get(\'/\', function(req, res){790 res\.render(\'index\.haml\', {791 locals: { title: \'My Site\' }792 });793});794.795.fi796.797.IP "" 0798.799.P800The 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:801.802.IP "" 4803.804.nf805806app\.set(\'view engine\', \'jade\');807.808.fi809.810.IP "" 0811.812.P813Allowing us to render with:814.815.IP "" 4816.817.nf818819res\.render(\'index\');820.821.fi822.823.IP "" 0824.825.P826vs:827.828.IP "" 4829.830.nf831832res\.render(\'index\.jade\');833.834.fi835.836.IP "" 0837.838.P839When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:840.841.IP "" 4842.843.nf844845res\.render(\'another\-page\.ejs\');846.847.fi848.849.IP "" 0850.851.P852Express also provides the \fIview options\fR setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:853.854.IP "" 4855.856.nf857858app\.set(\'view options\', {859 layout: false860});861.862.fi863.864.IP "" 0865.866.P867Which can then be overridden within the \fBres\.render()\fR call if need be:868.869.IP "" 4870.871.nf872873res\.render(\'myview\.ejs\', { layout: true });874.875.fi876.877.IP "" 0878.879.P880When an alternate layout is required, we may also specify a path\. For example if we have \fIview engine\fR set to \fIjade\fR and a file named \fI\./views/mylayout\.jade\fR we can simply pass:881.882.IP "" 4883.884.nf885886res\.render(\'page\', { layout: \'mylayout\' });887.888.fi889.890.IP "" 0891.892.P893Otherwise we must specify the extension:894.895.IP "" 4896.897.nf898899res\.render(\'page\', { layout: \'mylayout\.jade\' });900.901.fi902.903.IP "" 0904.905.P906These paths may also be absolute:907.908.IP "" 4909.910.nf911912res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });913.914.fi915.916.IP "" 0917.918.P919A good example of this is specifying custom \fIejs\fR opening and closing tags:920.921.IP "" 4922.923.nf924925app\.set(\'view options\', {926 open: \'{{\',927 close: \'}}\'928});929.930.fi931.932.IP "" 0933.934.SS "View Partials"935The Express view system has built\-in support for partials and collections, which are sort of "mini" views representing a document fragment\. For example rather than iterating in a view to display comments, we would use a partial with collection support:936.937.IP "" 4938.939.nf940941partial(\'comment\.haml\', { collection: comments });942.943.fi944.945.IP "" 0946.947.P948To make things even less verbose we can assume the extension as \fI\.haml\fR when omitted, however if we wished we could use an ejs partial, within a haml view for example\.949.950.IP "" 4951.952.nf953954partial(\'comment\', { collection: comments });955.956.fi957.958.IP "" 0959.960.P961And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:962.963.IP "" 4964.965.nf966967partial(\'comment\', comments);968.969.fi970.971.IP "" 0972.973.P974When using the partial collection support a few "magic" variables are provided for free:975.976.IP "\(bu" 4977\fIfirstInCollection\fR True if this is the first object978.979.IP "\(bu" 4980\fIindexInCollection\fR Index of the object in the collection981.982.IP "\(bu" 4983\fIlastInCollection\fR True if this is the last object984.985.IP "\(bu" 4986\fIcollectionLength\fR Length of the collection987.988.IP "" 0989.990.P991For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.992.

Added screencasts pageTj Holowaychukbefore adoption4144af3

lines 993–995why, one step back
993.P
994NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead\. For example do \fInot\fR implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates\.995.

Settings docsTj Holowaychukbefore adoptione562adc

lines 996–1010why, one step back
996.SS "Template Engines"
997Below are a few template engines commonly used with Express:998.999.IP "\(bu" 41000Jade \fIhttp://jade\-lang\.com\fR haml\.js successor1001.1002.IP "\(bu" 41003Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates1004.1005.IP "\(bu" 41006EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript1007.1008.IP "\(bu" 41009CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating1010.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 1011–1013why, one step back
1011.IP "\(bu" 4
1012jQuery Templates \fIhttps://github\.com/kof/node\-jqtpl\fR for node1013.

Settings docsTj Holowaychukbefore adoptione562adc

lines 1014–1416why, one step back
1014.IP "" 0
1015.1016.SS "Session Support"1017Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieDecoder\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.1018.1019.IP "" 41020.1021.nf10221023app\.use(express\.cookieDecoder());1024app\.use(express\.session());1025.1026.fi1027.1028.IP "" 01029.1030.P1031By default the \fIsession\fR middleware uses the memory store bundled with Connect, however many implementations exist\. For example connect\-redis \fIhttp://github\.com/visionmedia/connect\-redis\fR supplies a Redis \fIhttp://code\.google\.com/p/redis/\fR session store and can be used as shown below:1032.1033.IP "" 41034.1035.nf10361037var RedisStore = require(\'connect\-redis\');1038app\.use(express\.cookieDecoder());1039app\.use(express\.session({ store: new RedisStore }));1040.1041.fi1042.1043.IP "" 01044.1045.P1046Now the \fIreq\.session\fR and \fIreq\.sessionStore\fR properties will be accessible to all routes and subsequent middleware\. Properties on \fIreq\.session\fR are automatically saved on a response, so for example if we wish to shopping cart data:1047.1048.IP "" 41049.1050.nf10511052var RedisStore = require(\'connect\-redis\');1053app\.use(express\.bodyDecoder());1054app\.use(express\.cookieDecoder());1055app\.use(express\.session({ store: new RedisStore }));10561057app\.post(\'/add\-to\-cart\', function(req, res){1058 // Perhaps we posted several items with a form1059 // (use the bodyDecoder() middleware for this)1060 var items = req\.body\.items;1061 req\.session\.items = items;1062 res\.redirect(\'back\');1063});10641065app\.get(\'/add\-to\-cart\', function(req, res){1066 // When redirected back to GET /add\-to\-cart1067 // we could check req\.session\.items && req\.session\.items\.length1068 // to print out a message1069 if (req\.session\.items && req\.session\.items\.length) {1070 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);1071 }1072 res\.render(\'shopping\-cart\');1073});1074.1075.fi1076.1077.IP "" 01078.1079.P1080The \fIreq\.session\fR object also has methods such as \fISession#touch()\fR, \fISession#destroy()\fR, \fISession#regenerate()\fR among others to maintain and manipulate sessions\. For more information view the Connect Session \fIhttp://senchalabs\.github\.com/connect/session\.html\fR documentation\.1081.1082.SS "Migration Guide"1083Pre\-beta Express developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.1084.1085.SS "req\.header(key[, defaultValue])"1086Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1087.1088.IP "" 41089.1090.nf10911092req\.header(\'Host\');1093req\.header(\'host\');1094req\.header(\'Accept\', \'*/*\');1095.1096.fi1097.1098.IP "" 01099.1100.SS "req\.accepts(type)"1101Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1102.1103.P1104When the \fIAccept\fR header is not present \fItrue\fR is returned\. Otherwise the given \fItype\fR is matched by an exact match, and then subtypes\. You may pass the subtype such as "html" which is then converted internally to "text/html" using the mime lookup table\.1105.1106.IP "" 41107.1108.nf11091110// Accept: text/html1111req\.accepts(\'html\');1112// => true11131114// Accept: text/*; application/json1115req\.accepts(\'html\');1116req\.accepts(\'text/html\');1117req\.accepts(\'text/plain\');1118req\.accepts(\'application/json\');1119// => true11201121req\.accepts(\'image/png\');1122req\.accepts(\'png\');1123// => false1124.1125.fi1126.1127.IP "" 01128.1129.SS "req\.is(type)"1130Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.1131.1132.IP "" 41133.1134.nf11351136 // With Content\-Type: text/html; charset=utf\-81137 req\.is(\'html\');1138 req\.is(\'text/html\');1139 // => true11401141 // When Content\-Type is application/json1142 req\.is(\'json\');1143 req\.is(\'application/json\');1144 // => true11451146 req\.is(\'html\');1147 // => false1148.1149.fi1150.1151.IP "" 01152.1153.P1154Ad\-hoc callbacks can also be registered with Express, to perform assertions again the request, for example if we need an expressive way to check if our incoming request is an image, we can register \fI"an image"\fR callback:1155.1156.IP "" 41157.1158.nf11591160 app\.is(\'an image\', function(req){1161 return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1162 });1163.1164.fi1165.1166.IP "" 01167.1168.P1169Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1170.1171.IP "" 41172.1173.nf11741175 app\.post(\'/image/upload\', function(req, res, next){1176 if (req\.is(\'an image\')) {1177 // do something1178 } else {1179 next();1180 }1181 });1182.1183.fi1184.1185.IP "" 01186.1187.P1188Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1189.1190.P1191Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1192.1193.IP "" 41194.1195.nf11961197req\.is(\'image/*\');1198.1199.fi1200.1201.IP "" 01202.1203.P1204We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1205.1206.IP "" 41207.1208.nf12091210req\.is(\'*/json\');1211.1212.fi1213.1214.IP "" 01215.1216.SS "req\.param(name)"1217Return the value of param \fIname\fR when present\.1218.1219.IP "\(bu" 41220Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1221.1222.IP "\(bu" 41223Checks query string params (\fIreq\.query\fR), ex: ?id=121224.1225.IP "\(bu" 41226Checks urlencoded body params (\fIreq\.body\fR), ex: id=121227.1228.IP "" 01229.1230.P1231To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.1232.1233.SS "req\.flash(type[, msg])"1234Queue flash \fImsg\fR of the given \fItype\fR\.1235.1236.IP "" 41237.1238.nf12391240req\.flash(\'info\', \'email sent\');1241req\.flash(\'error\', \'email delivery failed\');1242req\.flash(\'info\', \'email re\-sent\');1243// => 212441245req\.flash(\'info\');1246// => [\'email sent\', \'email re\-sent\']12471248req\.flash(\'info\');1249// => []12501251req\.flash();1252// => { error: [\'email delivery failed\'], info: [] }1253.1254.fi1255.1256.IP "" 01257.1258.P1259Flash notification message may also utilize formatters, by default only the %s string formatter is available:1260.1261.IP "" 41262.1263.nf12641265req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1266.1267.fi1268.1269.IP "" 01270.1271.SS "req\.isXMLHttpRequest"1272Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1273.1274.IP "" 41275.1276.nf12771278req\.xhr1279req\.isXMLHttpRequest1280.1281.fi1282.1283.IP "" 01284.1285.SS "res\.header(key[, val])"1286Get or set the response header \fIkey\fR\.1287.1288.IP "" 41289.1290.nf12911292res\.header(\'Content\-Length\');1293// => undefined12941295res\.header(\'Content\-Length\', 123);1296// => 12312971298res\.header(\'Content\-Length\');1299// => 1231300.1301.fi1302.1303.IP "" 01304.1305.SS "res\.contentType(type)"1306Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1307.1308.IP "" 41309.1310.nf13111312 var filename = \'path/to/image\.png\';1313 res\.contentType(filename);1314 // res\.headers[\'Content\-Type\'] is now "image/png"1315.1316.fi1317.1318.IP "" 01319.1320.SS "res\.attachment([filename])"1321Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1322.1323.IP "" 41324.1325.nf13261327 res\.attachment(\'path/to/my/image\.png\');1328.1329.fi1330.1331.IP "" 01332.1333.SS "res\.sendfile(path)"1334Used by \fBres\.download()\fR to transfer an arbitrary file\.1335.1336.IP "" 41337.1338.nf13391340res\.sendfile(\'path/to/my\.file\');1341.1342.fi1343.1344.IP "" 01345.1346.P1347This 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 \fBnot\fR been streamed, \fInext(err)\fR will be called on an exception\.1348.1349.IP "" 41350.1351.nf13521353res\.sendfile(path, function(err, path){1354 if (err) {1355 // handle the error1356 } else {1357 console\.log(\'transferred %s\', path);1358 }1359});1360.1361.fi1362.1363.IP "" 01364.1365.P1366When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.1367.1368.SS "res\.download(file[, filename])"1369Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1370.1371.IP "" 41372.1373.nf13741375res\.download(\'path/to/image\.png\');1376res\.download(\'path/to/image\.png\', \'foo\.png\');1377.1378.fi1379.1380.IP "" 01381.1382.P1383This is equivalent to:1384.1385.IP "" 41386.1387.nf13881389res\.attachment(file);1390res\.sendfile(file);1391.1392.fi1393.1394.IP "" 01395.1396.SS "res\.send(body|status[, headers|status[, status]])"1397The \fBres\.send()\fR method is a high level response utility allowing you to pass objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status code based responses\. The following are all valid uses:1398.1399.IP "" 41400.1401.nf14021403 res\.send(); // 2041404 res\.send(new Buffer(\'wahoo\'));1405 res\.send({ some: \'json\' });1406 res\.send(\'<p>some html</p>\');1407 res\.send(\'Sorry, cant find that\', 404);1408 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1409 res\.send(404);1410.1411.fi1412.1413.IP "" 01414.1415.P1416By default the \fIContent\-Type\fR response header is set, however if explicitly assigned through \fBres\.send()\fR or previously with \fBres\.header()\fR or \fBres\.contentType()\fR it will not be set again\.

Added screencasts pageTj Holowaychukbefore adoption4144af3

lines 1417–1419why, one step back
1417.
1418.P1419Note that this method \fIend()\fR the response, so you will want to use node\'s \fIres\.writeHead()\fR / \fIres\.write()\fR for multiple writes or streaming\.

Settings docsTj Holowaychukbefore adoptione562adc

lines 1420–1511why, one step back
1420.
1421.SS "res\.redirect(url[, status])"1422Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1423.1424.IP "" 41425.1426.nf14271428res\.redirect(\'/\', 301);1429res\.redirect(\'/account\');1430res\.redirect(\'http://google\.com\');1431res\.redirect(\'home\');1432res\.redirect(\'back\');1433.1434.fi1435.1436.IP "" 01437.1438.P1439Express supports "redirect mapping", which by default provides \fIhome\fR, and \fIback\fR\. The \fIback\fR map checks the \fIReferrer\fR and \fIReferer\fR headers, while \fIhome\fR utilizes the "home" setting and defaults to "/"\.1440.1441.SS "res\.cookie(name, val[, options])"1442Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1443.1444.IP "" 41445.1446.nf14471448// "Remember me" for 15 minutes1449res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1450.1451.fi1452.1453.IP "" 01454.1455.P1456To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1457.1458.IP "" 41459.1460.nf14611462app\.use(express\.cookieDecoder());14631464app\.get(\'/\', function(req, res){1465 // use req\.cookies\.rememberme1466});1467.1468.fi1469.1470.IP "" 01471.1472.SS "res\.clearCookie(name)"1473Clear cookie \fIname\fR by setting "expires" far in the past\.1474.1475.IP "" 41476.1477.nf14781479res\.clearCookie(\'rememberme\');1480.1481.fi1482.1483.IP "" 01484.1485.SS "res\.render(view[, options[, fn]])"1486Render \fIview\fR with the given \fIoptions\fR and optional callback \fIfn\fR\. When a callback function is given a response will \fInot\fR be made automatically, however otherwise a response of \fI200\fR and \fItext/html\fR is given\.1487.1488.P1489Most engines accept one or more of the following options, both haml \fIhttp://github\.com/visionmedia/haml\.js\fR and jade \fIhttp://github\.com/visionmedia/jade\fR accept all:1490.1491.IP "\(bu" 41492\fIscope\fR Template evaluation context (value of \fIthis\fR)1493.1494.IP "\(bu" 41495\fIlocals\fR Object containing local variables1496.1497.IP "\(bu" 41498\fIdebug\fR Output debugging information1499.1500.IP "\(bu" 41501\fIstatus\fR Response status code, defaults to 2001502.1503.IP "\(bu" 41504\fIheaders\fR Response headers object1505.1506.IP "" 01507.1508.SS "res\.partial(view[, options])"1509Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1510.1511.IP "\(bu" 4

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

line 1512why, one step back
1512\fIobject\fR the object named by \fIas\fR or derived from the view name

Settings docsTj Holowaychukbefore adoptione562adc

lines 1513–1514why, one step back
1513.
1514.IP "\(bu" 4

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 1515–1517why, one step back
1515\fIas\fR Variable name for each \fIcollection\fR or \fIobject\fR value, defaults to the view name\.
1516.1517.IP "\(bu" 4

Settings docsTj Holowaychukbefore adoptione562adc

lines 1518–1586why, one step back
1518as: \'something\' will add the \fIsomething\fR local variable
1519.1520.IP "\(bu" 41521as: this will use the collection value as the template context1522.1523.IP "\(bu" 41524as: global will merge the collection value\'s properties with \fIlocals\fR1525.1526.IP "" 015271528.1529.IP "\(bu" 41530\fIcollection\fR Array of objects, the name is derived from the view name itself\. For example \fIvideo\.html\fR will have a object \fIvideo\fR available to it\.1531.1532.IP "" 01533.1534.P1535The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1536.1537.IP "" 41538.1539.nf15401541partial(\'theatre/movie\.jade\', { collection: movies });1542partial(\'theatre/movie\.jade\', movies);1543partial(\'movie\.jade\', { collection: movies });1544partial(\'movie\.jade\', movies);1545partial(\'movie\', movies);1546// In view: movie\.director1547.1548.fi1549.1550.IP "" 01551.1552.P1553To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1554.1555.IP "" 41556.1557.nf15581559partial(\'movie\', { collection: movies, as: \'video\' });1560// In view: video\.director1561.1562.fi1563.1564.IP "" 01565.1566.P1567Also we can make our movie the value of \fIthis\fR within our view so that instead of \fImovie\.director\fR we could use \fIthis\.director\fR\.1568.1569.IP "" 41570.1571.nf15721573partial(\'movie\', { collection: movies, as: this });1574// In view: this\.director1575.1576.fi1577.1578.IP "" 01579.1580.P1581Another alternative is to "explode" the properties of the collection item into pseudo globals (local variables) by using \fIas: global\fR, which again is syntactic sugar:1582.1583.IP "" 41584.1585.nf1586

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

line 1587why, one step back
1587partial(\'movie\', { collection: movies, as: global });

Settings docsTj Holowaychukbefore adoptione562adc

lines 1588–1593why, one step back
1588// In view: director
1589.1590.fi1591.1592.IP "" 01593.

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 1594–1630why, one step back
1594.P
1595This same logic applies to a single partial object usage:1596.1597.IP "" 41598.1599.nf16001601partial(\'movie\', { object: movie, as: this });1602// In view: this\.director16031604partial(\'movie\', { object: movie, as: global });1605// In view: director16061607partial(\'movie\', { object: movie, as: \'video\' });1608// In view: video\.director16091610partial(\'movie\', { object: movie });1611// In view: movie\.director1612.1613.fi1614.1615.IP "" 01616.1617.P1618When a non\-collection (does \fInot\fR have \fI\.length\fR) is passed as the second argument, it is assumed to be the \fIobject\fR, after which the object\'s local variable name is derived from the view name:1619.1620.IP "" 41621.1622.nf16231624partial(\'movie\', movie);1625// => In view: movie\.director1626.1627.fi1628.1629.IP "" 01630.

Re-built docsTj Holowaychukbefore adoption8e63d04

lines 1631–1654why, one step back
1631.SS "res\.local(name[, val])"
1632Get or set the given local variable \fIname\fR\. The locals built up for a response are applied to those given to the view rendering methods such as \fBres\.render()\fR\.1633.1634.IP "" 41635.1636.nf16371638 app\.all(\'/movie/:id\', function(req, res, next){1639 Movie\.get(req\.params\.id, function(err, movie){1640 // Assigns res\.locals\.movie = movie1641 res\.local(\'movie\', movie);1642 });1643 });16441645 app\.get(\'/movie/:id\', function(req, res){1646 // movie is already a local, however we1647 // can pass more if we wish1648 res\.render(\'movie\', { displayReviews: true });1649 });1650.1651.fi1652.1653.IP "" 01654.

Settings docsTj Holowaychukbefore adoptione562adc

lines 1655–1663why, one step back
1655.SS "app\.set(name[, val])"
1656Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1657.1658.IP "" 41659.1660.nf16611662app\.set(\'views\', __dirname + \'/views\');1663app\.set(\'views\');

Rebuilt docsTj Holowaychukbefore adoptiond017c3e

lines 1664–1677why, one step back
1664// => \.\.\.path\.\.\.
1665.1666.fi1667.1668.IP "" 01669.1670.P1671Alternatively you may simply access the settings via \fIapp\.settings\fR:1672.1673.IP "" 41674.1675.nf16761677app\.settings\.views

Settings docsTj Holowaychukbefore adoptione562adc

lines 1678–1693why, one step back
1678// => \.\.\.path\.\.\.
1679.1680.fi1681.1682.IP "" 01683.1684.SS "app\.enable(name)"1685Enable the given setting \fIname\fR:1686.1687.IP "" 41688.1689.nf16901691app\.enable(\'some arbitrary setting\');1692app\.set(\'some arbitrary setting\');1693// => true

Re-built docsTj Holowaychukbefore adoption8e63d04

lines 1694–1696why, one step back
1694
1695app\.enabled(\'some arbitrary setting\');1696// => true

Settings docsTj Holowaychukbefore adoptione562adc

lines 1697–1710why, one step back
1697.
1698.fi1699.1700.IP "" 01701.1702.SS "app\.disable(name)"1703Disable the given setting \fIname\fR:1704.1705.IP "" 41706.1707.nf17081709app\.disable(\'some setting\');1710app\.set(\'some setting\');

Re-built docsTj Holowaychukbefore adoption8e63d04

lines 1711–1713why, one step back
1711// => false
17121713app\.disabled(\'some setting\');

Settings docsTj Holowaychukbefore adoptione562adc

lines 1714–1975why, one step back
1714// => false
1715.1716.fi1717.1718.IP "" 01719.1720.SS "app\.configure(env|function[, function])"1721Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1722.1723.IP "" 41724.1725.nf17261727app\.configure(function(){1728 // executed for each env1729});17301731app\.configure(\'development\', function(){1732 // executed for \'development\' only1733});1734.1735.fi1736.1737.IP "" 01738.1739.SS "app\.redirect(name, val)"1740For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1741.1742.IP "" 41743.1744.nf17451746app\.redirect(\'google\', \'http://google\.com\');1747.1748.fi1749.1750.IP "" 01751.1752.P1753Now in a route we may call:1754.1755.P1756res\.redirect(\'google\');1757.1758.P1759We may also map dynamic redirects:1760.1761.IP "" 41762.1763.nf17641765app\.redirect(\'comments\', function(req, res){1766 return \'/post/\' + req\.params\.id + \'/comments\';1767});1768.1769.fi1770.1771.IP "" 01772.1773.P1774So now we may do the following, and the redirect will dynamically adjust to the context of the request\. If we called this route with \fIGET /post/12\fR our redirect \fILocation\fR would be \fI/post/12/comments\fR\.1775.1776.IP "" 41777.1778.nf17791780app\.get(\'/post/:id\', function(req, res){1781 res\.redirect(\'comments\');1782});1783.1784.fi1785.1786.IP "" 01787.1788.SS "app\.error(function)"1789Adds an error handler \fIfunction\fR which will receive the exception as the first parameter as shown below\. Note that we may set several error handlers by making several calls to this method, however the handler should call \fInext(err)\fR if it does not wish to deal with the exception:1790.1791.IP "" 41792.1793.nf17941795app\.error(function(err, req, res, next){1796 res\.send(err\.message, 500);1797});1798.1799.fi1800.1801.IP "" 01802.1803.SS "app\.helpers(obj)"1804Registers static view helpers\.1805.1806.IP "" 41807.1808.nf18091810app\.helpers({1811 name: function(first, last){ return first + \', \' + last },1812 firstName: \'tj\',1813 lastName: \'holowaychuk\'1814});1815.1816.fi1817.1818.IP "" 01819.1820.P1821Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1822.1823.IP "" 41824.1825.nf18261827<%= name(firstName, lastName) %>1828.1829.fi1830.1831.IP "" 01832.1833.SS "app\.dynamicHelpers(obj)"1834Registers dynamic view helpers\. Dynamic view helpers are simply functions which accept \fIreq\fR, \fIres\fR, and are evaluated against the \fIServer\fR instance before a view is rendered\. The \fIreturn value\fR of this function becomes the local variable it is associated with\.1835.1836.IP "" 41837.1838.nf18391840app\.dynamicHelpers({1841 session: function(req, res){1842 return req\.session;1843 }1844});1845.1846.fi1847.1848.IP "" 01849.1850.P1851All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1852.1853.IP "" 41854.1855.nf18561857<%= session\.name %>1858.1859.fi1860.1861.IP "" 01862.1863.SS "app\.mounted(fn)"1864Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1865.1866.IP "" 41867.1868.nf18691870var app = express\.createServer(),1871 blog = express\.createServer();18721873blog\.mounted(function(parent){1874 // parent is app1875 // "this" is blog1876});18771878app\.use(blog);1879.1880.fi1881.1882.IP "" 01883.1884.SS "app\.register(ext, exports)"1885Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:1886.1887.IP "" 41888.1889.nf18901891 app\.register(\'\.html\', require(\'jade\'));1892.1893.fi1894.1895.IP "" 01896.1897.P1898This is also useful for libraries that may not match extensions correctly\. For example my haml\.js library is installed from npm as "hamljs" so instead of layout\.hamljs, we can register the engine as "\.haml":1899.1900.IP "" 41901.1902.nf19031904 app\.register(\'\.haml\', require(\'haml\-js\'));1905.1906.fi1907.1908.IP "" 01909.1910.P1911For engines that do not comply with the Express specification, we can also wrap their api this way\.1912.1913.IP "" 41914.1915.nf19161917 app\.register(\'\.foo\', {1918 render: function(str, options) {1919 // perhaps their api is1920 // return foo\.toHTML(str, options);1921 }1922 });1923.1924.fi1925.1926.IP "" 01927.1928.SS "app\.listen([port[, host]])"1929Bind the app server to the given \fIport\fR, which defaults to 3000\. When \fIhost\fR is omitted all connections will be accepted via \fIINADDR_ANY\fR\.1930.1931.IP "" 41932.1933.nf19341935app\.listen();1936app\.listen(3000);1937app\.listen(3000, \'n\.n\.n\.n\');1938.1939.fi1940.1941.IP "" 01942.1943.P1944The \fIport\fR argument may also be a string representing the path to a unix domain socket:1945.1946.IP "" 41947.1948.nf19491950app\.listen(\'/tmp/express\.sock\');1951.1952.fi1953.1954.IP "" 01955.1956.P1957Then try it out:1958.1959.IP "" 41960.1961.nf19621963$ telnet /tmp/express\.sock1964GET / HTTP/1\.119651966HTTP/1\.1 200 OK1967Content\-Type: text/plain1968Content\-Length: 1119691970Hello World1971.1972.fi1973.1974.IP "" 01975