Skip to content
Myr

guide.1

This file

Path

docs/guide.1

2,080 lines · 44.7 KiB

Last changed by

view lookup docsTj Holowaychukbefore adoption8a62f8c

History of this file

Take it

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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" "" ""

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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);

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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: \.\.\. });

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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());

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\'));

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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());

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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(){

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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"

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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 });

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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:

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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());

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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()

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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());

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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());

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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 });

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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 }

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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);

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\'));

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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);

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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 }

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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);

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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:

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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());

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\');

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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());

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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);

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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;

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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!\');

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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 });

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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\' });

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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:

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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:

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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:

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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:

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 966–971why, one step back
966.
967.IP "" 0968.969.P970For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.971.

Added screencasts pageTj Holowaychukbefore adoption4144af3

line 972why, one step back
972.P

view lookup docsTj Holowaychukbefore adoption8a62f8c

lines 973–979why, one step back
973\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\.
974.975.SS "View Lookup"976View 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\.977.978.P979The 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 980why, one step back
980.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 981–998why, one step back
981.SS "Template Engines"
982Below are a few template engines commonly used with Express:983.984.IP "\(bu" 4985Jade \fIhttp://jade\-lang\.com\fR haml\.js successor986.987.IP "\(bu" 4988EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript989.990.IP "\(bu" 4991CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating992.993.IP "\(bu" 4994jQuery Templates \fIhttps://github\.com/kof/node\-jqtpl\fR for node995.996.IP "" 0997.998.SS "Session Support"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1000–1004why, one step back
1000.
1001.IP "" 41002.1003.nf1004

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1007–1019why, one step back
1007.
1008.fi1009.1010.IP "" 01011.1012.P1013By 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:1014.1015.IP "" 41016.1017.nf10181019var RedisStore = require(\'connect\-redis\');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1022–1034why, one step back
1022.
1023.fi1024.1025.IP "" 01026.1027.P1028Now 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:1029.1030.IP "" 41031.1032.nf10331034var RedisStore = require(\'connect\-redis\');

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1042–1061why, one step back
1042 var items = req\.body\.items;
1043 req\.session\.items = items;1044 res\.redirect(\'back\');1045});10461047app\.get(\'/add\-to\-cart\', function(req, res){1048 // When redirected back to GET /add\-to\-cart1049 // we could check req\.session\.items && req\.session\.items\.length1050 // to print out a message1051 if (req\.session\.items && req\.session\.items\.length) {1052 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);1053 }1054 res\.render(\'shopping\-cart\');1055});1056.1057.fi1058.1059.IP "" 01060.1061.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1063–1064why, one step back
1063.
1064.SS "Migration Guide"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1065why, one step back
1065Express 1\.x developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1066–1081why, one step back
1066.
1067.SS "req\.header(key[, defaultValue])"1068Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1069.1070.IP "" 41071.1072.nf10731074req\.header(\'Host\');1075req\.header(\'host\');1076req\.header(\'Accept\', \'*/*\');1077.1078.fi1079.1080.IP "" 01081.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1082–1100why, one step back
1082.P
1083The \fIReferrer\fR and \fIReferer\fR header fields are special\-cased, either will work:1084.1085.IP "" 41086.1087.nf10881089// sent Referrer: http://google\.com10901091req\.header(\'Referer\');1092// => "http://google\.com"10931094req\.header(\'Referrer\');1095// => "http://google\.com"1096.1097.fi1098.1099.IP "" 01100.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1101–1216why, one step back
1101.SS "req\.accepts(type)"
1102Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1103.1104.P1105When 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\.1106.1107.IP "" 41108.1109.nf11101111// Accept: text/html1112req\.accepts(\'html\');1113// => true11141115// Accept: text/*; application/json1116req\.accepts(\'html\');1117req\.accepts(\'text/html\');1118req\.accepts(\'text/plain\');1119req\.accepts(\'application/json\');1120// => true11211122req\.accepts(\'image/png\');1123req\.accepts(\'png\');1124// => false1125.1126.fi1127.1128.IP "" 01129.1130.SS "req\.is(type)"1131Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.1132.1133.IP "" 41134.1135.nf11361137 // With Content\-Type: text/html; charset=utf\-81138 req\.is(\'html\');1139 req\.is(\'text/html\');1140 // => true11411142 // When Content\-Type is application/json1143 req\.is(\'json\');1144 req\.is(\'application/json\');1145 // => true11461147 req\.is(\'html\');1148 // => false1149.1150.fi1151.1152.IP "" 01153.1154.P1155Ad\-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:1156.1157.IP "" 41158.1159.nf11601161 app\.is(\'an image\', function(req){1162 return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1163 });1164.1165.fi1166.1167.IP "" 01168.1169.P1170Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1171.1172.IP "" 41173.1174.nf11751176 app\.post(\'/image/upload\', function(req, res, next){1177 if (req\.is(\'an image\')) {1178 // do something1179 } else {1180 next();1181 }1182 });1183.1184.fi1185.1186.IP "" 01187.1188.P1189Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1190.1191.P1192Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1193.1194.IP "" 41195.1196.nf11971198req\.is(\'image/*\');1199.1200.fi1201.1202.IP "" 01203.1204.P1205We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1206.1207.IP "" 41208.1209.nf12101211req\.is(\'*/json\');1212.1213.fi1214.1215.IP "" 01216.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1219–1220why, one step back
1219.
1220.IP "\(bu" 4

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1222–1231why, one step back
1222.
1223.IP "\(bu" 41224Checks query string params (\fIreq\.query\fR), ex: ?id=121225.1226.IP "\(bu" 41227Checks urlencoded body params (\fIreq\.body\fR), ex: id=121228.1229.IP "" 01230.1231.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1233–1314why, one step back
1233.
1234.SS "req\.flash(type[, msg])"1235Queue flash \fImsg\fR of the given \fItype\fR\.1236.1237.IP "" 41238.1239.nf12401241req\.flash(\'info\', \'email sent\');1242req\.flash(\'error\', \'email delivery failed\');1243req\.flash(\'info\', \'email re\-sent\');1244// => 212451246req\.flash(\'info\');1247// => [\'email sent\', \'email re\-sent\']12481249req\.flash(\'info\');1250// => []12511252req\.flash();1253// => { error: [\'email delivery failed\'], info: [] }1254.1255.fi1256.1257.IP "" 01258.1259.P1260Flash notification message may also utilize formatters, by default only the %s string formatter is available:1261.1262.IP "" 41263.1264.nf12651266req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1267.1268.fi1269.1270.IP "" 01271.1272.SS "req\.isXMLHttpRequest"1273Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1274.1275.IP "" 41276.1277.nf12781279req\.xhr1280req\.isXMLHttpRequest1281.1282.fi1283.1284.IP "" 01285.1286.SS "res\.header(key[, val])"1287Get or set the response header \fIkey\fR\.1288.1289.IP "" 41290.1291.nf12921293res\.header(\'Content\-Length\');1294// => undefined12951296res\.header(\'Content\-Length\', 123);1297// => 12312981299res\.header(\'Content\-Length\');1300// => 1231301.1302.fi1303.1304.IP "" 01305.1306.SS "res\.contentType(type)"1307Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1308.1309.IP "" 41310.1311.nf13121313 var filename = \'path/to/image\.png\';1314 res\.contentType(filename);

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1316–1333why, one step back
1316.
1317.fi1318.1319.IP "" 01320.1321.SS "res\.attachment([filename])"1322Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1323.1324.IP "" 41325.1326.nf13271328 res\.attachment(\'path/to/my/image\.png\');1329.1330.fi1331.1332.IP "" 01333.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1335–1347why, one step back
1335Used by \fBres\.download()\fR to transfer an arbitrary file\.
1336.1337.IP "" 41338.1339.nf13401341res\.sendfile(\'path/to/my\.file\');1342.1343.fi1344.1345.IP "" 01346.1347.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1349–1353why, one step back
1349.
1350.IP "" 41351.1352.nf1353

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1357–1366why, one step back
1357 } else {
1358 console\.log(\'transferred %s\', path);1359 }1360});1361.1362.fi1363.1364.IP "" 01365.1366.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

line 1368why, one step back
1368.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1369–1381why, one step back
1369.IP "" 4
1370.1371.nf13721373res\.sendfile(path, { bufferSize: 1024 }, function(err){1374 // handle1375});1376.1377.fi1378.1379.IP "" 01380.1381.SS "res\.download(file[, filename[, callback]])"

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1382–1408why, one step back
1382Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.
1383.1384.IP "" 41385.1386.nf13871388res\.download(\'path/to/image\.png\');1389res\.download(\'path/to/image\.png\', \'foo\.png\');1390.1391.fi1392.1393.IP "" 01394.1395.P1396This is equivalent to:1397.1398.IP "" 41399.1400.nf14011402res\.attachment(file);1403res\.sendfile(file);1404.1405.fi1406.1407.IP "" 01408.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1409–1423why, one step back
1409.P
1410An optional callback may be supplied as either the second or third argument, which is passed to \fIres\.sendfile()\fR:1411.1412.IP "" 41413.1414.nf14151416res\.download(path, \'expenses\.doc\', function(err){1417 // handle1418});1419.1420.fi1421.1422.IP "" 01423.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1425why, one step back
1425The \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:

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1426–1444why, one step back
1426.
1427.IP "" 41428.1429.nf14301431 res\.send(); // 2041432 res\.send(new Buffer(\'wahoo\'));1433 res\.send({ some: \'json\' });1434 res\.send(\'<p>some html</p>\');1435 res\.send(\'Sorry, cant find that\', 404);1436 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1437 res\.send(404);1438.1439.fi1440.1441.IP "" 01442.1443.P1444By 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 1445–1446why, one step back
1445.
1446.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1448–1469why, one step back
1448.
1449.SS "res\.redirect(url[, status])"1450Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1451.1452.IP "" 41453.1454.nf14551456res\.redirect(\'/\', 301);1457res\.redirect(\'/account\');1458res\.redirect(\'http://google\.com\');1459res\.redirect(\'home\');1460res\.redirect(\'back\');1461.1462.fi1463.1464.IP "" 01465.1466.P1467Express 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 "/"\.1468.1469.SS "res\.cookie(name, val[, options])"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1471–1489why, one step back
1471.
1472.IP "" 41473.1474.nf14751476// "Remember me" for 15 minutes1477res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1478.1479.fi1480.1481.IP "" 01482.1483.P1484To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1485.1486.IP "" 41487.1488.nf1489

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

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

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1494–1516why, one step back
1494});
1495.1496.fi1497.1498.IP "" 01499.1500.SS "res\.clearCookie(name)"1501Clear cookie \fIname\fR by setting "expires" far in the past\.1502.1503.IP "" 41504.1505.nf15061507res\.clearCookie(\'rememberme\');1508.1509.fi1510.1511.IP "" 01512.1513.SS "res\.render(view[, options[, fn]])"1514Render \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\.1515.1516.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1517why, one step back
1517The \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:

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

line 1518why, one step back
1518.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

line 1520why, one step back
1520.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

line 1525why, one step back
1525.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

line 1526why, one step back
1526.fi

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1527–1652why, one step back
1527.
1528.IP "" 01529.1530.SS "res\.partial(view[, options])"1531Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1532.1533.IP "\(bu" 41534\fIobject\fR the object named by \fIas\fR or derived from the view name1535.1536.IP "\(bu" 41537\fIas\fR Variable name for each \fIcollection\fR or \fIobject\fR value, defaults to the view name\.1538.1539.IP "\(bu" 41540as: \'something\' will add the \fIsomething\fR local variable1541.1542.IP "\(bu" 41543as: this will use the collection value as the template context1544.1545.IP "\(bu" 41546as: global will merge the collection value\'s properties with \fIlocals\fR1547.1548.IP "" 015491550.1551.IP "\(bu" 41552\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\.1553.1554.IP "" 01555.1556.P1557The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1558.1559.IP "" 41560.1561.nf15621563partial(\'theatre/movie\.jade\', { collection: movies });1564partial(\'theatre/movie\.jade\', movies);1565partial(\'movie\.jade\', { collection: movies });1566partial(\'movie\.jade\', movies);1567partial(\'movie\', movies);1568// In view: movie\.director1569.1570.fi1571.1572.IP "" 01573.1574.P1575To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1576.1577.IP "" 41578.1579.nf15801581partial(\'movie\', { collection: movies, as: \'video\' });1582// In view: video\.director1583.1584.fi1585.1586.IP "" 01587.1588.P1589Also 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\.1590.1591.IP "" 41592.1593.nf15941595partial(\'movie\', { collection: movies, as: this });1596// In view: this\.director1597.1598.fi1599.1600.IP "" 01601.1602.P1603Another 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:1604.1605.IP "" 41606.1607.nf16081609partial(\'movie\', { collection: movies, as: global });1610// In view: director1611.1612.fi1613.1614.IP "" 01615.1616.P1617This same logic applies to a single partial object usage:1618.1619.IP "" 41620.1621.nf16221623partial(\'movie\', { object: movie, as: this });1624// In view: this\.director16251626partial(\'movie\', { object: movie, as: global });1627// In view: director16281629partial(\'movie\', { object: movie, as: \'video\' });1630// In view: video\.director16311632partial(\'movie\', { object: movie });1633// In view: movie\.director1634.1635.fi1636.1637.IP "" 01638.1639.P1640When 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:1641.1642.IP "" 41643.1644.nf16451646partial(\'movie\', movie);1647// => In view: movie\.director1648.1649.fi1650.1651.IP "" 01652.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1653–1676why, one step back
1653.P
1654This 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:1655.1656.IP "" 41657.1658.nf16591660app\.get(\'/users\', function(req, res){1661 if (req\.xhr) {1662 // respond with the each user in the collection1663 // passed to the "user" view1664 res\.partial(\'user\', users);1665 } else {1666 // respond with layout, and users page1667 // which internally does partial(\'user\', users)1668 // along with other UI1669 res\.render(\'users\', { users: users });1670 }1671});1672.1673.fi1674.1675.IP "" 01676.

Re-built docsTj Holowaychukbefore adoption8e63d04

lines 1677–1700why, one step back
1677.SS "res\.local(name[, val])"
1678Get 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\.1679.1680.IP "" 41681.1682.nf16831684 app\.all(\'/movie/:id\', function(req, res, next){1685 Movie\.get(req\.params\.id, function(err, movie){1686 // Assigns res\.locals\.movie = movie1687 res\.local(\'movie\', movie);1688 });1689 });16901691 app\.get(\'/movie/:id\', function(req, res){1692 // movie is already a local, however we1693 // can pass more if we wish1694 res\.render(\'movie\', { displayReviews: true });1695 });1696.1697.fi1698.1699.IP "" 01700.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1701–1739why, one step back
1701.SS "app\.set(name[, val])"
1702Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1703.1704.IP "" 41705.1706.nf17071708app\.set(\'views\', __dirname + \'/views\');1709app\.set(\'views\');1710// => \.\.\.path\.\.\.1711.1712.fi1713.1714.IP "" 01715.1716.P1717Alternatively you may simply access the settings via \fIapp\.settings\fR:1718.1719.IP "" 41720.1721.nf17221723app\.settings\.views1724// => \.\.\.path\.\.\.1725.1726.fi1727.1728.IP "" 01729.1730.SS "app\.enable(name)"1731Enable the given setting \fIname\fR:1732.1733.IP "" 41734.1735.nf17361737app\.enable(\'some arbitrary setting\');1738app\.set(\'some arbitrary setting\');1739// => true

Re-built docsTj Holowaychukbefore adoption8e63d04

lines 1740–1742why, one step back
1740
1741app\.enabled(\'some arbitrary setting\');1742// => true

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1743–1747why, one step back
1743.
1744.fi1745.1746.IP "" 01747.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1748–1765why, one step back
1748.SS "app\.enabled(name)"
1749Check if setting \fIname\fR is enabled:1750.1751.IP "" 41752.1753.nf17541755app\.enabled(\'view cache\');1756// => false17571758app\.enable(\'view cache\');1759app\.enabled(\'view cache\');1760// => true1761.1762.fi1763.1764.IP "" 01765.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1766–1774why, one step back
1766.SS "app\.disable(name)"
1767Disable the given setting \fIname\fR:1768.1769.IP "" 41770.1771.nf17721773app\.disable(\'some setting\');1774app\.set(\'some setting\');

Re-built docsTj Holowaychukbefore adoption8e63d04

lines 1775–1777why, one step back
1775// => false
17761777app\.disabled(\'some setting\');

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1778–1783why, one step back
1778// => false
1779.1780.fi1781.1782.IP "" 01783.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1784–1803why, one step back
1784.SS "app\.disabled(name)"
1785Check if setting \fIname\fR is disabled:1786.1787.IP "" 41788.1789.nf17901791app\.enable(\'view cache\');17921793app\.disabled(\'view cache\');1794// => false17951796app\.disable(\'view cache\');1797app\.disabled(\'view cache\');1798// => true1799.1800.fi1801.1802.IP "" 01803.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1804–1823why, one step back
1804.SS "app\.configure(env|function[, function])"
1805Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1806.1807.IP "" 41808.1809.nf18101811app\.configure(function(){1812 // executed for each env1813});18141815app\.configure(\'development\', function(){1816 // executed for \'development\' only1817});1818.1819.fi1820.1821.IP "" 01822.1823.SS "app\.redirect(name, val)"

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1825–1849why, one step back
1825.
1826.IP "" 41827.1828.nf18291830app\.redirect(\'google\', \'http://google\.com\');1831.1832.fi1833.1834.IP "" 01835.1836.P1837Now in a route we may call:1838.1839.P1840res\.redirect(\'google\');1841.1842.P1843We may also map dynamic redirects:1844.1845.IP "" 41846.1847.nf18481849app\.redirect(\'comments\', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1851–1864why, one step back
1851});
1852.1853.fi1854.1855.IP "" 01856.1857.P1858So 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\.1859.1860.IP "" 41861.1862.nf18631864app\.get(\'/post/:id\', function(req, res){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1866–1871why, one step back
1866});
1867.1868.fi1869.1870.IP "" 01871.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1872–1884why, one step back
1872.P
1873When 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:1874.1875.IP "" 41876.1877.nf18781879res\.redirect(\'/posts\');1880.1881.fi1882.1883.IP "" 01884.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1885–1892why, one step back
1885.SS "app\.error(function)"
1886Adds 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:1887.1888.IP "" 41889.1890.nf18911892app\.error(function(err, req, res, next){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1894–1902why, one step back
1894});
1895.1896.fi1897.1898.IP "" 01899.1900.SS "app\.helpers(obj)"1901Registers static view helpers\.1902.

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1903–1905why, one step back
1903.P
1904app\.helpers({1905.

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1906–1909why, one step back
1906.IP "" 4
1907.1908.nf1909

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

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

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1913–1918why, one step back
1913.
1914.fi1915.1916.IP "" 01917.1918.P

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1919–1921why, one step back
1919});
1920.1921.P

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1922–1941why, one step back
1922Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.
1923.1924.IP "" 41925.1926.nf19271928<%= name(firstName, lastName) %>1929.1930.fi1931.1932.IP "" 01933.1934.SS "app\.dynamicHelpers(obj)"1935Registers 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\.1936.1937.IP "" 41938.1939.nf19401941app\.dynamicHelpers({

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1942–1944why, one step back
1942 session: function(req, res){
1943 return req\.session;1944 }

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1945–1974why, one step back
1945});
1946.1947.fi1948.1949.IP "" 01950.1951.P1952All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1953.1954.IP "" 41955.1956.nf19571958<%= session\.name %>1959.1960.fi1961.1962.IP "" 01963.1964.SS "app\.mounted(fn)"1965Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1966.1967.IP "" 41968.1969.nf19701971var app = express\.createServer(),1972 blog = express\.createServer();19731974blog\.mounted(function(parent){

Merge branch 'docs'Tj Holowaychukbefore adoption64da262

lines 1975–1976why, one step back
1975 // parent is app
1976 // "this" is blog

Added default link color for express(1) generated appsTj Holowaychukbefore adoptionebbe481

lines 1977–2011why, one step back
1977});
19781979app\.use(blog);1980.1981.fi1982.1983.IP "" 01984.1985.SS "app\.register(ext, exports)"1986Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:1987.1988.IP "" 41989.1990.nf19911992 app\.register(\'\.html\', require(\'jade\'));1993.1994.fi1995.1996.IP "" 01997.1998.P1999This 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":2000.

The first 2,000 of 2,080 lines.