Skip to content
Myr

guide.1

This file

Path

docs/guide.1

2,099 lines · 45.7 KiB

Last changed by

docsTj Holowaychukbefore adoption131970b

History of this file

Take it

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

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 4why, one step back
4.TH "GUIDE" "" "March 2011" "" ""

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 5–12why, one step back
5.
6.SH "NAME"7\fBguide\fR8.9.SS "Installation"10.11.nf12

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 13why, one step back
13$ npm install express

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 14–16why, one step back
14.
15.fi16.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 17–18why, one step back
17.SS "Creating A Server"
18To create an instance of the \fIexpress\.HTTPServer\fR, simply invoke the \fIcreateServer()\fR method\. With our instance \fIapp\fR we can then define routes based on the HTTP verbs, in this example \fIapp\.get()\fR\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 19–23why, one step back
19.
20.IP "" 421.22.nf23

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 24–30why, one step back
24var app = require(\'express\')\.createServer();
2526app\.get(\'/\', function(req, res){27 res\.send(\'hello world\');28});2930app\.listen(3000);

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 31–35why, one step back
31.
32.fi33.34.IP "" 035.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 36–37why, one step back
36.SS "Creating An HTTPS Server"
37To initialize a \fIexpress\.HTTPSServer\fR we do the same as above, however we pass an options object, accepting \fIkey\fR, \fIcert\fR and the others mentioned in node\'s https documentation \fIhttp://nodejs\.org/docs/v0\.3\.7/api/https\.html#https\.createServer\fR\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 38–42why, one step back
38.
39.IP "" 440.41.nf42

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 43why, one step back
43 var app = require(\'express\')\.createServer({ key: \.\.\. });

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 44–52why, one step back
44.
45.fi46.47.IP "" 048.49.SS "Configuration"50Express 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\.51.52.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 53why, one step back
53In 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 \fIbodyParser\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()\fR, \fIapp\.post()\fR, etc will mount the routes\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 54–60why, one step back
54.
55.IP "" 456.57.nf5859app\.configure(function(){60 app\.use(express\.methodOverride());

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 61why, one step back
61 app\.use(express\.bodyParser());

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 62–65why, one step back
62 app\.use(app\.router);
63});6465app\.configure(\'development\', function(){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 66why, one step back
66 app\.use(express\.static(__dirname + \'/public\'));

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 67–70why, one step back
67 app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));
68});6970app\.configure(\'production\', function(){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 71–73why, one step back
71 var oneYear = 31557600000;
72 app\.use(express\.static({ root: __dirname + \'/public\', maxAge: oneYear }));73 app\.use(express\.errorHandler());

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 74–86why, one step back
74});
75.76.fi77.78.IP "" 079.80.P81For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:82.83.IP "" 484.85.nf86

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 87why, one step back
87 app\.configure(function(){

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 88–89why, one step back
88 app\.set(\'views\', __dirname + \'/views\');
89 app\.set(\'views\');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 90why, one step back
90 // => "/absolute/path/to/views"

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 91–96why, one step back
91
92 app\.enable(\'some feature\');93 // same as app\.set(\'some feature\', true);9495 app\.disable(\'some feature\');96 // same as app\.set(\'some feature\', false);

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 97–100why, one step back
97
98 app\.enabled(\'some feature\')99 // => false100 });

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 101–167why, one step back
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\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.127.128.IP "\(bu" 4129\fIviews\fR Root views directory defaulting to \fBCWD/views\fR130.131.IP "\(bu" 4132\fIview engine\fR Default view engine name for views rendered without extensions133.134.IP "\(bu" 4135\fIview options\fR An object specifying global view options136.137.IP "" 0138.139.SS "Routing"140Express 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\.141.142.IP "" 4143.144.nf145146app\.get(\'/user/:id\', function(req, res){147 res\.send(\'user \' + req\.params\.id);148});149.150.fi151.152.IP "" 0153.154.P155A 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:156.157.IP "" 4158.159.nf160161\e/user\e/([^\e/]+)\e/?162.163.fi164.165.IP "" 0166.167.P

Regenerated docsTj Holowaychukbefore adoptiond3abcaf

line 168why, one step back
168Regular 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\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 169–235why, one step back
169.
170.IP "" 4171.172.nf173174app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){175 res\.send(req\.params);176});177.178.fi179.180.IP "" 0181.182.P183Curl requests against the previously defined route:184.185.IP "" 4186.187.nf188189 $ curl http://dev:3000/user190 [null,null]191 $ curl http://dev:3000/users192 [null,null]193 $ curl http://dev:3000/users/1194 ["1",null]195 $ curl http://dev:3000/users/1\.\.15196 ["1","15"]197.198.fi199.200.IP "" 0201.202.P203Below are some route examples, and the associated paths that they may consume:204.205.IP "" 4206.207.nf208209 "/user/:id"210 /user/12211212 "/users/:id?"213 /users/5214 /users215216 "/files/*"217 /files/jquery\.js218 /files/javascripts/jquery\.js219220 "/file/*\.*"221 /files/jquery\.js222 /files/javascripts/jquery\.js223224 "/user/:id/:operation?"225 /user/1226 /user/1/edit227228 "/products\.:format"229 /products\.json230 /products\.xml231232 "/products\.:format?"233 /products\.json234 /products\.xml235 /products

Regenerated docsTj Holowaychukbefore adoptiond3abcaf

lines 236–239why, one step back
236
237 "/user/:id\.:format?"238 /user/12239 /user/12\.json

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 240–245why, one step back
240.
241.fi242.243.IP "" 0244.245.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 246why, one step back
246For example we can \fBPOST\fR some json, and echo the json back using the \fIbodyParser\fR middleware which will parse json request bodies (as well as others), and place the result in \fIreq\.body\fR:

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 247–254why, one step back
247.
248.IP "" 4249.250.nf251252var express = require(\'express\')253 , app = express\.createServer();254

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 255why, one step back
255app\.use(express\.bodyParser());

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 256–265why, one step back
256
257app\.post(\'/\', function(req, res){258 res\.send(req\.body);259});260261app\.listen(3000);262.263.fi264.265.IP "" 0

Regenerated docsTj Holowaychukbefore adoptiond3abcaf

lines 266–267why, one step back
266.
267.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 268why, one step back
268Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, 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\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 269–270why, one step back
269.
270.SS "Passing Route Control"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 271why, one step back
271We 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 in the order that they are added via \fIuse()\fR\. 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 and decides to respond\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 272–294why, one step back
272.
273.IP "" 4274.275.nf276277app\.get(\'/users/:id?\', function(req, res, next){278 var id = req\.params\.id;279 if (id) {280 // do something281 } else {282 next();283 }284});285286app\.get(\'/users\', function(req, res){287 // do something else288});289.290.fi291.292.IP "" 0293.294.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 295why, one step back
295The \fIapp\.all()\fR method is useful for applying the same logic for all HTTP verbs in a single call\. Below we use this to load a user from our fake database, and assign it to \fIreq\.user\fR\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 296–346why, one step back
296.
297.IP "" 4298.299.nf300301var express = require(\'express\')302 , app = express\.createServer();303304var users = [{ name: \'tj\' }];305306app\.all(\'/user/:id/:op?\', function(req, res, next){307 req\.user = users[req\.params\.id];308 if (req\.user) {309 next();310 } else {311 next(new Error(\'cannot find user \' + req\.params\.id));312 }313});314315app\.get(\'/user/:id\', function(req, res){316 res\.send(\'viewing \' + req\.user\.name);317});318319app\.get(\'/user/:id/edit\', function(req, res){320 res\.send(\'editing \' + req\.user\.name);321});322323app\.put(\'/user/:id\', function(req, res){324 res\.send(\'updating \' + req\.user\.name);325});326327app\.get(\'*\', function(req, res){328 res\.send(\'what???\', 404);329});330331app\.listen(3000);332.333.fi334.335.IP "" 0336.337.SS "Middleware"338Middleware 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:339.340.IP "" 4341.342.nf343344 var express = require(\'express\');345346var app = express\.createServer(

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 347–348why, one step back
347 express\.logger()
348 , express\.bodyParser()

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 349–355why, one step back
349 );
350.351.fi352.353.IP "" 0354.355.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 356why, one step back
356Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks, in a progressive manor\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 357–376why, one step back
357.
358.IP "" 4359.360.nf361362app\.use(express\.logger({ format: \':method :uri\' }));363.364.fi365.366.IP "" 0367.368.P369Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:370.371.IP "" 4372.373.nf374375var connect = require(\'connect\');376app\.use(connect\.logger());

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 377why, one step back
377app\.use(connect\.bodyParser());

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 378–390why, one step back
378.
379.fi380.381.IP "" 0382.383.P384This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:385.386.IP "" 4387.388.nf389390app\.use(express\.logger());

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 391why, one step back
391app\.use(express\.bodyParser());

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 392–407why, one step back
392.
393.fi394.395.IP "" 0396.397.SS "Route Middleware"398Routes 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\.399.400.P401Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.402.403.IP "" 4404.405.nf406407app\.get(\'/user/:id\', function(req, res, next){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 408–411why, one step back
408 loadUser(req\.params\.id, function(err, user){
409 if (err) return next(err);410 res\.send(\'Viewing user \' + user\.name);411 });

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 412–425why, one step back
412});
413.414.fi415.416.IP "" 0417.418.P419To 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\.420.421.IP "" 4422.423.nf424425function loadUser(req, res, next) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 426–433why, one step back
426 // You would fetch your user from the db
427 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 }

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 434–436why, one step back
434}
435436app\.get(\'/user/:id\', loadUser, function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 437why, one step back
437 res\.send(\'Viewing user \' + req\.user\.name);

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 438–451why, one step back
438});
439.440.fi441.442.IP "" 0443.444.P445Multiple 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\.446.447.IP "" 4448.449.nf450451function andRestrictToSelf(req, res, next) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 452–454why, one step back
452 req\.authenticatedUser\.id == req\.user\.id
453 ? next()454 : next(new Error(\'Unauthorized\'));

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 455–457why, one step back
455}
456457app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 458why, one step back
458 res\.send(\'Editing user \' + req\.user\.name);

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 459–472why, one step back
459});
460.461.fi462.463.IP "" 0464.465.P466Keeping 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\.467.468.IP "" 4469.470.nf471472function andRestrictTo(role) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 473–477why, one step back
473 return function(req, res, next) {
474 req\.authenticatedUser\.role == role475 ? next()476 : next(new Error(\'Unauthorized\'));477 }

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 478–480why, one step back
478}
479480app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 481why, one step back
481 res\.send(\'Deleted user \' + req\.user\.name);

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 482–533why, one step back
482});
483.484.fi485.486.IP "" 0487.488.P489Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.490.491.IP "" 4492.493.nf494495var a = [middleware1, middleware2]496 , b = [middleware3, middleware4]497 , all = [a, b];498499app\.get(\'/foo\', a, function(){});500app\.get(\'/bar\', a, function(){});501502app\.get(\'/\', a, middleware3, middleware4, function(){});503app\.get(\'/\', a, b, function(){});504app\.get(\'/\', all, function(){});505.506.fi507.508.IP "" 0509.510.P511For 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\.512.513.SS "HTTP Methods"514We 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\.515.516.P517A 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\.518.519.IP "" 4520.521.nf522523 <form method="post" action="/">524 <input type="text" name="user[name]" />525 <input type="text" name="user[email]" />526 <input type="submit" value="Submit" />527 </form>528.529.fi530.531.IP "" 0532.533.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 534why, one step back
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:

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 535–539why, one step back
535.
536.IP "" 4537.538.nf539

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 540why, one step back
540app\.use(express\.bodyParser());

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 541–553why, one step back
541.
542.fi543.544.IP "" 0545.546.P547Our 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\.548.549.IP "" 4550.551.nf552553app\.post(\'/\', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 554–555why, one step back
554 console\.log(req\.body\.user);
555 res\.redirect(\'back\');

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 556–562why, one step back
556});
557.558.fi559.560.IP "" 0561.562.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 563why, one step back
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\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 564–568why, one step back
564.
565.IP "" 4566.567.nf568

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 569why, one step back
569app\.use(express\.bodyParser());

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 570–606why, one step back
570app\.use(express\.methodOverride());
571.572.fi573.574.IP "" 0575.576.P577The 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:578.579.IP "" 4580.581.nf582583<form method="post" action="/">584 <input type="hidden" name="_method" value="put" />585 <input type="text" name="user[name]" />586 <input type="text" name="user[email]" />587 <input type="submit" value="Submit" />588</form>589590app\.put(\'/\', function(){591 console\.log(req\.body\.user);592 res\.redirect(\'back\');593});594.595.fi596.597.IP "" 0598.599.SS "Error Handling"600Express 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:601.602.IP "" 4603.604.nf605606function NotFound(msg){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 607–609why, one step back
607 this\.name = \'NotFound\';
608 Error\.call(this, msg);609 Error\.captureStackTrace(this, arguments\.callee);

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 610–611why, one step back
610}
611

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 612why, one step back
612NotFound\.protoype\.__proto__ = Error\.prototype;

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 613–614why, one step back
613
614app\.get(\'/404\', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 615why, one step back
615 throw new NotFound;

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 616–618why, one step back
616});
617618app\.get(\'/500\', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 619why, one step back
619 throw new Error(\'keyboard cat!\');

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 620–648why, one step back
620});
621.622.fi623.624.IP "" 0625.626.P627We 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\.628.629.P630Note 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\.631.632.IP "" 4633.634.nf635636app\.error(function(err, req, res, next){637 if (err instanceof NotFound) {638 res\.render(\'404\.jade\');639 } else {640 next(err);641 }642});643.644.fi645.646.IP "" 0647.648.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 649why, one step back
649Here 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\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 650–655why, one step back
650.
651.IP "" 4652.653.nf654655app\.error(function(err, req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 656–658why, one step back
656 res\.render(\'500\.jade\', {
657 error: err658 });

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 659–693why, one step back
659});
660.661.fi662.663.IP "" 0664.665.P666Our 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:667.668.IP "" 4669.670.nf671672app\.use(express\.errorHandler({ dumpExceptions: true }));673.674.fi675.676.IP "" 0677.678.P679Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:680.681.IP "" 4682.683.nf684685app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));686.687.fi688.689.IP "" 0690.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.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 694–695why, one step back
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:

Route precondition docsTj Holowaychukbefore adoptionfd2f67b

lines 696–712why, one step back
696.
697.IP "" 4698.699.nf700701app\.get(\'/user/:userId\', function(req, res, next){702 User\.get(req\.params\.userId, function(err, user){703 if (err) return next(err);704 res\.send(\'user \' + user\.name);705 });706});707.708.fi709.710.IP "" 0711.712.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 713why, one step back
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\.

Route precondition docsTj Holowaychukbefore adoptionfd2f67b

lines 714–772why, one step back
714.
715.IP "" 4716.717.nf718719app\.param(\'userId\', function(req, res, next, id){720 User\.get(id, function(err, user){721 if (err) return next(err);722 if (!user) return next(new Error(\'failed to find user\'));723 req\.user = user;724 next();725 });726});727.728.fi729.730.IP "" 0731.732.P733Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:734.735.IP "" 4736.737.nf738739app\.get(\'/user/:userId\', function(req, res){740 res\.send(\'user \' + req\.user\.name);741});742.743.fi744.745.IP "" 0746.747.P748For 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\.749.750.IP "" 4751.752.nf753754app\.param(\'number\', function(n){ return parseInt(n, 10); });755.756.fi757.758.IP "" 0759.760.P761We 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:762.763.IP "" 4764.765.nf766767app\.param([\'from\', \'to\'], function(n){ return parseInt(n, 10); });768.769.fi770.771.IP "" 0772.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

line 773why, one step back
773.SS "View Rendering"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 774why, one step back
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\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 775–776why, one step back
775.
776.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 777why, one step back
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\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 778–783why, one step back
778.
779.IP "" 4780.781.nf782783app\.get(\'/\', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 784why, one step back
784 res\.render(\'index\.jade\', { title: \'My Site\' });

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 785–791why, one step back
785});
786.787.fi788.789.IP "" 0790.791.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 792why, one step back
792The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using jade we could set:

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 793–850why, one step back
793.
794.IP "" 4795.796.nf797798app\.set(\'view engine\', \'jade\');799.800.fi801.802.IP "" 0803.804.P805Allowing us to render with:806.807.IP "" 4808.809.nf810811res\.render(\'index\');812.813.fi814.815.IP "" 0816.817.P818vs:819.820.IP "" 4821.822.nf823824res\.render(\'index\.jade\');825.826.fi827.828.IP "" 0829.830.P831When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:832.833.IP "" 4834.835.nf836837res\.render(\'another\-page\.ejs\');838.839.fi840.841.IP "" 0842.843.P844Express 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:845.846.IP "" 4847.848.nf849850app\.set(\'view options\', {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 851why, one step back
851 layout: false

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 852–858why, one step back
852});
853.854.fi855.856.IP "" 0857.858.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 859why, one step back
859Which can then be overridden within the \fIres\.render()\fR call if need be:

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 860–926why, one step back
860.
861.IP "" 4862.863.nf864865res\.render(\'myview\.ejs\', { layout: true });866.867.fi868.869.IP "" 0870.871.P872When 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:873.874.IP "" 4875.876.nf877878res\.render(\'page\', { layout: \'mylayout\' });879.880.fi881.882.IP "" 0883.884.P885Otherwise we must specify the extension:886.887.IP "" 4888.889.nf890891res\.render(\'page\', { layout: \'mylayout\.jade\' });892.893.fi894.895.IP "" 0896.897.P898These paths may also be absolute:899.900.IP "" 4901.902.nf903904res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });905.906.fi907.908.IP "" 0909.910.P911A good example of this is specifying custom \fIejs\fR opening and closing tags:912.913.IP "" 4914.915.nf916917app\.set(\'view options\', {918 open: \'{{\',919 close: \'}}\'920});921.922.fi923.924.IP "" 0925.926.SS "View Partials"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 927why, one step back
927The Express view system has built\-in support for partials and collections, which are "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:

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 928–939why, one step back
928.
929.IP "" 4930.931.nf932933partial(\'comment\', { collection: comments });934.935.fi936.937.IP "" 0938.939.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 940why, one step back
940If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 941–955why, one step back
941.
942.IP "" 4943.944.nf945946partial(\'comment\', comments);947.948.fi949.950.IP "" 0951.952.P953When using the partial collection support a few "magic" variables are provided for free:954.955.IP "\(bu" 4

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 956why, one step back
956\fIfirstInCollection\fR true if this is the first object

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 957–958why, one step back
957.
958.IP "\(bu" 4

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 959why, one step back
959\fIindexInCollection\fR index of the object in the collection

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 960–961why, one step back
960.
961.IP "\(bu" 4

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 962why, one step back
962\fIlastInCollection\fR true if this is the last object

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 963–964why, one step back
963.
964.IP "\(bu" 4

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 965why, one step back
965\fIcollectionLength\fR length of the collection

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 966–969why, one step back
966.
967.IP "" 0968.969.P

docsTj Holowaychukbefore adoption4609984

lines 970–972why, one step back
970Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well\. So for example if we were to render a blog post with \fIpartial(\'blog/post\', post)\fR it would generate the \fIpost\fR local, but the view calling this function had the local \fIuser\fR, it would be available to the \fIblog/post\fR view as well\.
971.972.P

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 973–974why, one step back
973For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.
974.

Added screencasts pageTj Holowaychukbefore adoption4144af3

line 975why, one step back
975.P

view lookup docsTj Holowaychukbefore adoption8a62f8c

lines 976–982why, one step back
976\fBNOTE:\fR be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views\. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead\.
977.978.SS "View Lookup"979View lookup is performed relative to the parent view, for example if we had a page view named \fIviews/user/list\.jade\fR, and within that view we did \fIpartial(\'edit\')\fR it would attempt to load \fIviews/user/edit\.jade\fR, whereas \fIpartial(\'\.\./messages\')\fR would load \fIviews/messages\.jade\fR\.980.981.P982The view system also allows for index templates, allowing you to have a directory of the same name\. For example within a route we may have \fIres\.render(\'users\')\fR either \fIviews/users\.jade\fR, or \fIviews/users/index\.jade\fR\.

Added screencasts pageTj Holowaychukbefore adoption4144af3

line 983why, one step back
983.

more docsTj Holowaychukbefore adoption0b6a941

lines 984–986why, one step back
984.P
985When utilizing index views as shown above, we may reference \fIviews/users/index\.jade\fR from a view in the same directory by \fIpartial(\'users\')\fR, and the view system will try \fI\.\./users/index\fR, preventing us from needing to call \fIpartial(\'index\')\fR\.986.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 987–1004why, one step back
987.SS "Template Engines"
988Below are a few template engines commonly used with Express:989.990.IP "\(bu" 4991Jade \fIhttp://jade\-lang\.com\fR haml\.js successor992.993.IP "\(bu" 4994EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript995.996.IP "\(bu" 4997CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating998.999.IP "\(bu" 41000jQuery Templates \fIhttps://github\.com/kof/node\-jqtpl\fR for node1001.1002.IP "" 01003.1004.SS "Session Support"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1005why, one step back
1005Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieParser\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1006–1010why, one step back
1006.
1007.IP "" 41008.1009.nf1010

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1011–1012why, one step back
1011app\.use(express\.cookieParser());
1012app\.use(express\.session({ secret: "keyboard cat" }));

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1013–1025why, one step back
1013.
1014.fi1015.1016.IP "" 01017.1018.P1019By 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:1020.1021.IP "" 41022.1023.nf10241025var RedisStore = require(\'connect\-redis\');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1026–1027why, one step back
1026app\.use(express\.cookieParser());
1027app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1028–1040why, one step back
1028.
1029.fi1030.1031.IP "" 01032.1033.P1034Now 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:1035.1036.IP "" 41037.1038.nf10391040var RedisStore = require(\'connect\-redis\');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1041–1043why, one step back
1041app\.use(express\.bodyParser());
1042app\.use(express\.cookieParser());1043app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1044–1046why, one step back
1044
1045app\.post(\'/add\-to\-cart\', function(req, res){1046 // Perhaps we posted several items with a form

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1047why, one step back
1047 // (use the bodyParser() middleware for this)

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1048–1067why, one step back
1048 var items = req\.body\.items;
1049 req\.session\.items = items;1050 res\.redirect(\'back\');1051});10521053app\.get(\'/add\-to\-cart\', function(req, res){1054 // When redirected back to GET /add\-to\-cart1055 // we could check req\.session\.items && req\.session\.items\.length1056 // to print out a message1057 if (req\.session\.items && req\.session\.items\.length) {1058 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);1059 }1060 res\.render(\'shopping\-cart\');1061});1062.1063.fi1064.1065.IP "" 01066.1067.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1068why, one step back
1068The \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/middleware\-session\.html\fR documentation\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

line 1069why, one step back
1069.

docsTj Holowaychukbefore adoption5581ca2

line 1070why, one step back
1070.SS "Migration Guide"

docsTj Holowaychukbefore adoptionc1a82bf

line 1071why, one step back
1071Express 1\.x developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application to work with Express 2\.x, Connect 1\.x, and Node 0\.4\.x\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1072–1087why, one step back
1072.
1073.SS "req\.header(key[, defaultValue])"1074Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1075.1076.IP "" 41077.1078.nf10791080req\.header(\'Host\');1081req\.header(\'host\');1082req\.header(\'Accept\', \'*/*\');1083.1084.fi1085.1086.IP "" 01087.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1088–1106why, one step back
1088.P
1089The \fIReferrer\fR and \fIReferer\fR header fields are special\-cased, either will work:1090.1091.IP "" 41092.1093.nf10941095// sent Referrer: http://google\.com10961097req\.header(\'Referer\');1098// => "http://google\.com"10991100req\.header(\'Referrer\');1101// => "http://google\.com"1102.1103.fi1104.1105.IP "" 01106.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1107–1222why, one step back
1107.SS "req\.accepts(type)"
1108Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1109.1110.P1111When 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\.1112.1113.IP "" 41114.1115.nf11161117// Accept: text/html1118req\.accepts(\'html\');1119// => true11201121// Accept: text/*; application/json1122req\.accepts(\'html\');1123req\.accepts(\'text/html\');1124req\.accepts(\'text/plain\');1125req\.accepts(\'application/json\');1126// => true11271128req\.accepts(\'image/png\');1129req\.accepts(\'png\');1130// => false1131.1132.fi1133.1134.IP "" 01135.1136.SS "req\.is(type)"1137Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.1138.1139.IP "" 41140.1141.nf11421143 // With Content\-Type: text/html; charset=utf\-81144 req\.is(\'html\');1145 req\.is(\'text/html\');1146 // => true11471148 // When Content\-Type is application/json1149 req\.is(\'json\');1150 req\.is(\'application/json\');1151 // => true11521153 req\.is(\'html\');1154 // => false1155.1156.fi1157.1158.IP "" 01159.1160.P1161Ad\-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:1162.1163.IP "" 41164.1165.nf11661167 app\.is(\'an image\', function(req){1168 return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1169 });1170.1171.fi1172.1173.IP "" 01174.1175.P1176Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1177.1178.IP "" 41179.1180.nf11811182 app\.post(\'/image/upload\', function(req, res, next){1183 if (req\.is(\'an image\')) {1184 // do something1185 } else {1186 next();1187 }1188 });1189.1190.fi1191.1192.IP "" 01193.1194.P1195Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1196.1197.P1198Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1199.1200.IP "" 41201.1202.nf12031204req\.is(\'image/*\');1205.1206.fi1207.1208.IP "" 01209.1210.P1211We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1212.1213.IP "" 41214.1215.nf12161217req\.is(\'*/json\');1218.1219.fi1220.1221.IP "" 01222.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1223–1224why, one step back
1223.SS "req\.param(name[, default])"
1224Return the value of param \fIname\fR when present or \fIdefault\fR\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1225–1226why, one step back
1225.
1226.IP "\(bu" 4

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1227why, one step back
1227Checks route params (\fIreq\.params\fR), ex: /user/:id

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1228–1237why, one step back
1228.
1229.IP "\(bu" 41230Checks query string params (\fIreq\.query\fR), ex: ?id=121231.1232.IP "\(bu" 41233Checks urlencoded body params (\fIreq\.body\fR), ex: id=121234.1235.IP "" 01236.1237.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1238why, one step back
1238To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the _express\.bodyParser middleware\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1239–1320why, one step back
1239.
1240.SS "req\.flash(type[, msg])"1241Queue flash \fImsg\fR of the given \fItype\fR\.1242.1243.IP "" 41244.1245.nf12461247req\.flash(\'info\', \'email sent\');1248req\.flash(\'error\', \'email delivery failed\');1249req\.flash(\'info\', \'email re\-sent\');1250// => 212511252req\.flash(\'info\');1253// => [\'email sent\', \'email re\-sent\']12541255req\.flash(\'info\');1256// => []12571258req\.flash();1259// => { error: [\'email delivery failed\'], info: [] }1260.1261.fi1262.1263.IP "" 01264.1265.P1266Flash notification message may also utilize formatters, by default only the %s string formatter is available:1267.1268.IP "" 41269.1270.nf12711272req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1273.1274.fi1275.1276.IP "" 01277.1278.SS "req\.isXMLHttpRequest"1279Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1280.1281.IP "" 41282.1283.nf12841285req\.xhr1286req\.isXMLHttpRequest1287.1288.fi1289.1290.IP "" 01291.1292.SS "res\.header(key[, val])"1293Get or set the response header \fIkey\fR\.1294.1295.IP "" 41296.1297.nf12981299res\.header(\'Content\-Length\');1300// => undefined13011302res\.header(\'Content\-Length\', 123);1303// => 12313041305res\.header(\'Content\-Length\');1306// => 1231307.1308.fi1309.1310.IP "" 01311.1312.SS "res\.contentType(type)"1313Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1314.1315.IP "" 41316.1317.nf13181319 var filename = \'path/to/image\.png\';1320 res\.contentType(filename);

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1321why, one step back
1321 // Content\-Type is now "image/png"

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1322–1339why, one step back
1322.
1323.fi1324.1325.IP "" 01326.1327.SS "res\.attachment([filename])"1328Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1329.1330.IP "" 41331.1332.nf13331334 res\.attachment(\'path/to/my/image\.png\');1335.1336.fi1337.1338.IP "" 01339.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1340why, one step back
1340.SS "res\.sendfile(path[, options[, callback]])"

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1341–1353why, one step back
1341Used by \fBres\.download()\fR to transfer an arbitrary file\.
1342.1343.IP "" 41344.1345.nf13461347res\.sendfile(\'path/to/my\.file\');1348.1349.fi1350.1351.IP "" 01352.1353.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1354why, one step back
1354This method accepts an optional callback which is called when an error occurs, or when the transfer is complete\. By default failures call \fBnext(err)\fR, however when a callback is supplied you must do this explicitly, or act on the error\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1355–1359why, one step back
1355.
1356.IP "" 41357.1358.nf1359

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1360why, one step back
1360res\.sendfile(path, function(err){

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

line 1361why, one step back
1361 if (err) {

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1362why, one step back
1362 next(err);

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1363–1372why, one step back
1363 } else {
1364 console\.log(\'transferred %s\', path);1365 }1366});1367.1368.fi1369.1370.IP "" 01371.1372.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1373why, one step back
1373Options may also be passed to the internal \fIfs\.createReadStream()\fR call, for example altering the \fIbufferSize\fR:

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

line 1374why, one step back
1374.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1375–1387why, one step back
1375.IP "" 4
1376.1377.nf13781379res\.sendfile(path, { bufferSize: 1024 }, function(err){1380 // handle1381});1382.1383.fi1384.1385.IP "" 01386.1387.SS "res\.download(file[, filename[, callback]])"

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1388–1414why, one step back
1388Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.
1389.1390.IP "" 41391.1392.nf13931394res\.download(\'path/to/image\.png\');1395res\.download(\'path/to/image\.png\', \'foo\.png\');1396.1397.fi1398.1399.IP "" 01400.1401.P1402This is equivalent to:1403.1404.IP "" 41405.1406.nf14071408res\.attachment(file);1409res\.sendfile(file);1410.1411.fi1412.1413.IP "" 01414.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1415–1429why, one step back
1415.P
1416An optional callback may be supplied as either the second or third argument, which is passed to \fIres\.sendfile()\fR:1417.1418.IP "" 41419.1420.nf14211422res\.download(path, \'expenses\.doc\', function(err){1423 // handle1424});1425.1426.fi1427.1428.IP "" 01429.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

line 1430why, one step back
1430.SS "res\.send(body|status[, headers|status[, status]])"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1431why, one step back
1431The \fIres\.send()\fR method is a high level response utility allowing you to pass objects to respond with json, strings for html, Buffer instances, or numbers representing the status code\. The following are all valid uses:

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1432–1450why, one step back
1432.
1433.IP "" 41434.1435.nf14361437 res\.send(); // 2041438 res\.send(new Buffer(\'wahoo\'));1439 res\.send({ some: \'json\' });1440 res\.send(\'<p>some html</p>\');1441 res\.send(\'Sorry, cant find that\', 404);1442 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1443 res\.send(404);1444.1445.fi1446.1447.IP "" 01448.1449.P1450By 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 1451–1452why, one step back
1451.
1452.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1453why, one step back
1453Note that this method \fIend()\fRs the response, so you will want to use node\'s \fIres\.write()\fR for multiple writes or streaming\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1454–1475why, one step back
1454.
1455.SS "res\.redirect(url[, status])"1456Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1457.1458.IP "" 41459.1460.nf14611462res\.redirect(\'/\', 301);1463res\.redirect(\'/account\');1464res\.redirect(\'http://google\.com\');1465res\.redirect(\'home\');1466res\.redirect(\'back\');1467.1468.fi1469.1470.IP "" 01471.1472.P1473Express 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 "/"\.1474.1475.SS "res\.cookie(name, val[, options])"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1476why, one step back
1476Sets the given cookie \fIname\fR to \fIval\fR, with options \fIhttpOnly\fR, \fIsecure\fR, \fIexpires\fR etc\.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1477–1489why, one step back
1477.
1478.IP "" 41479.1480.nf14811482// "Remember me" for 15 minutes1483res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1484.1485.fi1486.1487.IP "" 01488.1489.P

docsTj Holowaychukbefore adoption131970b

lines 1490–1502why, one step back
1490The \fImaxAge\fR property may be used to set \fIexpires\fR relative to \fIDate\.now()\fR in milliseconds, so our example above can now become:
1491.1492.IP "" 41493.1494.nf14951496res\.cookie(\'rememberme\', \'yes\', { maxAge: 900000 });1497.1498.fi1499.1500.IP "" 01501.1502.P

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1503–1508why, one step back
1503To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:
1504.1505.IP "" 41506.1507.nf1508

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1509why, one step back
1509app\.use(express\.cookieParser());

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1510–1511why, one step back
1510
1511app\.get(\'/\', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1512why, one step back
1512 // use req\.cookies\.rememberme

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1513–1535why, one step back
1513});
1514.1515.fi1516.1517.IP "" 01518.1519.SS "res\.clearCookie(name)"1520Clear cookie \fIname\fR by setting "expires" far in the past\.1521.1522.IP "" 41523.1524.nf15251526res\.clearCookie(\'rememberme\');1527.1528.fi1529.1530.IP "" 01531.1532.SS "res\.render(view[, options[, fn]])"1533Render \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\.1534.1535.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1536why, one step back
1536The \fIoptions\fR passed are the local variables as well, for example if we want to expose "user" to the view, and prevent a local we do so within the same object:

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

line 1537why, one step back
1537.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1538why, one step back
1538.IP "" 4

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

line 1539why, one step back
1539.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1540–1543why, one step back
1540.nf
15411542var user = { name: \'tj\' };1543res\.render(\'index\', { layout: false, user: user });

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

line 1544why, one step back
1544.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1545why, one step back
1545.fi

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1546–1671why, one step back
1546.
1547.IP "" 01548.1549.SS "res\.partial(view[, options])"1550Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1551.1552.IP "\(bu" 41553\fIobject\fR the object named by \fIas\fR or derived from the view name1554.1555.IP "\(bu" 41556\fIas\fR Variable name for each \fIcollection\fR or \fIobject\fR value, defaults to the view name\.1557.1558.IP "\(bu" 41559as: \'something\' will add the \fIsomething\fR local variable1560.1561.IP "\(bu" 41562as: this will use the collection value as the template context1563.1564.IP "\(bu" 41565as: global will merge the collection value\'s properties with \fIlocals\fR1566.1567.IP "" 015681569.1570.IP "\(bu" 41571\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\.1572.1573.IP "" 01574.1575.P1576The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1577.1578.IP "" 41579.1580.nf15811582partial(\'theatre/movie\.jade\', { collection: movies });1583partial(\'theatre/movie\.jade\', movies);1584partial(\'movie\.jade\', { collection: movies });1585partial(\'movie\.jade\', movies);1586partial(\'movie\', movies);1587// In view: movie\.director1588.1589.fi1590.1591.IP "" 01592.1593.P1594To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1595.1596.IP "" 41597.1598.nf15991600partial(\'movie\', { collection: movies, as: \'video\' });1601// In view: video\.director1602.1603.fi1604.1605.IP "" 01606.1607.P1608Also 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\.1609.1610.IP "" 41611.1612.nf16131614partial(\'movie\', { collection: movies, as: this });1615// In view: this\.director1616.1617.fi1618.1619.IP "" 01620.1621.P1622Another 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:1623.1624.IP "" 41625.1626.nf16271628partial(\'movie\', { collection: movies, as: global });1629// In view: director1630.1631.fi1632.1633.IP "" 01634.1635.P1636This same logic applies to a single partial object usage:1637.1638.IP "" 41639.1640.nf16411642partial(\'movie\', { object: movie, as: this });1643// In view: this\.director16441645partial(\'movie\', { object: movie, as: global });1646// In view: director16471648partial(\'movie\', { object: movie, as: \'video\' });1649// In view: video\.director16501651partial(\'movie\', { object: movie });1652// In view: movie\.director1653.1654.fi1655.1656.IP "" 01657.1658.P1659When 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:1660.1661.IP "" 41662.1663.nf16641665partial(\'movie\', movie);1666// => In view: movie\.director1667.1668.fi1669.1670.IP "" 01671.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1672–1695why, one step back
1672.P
1673This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:1674.1675.IP "" 41676.1677.nf16781679app\.get(\'/users\', function(req, res){1680 if (req\.xhr) {1681 // respond with the each user in the collection1682 // passed to the "user" view1683 res\.partial(\'user\', users);1684 } else {1685 // respond with layout, and users page1686 // which internally does partial(\'user\', users)1687 // along with other UI1688 res\.render(\'users\', { users: users });1689 }1690});1691.1692.fi1693.1694.IP "" 01695.

Re-built docsTj Holowaychukbefore adoption8e63d04

lines 1696–1719why, one step back
1696.SS "res\.local(name[, val])"
1697Get 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\.1698.1699.IP "" 41700.1701.nf17021703 app\.all(\'/movie/:id\', function(req, res, next){1704 Movie\.get(req\.params\.id, function(err, movie){1705 // Assigns res\.locals\.movie = movie1706 res\.local(\'movie\', movie);1707 });1708 });17091710 app\.get(\'/movie/:id\', function(req, res){1711 // movie is already a local, however we1712 // can pass more if we wish1713 res\.render(\'movie\', { displayReviews: true });1714 });1715.1716.fi1717.1718.IP "" 01719.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1720–1758why, one step back
1720.SS "app\.set(name[, val])"
1721Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1722.1723.IP "" 41724.1725.nf17261727app\.set(\'views\', __dirname + \'/views\');1728app\.set(\'views\');1729// => \.\.\.path\.\.\.1730.1731.fi1732.1733.IP "" 01734.1735.P1736Alternatively you may simply access the settings via \fIapp\.settings\fR:1737.1738.IP "" 41739.1740.nf17411742app\.settings\.views1743// => \.\.\.path\.\.\.1744.1745.fi1746.1747.IP "" 01748.1749.SS "app\.enable(name)"1750Enable the given setting \fIname\fR:1751.1752.IP "" 41753.1754.nf17551756app\.enable(\'some arbitrary setting\');1757app\.set(\'some arbitrary setting\');1758// => true

Re-built docsTj Holowaychukbefore adoption8e63d04

lines 1759–1761why, one step back
1759
1760app\.enabled(\'some arbitrary setting\');1761// => true

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1762–1766why, one step back
1762.
1763.fi1764.1765.IP "" 01766.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1767–1784why, one step back
1767.SS "app\.enabled(name)"
1768Check if setting \fIname\fR is enabled:1769.1770.IP "" 41771.1772.nf17731774app\.enabled(\'view cache\');1775// => false17761777app\.enable(\'view cache\');1778app\.enabled(\'view cache\');1779// => true1780.1781.fi1782.1783.IP "" 01784.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1785–1793why, one step back
1785.SS "app\.disable(name)"
1786Disable the given setting \fIname\fR:1787.1788.IP "" 41789.1790.nf17911792app\.disable(\'some setting\');1793app\.set(\'some setting\');

Re-built docsTj Holowaychukbefore adoption8e63d04

lines 1794–1796why, one step back
1794// => false
17951796app\.disabled(\'some setting\');

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1797–1802why, one step back
1797// => false
1798.1799.fi1800.1801.IP "" 01802.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1803–1822why, one step back
1803.SS "app\.disabled(name)"
1804Check if setting \fIname\fR is disabled:1805.1806.IP "" 41807.1808.nf18091810app\.enable(\'view cache\');18111812app\.disabled(\'view cache\');1813// => false18141815app\.disable(\'view cache\');1816app\.disabled(\'view cache\');1817// => true1818.1819.fi1820.1821.IP "" 01822.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1823–1842why, one step back
1823.SS "app\.configure(env|function[, function])"
1824Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1825.1826.IP "" 41827.1828.nf18291830app\.configure(function(){1831 // executed for each env1832});18331834app\.configure(\'development\', function(){1835 // executed for \'development\' only1836});1837.1838.fi1839.1840.IP "" 01841.1842.SS "app\.redirect(name, val)"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1843why, one step back
1843For use with \fIres\.redirect()\fR we can map redirects at the application level as shown below:

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1844–1868why, one step back
1844.
1845.IP "" 41846.1847.nf18481849app\.redirect(\'google\', \'http://google\.com\');1850.1851.fi1852.1853.IP "" 01854.1855.P1856Now in a route we may call:1857.1858.P1859res\.redirect(\'google\');1860.1861.P1862We may also map dynamic redirects:1863.1864.IP "" 41865.1866.nf18671868app\.redirect(\'comments\', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1869why, one step back
1869 return \'/post/\' + req\.params\.id + \'/comments\';

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1870–1883why, one step back
1870});
1871.1872.fi1873.1874.IP "" 01875.1876.P1877So 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\.1878.1879.IP "" 41880.1881.nf18821883app\.get(\'/post/:id\', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1884why, one step back
1884 res\.redirect(\'comments\');

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1885–1890why, one step back
1885});
1886.1887.fi1888.1889.IP "" 01890.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1891–1903why, one step back
1891.P
1892When mounted, \fIres\.redirect()\fR will respect the mount\-point\. For example if a blog app is mounted at \fI/blog\fR, the following will redirect to \fI/blog/posts\fR:1893.1894.IP "" 41895.1896.nf18971898res\.redirect(\'/posts\');1899.1900.fi1901.1902.IP "" 01903.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1904–1911why, one step back
1904.SS "app\.error(function)"
1905Adds 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:1906.1907.IP "" 41908.1909.nf19101911app\.error(function(err, req, res, next){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1912why, one step back
1912 res\.send(err\.message, 500);

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1913–1921why, one step back
1913});
1914.1915.fi1916.1917.IP "" 01918.1919.SS "app\.helpers(obj)"1920Registers static view helpers\.1921.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1922–1924why, one step back
1922.P
1923app\.helpers({1924.

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1925–1928why, one step back
1925.IP "" 4
1926.1927.nf1928

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1929–1931why, one step back
1929 name: function(first, last){ return first + \', \' + last }
1930, firstName: \'tj\'1931, lastName: \'holowaychuk\'

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1932–1937why, one step back
1932.
1933.fi1934.1935.IP "" 01936.1937.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1938–1940why, one step back
1938});
1939.1940.P

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1941–1960why, one step back
1941Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.
1942.1943.IP "" 41944.1945.nf19461947<%= name(firstName, lastName) %>1948.1949.fi1950.1951.IP "" 01952.1953.SS "app\.dynamicHelpers(obj)"1954Registers 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\.1955.1956.IP "" 41957.1958.nf19591960app\.dynamicHelpers({

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1961–1963why, one step back
1961 session: function(req, res){
1962 return req\.session;1963 }

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1964–1993why, one step back
1964});
1965.1966.fi1967.1968.IP "" 01969.1970.P1971All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1972.1973.IP "" 41974.1975.nf19761977<%= session\.name %>1978.1979.fi1980.1981.IP "" 01982.1983.SS "app\.mounted(fn)"1984Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1985.1986.IP "" 41987.1988.nf19891990var app = express\.createServer(),1991 blog = express\.createServer();19921993blog\.mounted(function(parent){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1994–1995why, one step back
1994 // parent is app
1995 // "this" is blog

route-separation example using new view resolutionTj Holowaychukbefore adoption136f920

lines 1996–2030why, one step back
1996});
19971998app\.use(blog);1999.2000.fi

The first 2,000 of 2,099 lines.