Merge branch 'docs'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tj Holowaychuk · committed by Tj Holowaychuk · parents 631c1f9, 61aec6e · Browse files · 16 files·+819 added−553 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+819 added−553 removed
- other:+819 added−553 removed
Provenance
- Commit
64da262- Tree
32fcc55- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent 1
631c1f9- Parent 2
61aec6e
16 files changed+819 added−553 removed
modified:docs/guide.1+275 added-176 removed
1 .\" generated with Ronn/v0.7.32 .\" http://github.com/rtomayko/ronn/tree/0.7.33 .4-.TH "GUIDE" "" "December 2010" "" ""4+.TH "GUIDE" "" "March 2011" "" ""5 .6 .SH "NAME"7 \fBguide\fR8 .9 .SS "Installation"10-curl:10 .12-.IP "" 413-.11 .nf12 16-$ curl \-# http://expressjs\.com/install\.sh | sh13+$ npm install express14 .15 .fi16 .20-.IP "" 017+.SS "Creating A Server"18+To 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\.19 .22-.P23-npm:24-.20 .IP "" 421 .22 .nf23 29-$ npm install express24+var app = require(\'express\')\.createServer();25+26+app\.get(\'/\', function(req, res){27+ res\.send(\'hello world\');28+});29+30+app\.listen(3000);31 .32 .fi33 .34 .IP "" 035 .35-.SS "Creating An Application"36-The \fIexpress\.Server\fR now inherits from \fIhttp\.Server\fR, however follows the same idiom by providing \fIexpress\.createServer()\fR as shown below\. This means that you can utilize Express server\'s transparently with other libraries\.36+.SS "Creating An HTTPS Server"37+To 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\.38 .39 .IP "" 440 .41 .nf42 42-var app = require(\'express\')\.createServer();43-44-app\.get(\'/\', function(req, res){45- res\.send(\'hello world\');46-});47-48-app\.listen(3000);43+ var app = require(\'express\')\.createServer({ key: \.\.\. });44 .45 .fi46 .47 .IP "" 01 unmodified line49 .SS "Configuration"50 Express 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 .P58-In the example below we only \fIdumpExceptions\fR, and respond with exception stack traces in \fIdevelopment\fR mode, however for both environments we utilize \fImethodOverride\fR and \fIbodyDecoder\fR\. Note the use of \fIapp\.router\fR, which can (optionally) be used to mount the application routes, otherwise the first call to \fIapp\.{get,put,del,post}()\fR will mount the routes\.53+In 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\.54 .55 .IP "" 456 .57 .nf58 59 app\.configure(function(){60 app\.use(express\.methodOverride());66- app\.use(express\.bodyDecoder());61+ app\.use(express\.bodyParser());62 app\.use(app\.router);68- app\.use(express\.staticProvider(__dirname + \'/public\'));63 });64 65 app\.configure(\'development\', function(){66+ app\.use(express\.static(__dirname + \'/public\'));67 app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));68 });69 70 app\.configure(\'production\', function(){71+ var oneYear = 31557600000;72+ app\.use(express\.static({ root: __dirname + \'/public\', maxAge: oneYear }));76- app\.use(express\.errorHandler());73+ app\.use(express\.errorHandler());74 });75 .76 .fi77 .5 unmodified lines83 .IP "" 484 .85 .nf86 90-app\.configure(function(){87+ app\.configure(function(){88 app\.set(\'views\', __dirname + \'/views\');89 app\.set(\'views\');93- // => "\.\.\. views directory \.\.\."90+ // => "/absolute/path/to/views"91 92 app\.enable(\'some feature\');93 // same as app\.set(\'some feature\', true);94 95 app\.disable(\'some feature\');96 // same as app\.set(\'some feature\', false);97+98+ app\.enabled(\'some feature\')99+ // => false100-});100+ });101 .102 .fi103 .104 .IP "" 017 unmodified lines122 .SS "Settings"123 Express supports the following settings out of the box:124 .125 .IP "\(bu" 4126-\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR127-.128-.IP "\(bu" 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\fR3 unmodified lines133 .134 .IP "\(bu" 4135 \fIview options\fR An object specifying global view options136 .140-.IP "\(bu" 4141-\fIstream threshold\fR Bytesize indicating when a file should be streamed for \fIres\.sendfile()\fR using \fIfs\.ReadStream()\fR and \fIsys\.pump()\fR\.142-.137 .IP "" 0138 .139 .SS "Routing"140 Express 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\.101 unmodified lines242 .243 .IP "" 0244 .245 .P252-For example we can \fBPOST\fR some json, and echo the json back using the \fIbodyDecoder\fR middleware which will parse json request bodies (as well as others), and place the result in \fIreq\.body\fR:246+For 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:247 .248 .IP "" 4249 .250 .nf251 252 var express = require(\'express\')253 , app = express\.createServer();254 261-app\.use(express\.bodyDecoder());255+app\.use(express\.bodyParser());256 257 app\.post(\'/\', function(req, res){258 res\.send(req\.body);259 });4 unmodified lines264 .265 .IP "" 0266 .267 .P274-Express 2\.0\.0\-pre also supports named capture groups\. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, however say for example we are limiting a user id to digits, we may use \fI\'/user/:id(\ed+)\'\fR which will \fInot\fR match unless the placeholder value contains only digits\.268+Typically 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\.269 .270 .SS "Passing Route Control"277-We may pass control to the next \fImatching\fR route, by calling the \fIthird\fR argument, the \fInext()\fR function\. When a match cannot be made, control is passed back to Connect, and middleware continue to be invoked\. The same is true for several routes which have the same path defined, they will simply be executed in order until one does \fInot\fR call \fInext()\fR\.271+We 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\.272 .273 .IP "" 4274 .275 .nf15 unmodified lines291 .292 .IP "" 0293 .294 .P301-Express 1\.0 also introduces the \fIall()\fR method, which provides a route callback matching any HTTP method\. This is useful in many ways, one example being the loading of resources before executing subsequent routes as shown below:295+The \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\.296 .297 .IP "" 4298 .299 .nf43 unmodified lines343 344 var express = require(\'express\');345 346 var app = express\.createServer(353- express\.logger(),354- express\.bodyDecoder()347+ express\.logger()348+ , express\.bodyParser()349 );350 .351 .fi352 .353 .IP "" 0354 .355 .P362-Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:356+Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks, in a progressive manor\.357 .358 .IP "" 4359 .360 .nf12 unmodified lines373 .nf374 375 var connect = require(\'connect\');376 app\.use(connect\.logger());377+app\.use(connect\.bodyParser());378 .379 .fi380 .381 .IP "" 05 unmodified lines387 .388 .nf389 390 app\.use(express\.logger());391+app\.use(express\.bodyParser());392 .393 .fi394 .395 .IP "" 08 unmodified lines404 .405 .nf406 407 app\.get(\'/user/:id\', function(req, res, next){412- loadUser(req\.params\.id, function(err, user){413- if (err) return next(err);414- res\.send(\'Viewing user \' + user\.name);415- });408+ loadUser(req\.params\.id, function(err, user){409+ if (err) return next(err);410+ res\.send(\'Viewing user \' + user\.name);411+ });412 });413 .414 .fi415 .6 unmodified lines422 .423 .nf424 425 function loadUser(req, res, next) {430- // You would fetch your user from the db431- var user = users[req\.params\.id];432- if (user) {433- req\.user = user;434- next();435- } else {436- next(new Error(\'Failed to load user \' + req\.params\.id));437- }426+ // You would fetch your user from the db427+ var user = users[req\.params\.id];428+ if (user) {429+ req\.user = user;430+ next();431+ } else {432+ next(new Error(\'Failed to load user \' + req\.params\.id));433+ }434 }435 436 app\.get(\'/user/:id\', loadUser, function(req, res){441- res\.send(\'Viewing user \' + req\.user\.name);437+ res\.send(\'Viewing user \' + req\.user\.name);438 });439 .440 .fi441 .6 unmodified lines448 .449 .nf450 451 function andRestrictToSelf(req, res, next) {456- req\.authenticatedUser\.id == req\.user\.id457- ? next()458- : next(new Error(\'Unauthorized\'));452+ req\.authenticatedUser\.id == req\.user\.id453+ ? next()454+ : next(new Error(\'Unauthorized\'));455 }456 457 app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){462- res\.send(\'Editing user \' + req\.user\.name);458+ res\.send(\'Editing user \' + req\.user\.name);459 });460 .461 .fi462 .6 unmodified lines469 .470 .nf471 472 function andRestrictTo(role) {477- return function(req, res, next) {478- req\.authenticatedUser\.role == role479- ? next()480- : next(new Error(\'Unauthorized\'));481- }473+ return function(req, res, next) {474+ req\.authenticatedUser\.role == role475+ ? next()476+ : next(new Error(\'Unauthorized\'));477+ }478 }479 480 app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){485- res\.send(\'Deleted user \' + req\.user\.name);481+ res\.send(\'Deleted user \' + req\.user\.name);482 });483 .484 .fi485 .44 unmodified lines530 .531 .IP "" 0532 .533 .P538-By default Express does not know what to do with this request body, so we should add the \fIbodyDecoder\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:534+By default Express does not know what to do with this request body, so we should add the \fIbodyParser\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR and \fIapplication/json\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:535 .536 .IP "" 4537 .538 .nf539 544-app\.use(express\.bodyDecoder());540+app\.use(express\.bodyParser());541 .542 .fi543 .544 .IP "" 05 unmodified lines550 .551 .nf552 553 app\.post(\'/\', function(req, res){558- console\.log(req\.body\.user);559- res\.redirect(\'back\');554+ console\.log(req\.body\.user);555+ res\.redirect(\'back\');556 });557 .558 .fi559 .560 .IP "" 0561 .562 .P567-When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyDecoder\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.563+When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyParser\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.564 .565 .IP "" 4566 .567 .nf568 573-app\.use(express\.bodyDecoder());569+app\.use(express\.bodyParser());570 app\.use(express\.methodOverride());571 .572 .fi573 .29 unmodified lines603 .604 .nf605 606 function NotFound(msg){611- this\.name = \'NotFound\';612- Error\.call(this, msg);613- Error\.captureStackTrace(this, arguments\.callee);607+ this\.name = \'NotFound\';608+ Error\.call(this, msg);609+ Error\.captureStackTrace(this, arguments\.callee);610 }611 616-sys\.inherits(NotFound, Error);612+NotFound\.protoype\.__proto__ = Error\.prototype;613 614 app\.get(\'/404\', function(req, res){619- throw new NotFound;615+ throw new NotFound;616 });617 618 app\.get(\'/500\', function(req, res){623- throw new Error(\'keyboard cat!\');619+ throw new Error(\'keyboard cat!\');620 });621 .622 .fi623 .21 unmodified lines645 .646 .IP "" 0647 .648 .P653-Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like649+Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like\. For example when node performs filesystem syscalls, you may receive an error object with the \fIerror\.code\fR of \fIENOENT\fR, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired\.650 .651 .IP "" 4652 .653 .nf654 655 app\.error(function(err, req, res){660- res\.render(\'500\.jade\', {661- locals: {662- error: err663- }664- });656+ res\.render(\'500\.jade\', {657+ error: err658+ });659 });660 .661 .fi662 .27 unmodified lines690 .691 .P692 The \fIerrorHandler\fR middleware also responds with \fIjson\fR if \fIAccept: application/json\fR is present, which is useful for developing apps that rely heavily on client\-side JavaScript\.693 .700-.SS "Route Preconditions"701-Route placeholder pre\-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls\. For example if you are constantly fetching common data for several routes, such as loading a user for \fI/user/:id\fR,we might typically do something like below:694+.SS "Route Param Pre\-conditions"695+Route param pre\-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls\. For example if you are constantly fetching common data for several routes, such as loading a user for \fI/user/:id\fR, we might typically do something like below:696 .697 .IP "" 4698 .699 .nf9 unmodified lines709 .710 .IP "" 0711 .712 .P719-With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database\. Below we invoke \fIapp\.param()\fR with the parameter name we wish to map to some middleware, as you can see we receive the \fIid\fR argument which contains the placeholder value\. Using this we load the user and perform error handling as usual, and simple call \fInext()\fR to pass control to the next precondition or route handler\.713+With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database\. Below we invoke \fIapp\.param()\fR with the parameter name we wish to map to some middleware, as you can see we receive the \fIid\fR argument which contains the placeholder value\. Using this we load the user and perform error handling as usual, and simple call \fInext()\fR to pass control to the next precondition or route handler\.714 .715 .IP "" 4716 .717 .nf52 unmodified lines770 .771 .IP "" 0772 .773 .SS "View Rendering"780-View filenames take the form \fINAME\fR\.\fIENGINE\fR, where \fIENGINE\fR is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.render(str, options)\fR to comply with Express, however \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by jade\.774+View filenames take the form "<name>\.<engine>", where <engine> is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.compile(str, options)\fR, and return a \fIFunction\fR to comply with Express\. To alter this behaviour \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by ejs\.775 .776 .P783-Below is an example using Haml\.js \fIhttp://github\.com/visionmedia/haml\.js\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.html\fR will be passed as the \fIbody\fR local variable in \fIlayout\.haml\fR\.777+Below is an example using Jade \fIhttp://github\.com/visionmedia/jade\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.jade\fR will be passed as the \fIbody\fR local variable in \fIlayout\.jade\fR\.778 .779 .IP "" 4780 .781 .nf782 783 app\.get(\'/\', function(req, res){790- res\.render(\'index\.haml\', {791- locals: { title: \'My Site\' }792- });784+ res\.render(\'index\.jade\', { title: \'My Site\' });785 });786 .787 .fi788 .789 .IP "" 0790 .791 .P800-The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using Jade \fIhttp://github\.com/visionmedia/jade\fR we could set:792+The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using jade we could set:793 .794 .IP "" 4795 .796 .nf50 unmodified lines847 .848 .nf849 850 app\.set(\'view options\', {859- layout: false851+ layout: false852 });853 .854 .fi855 .856 .IP "" 0857 .858 .P867-Which can then be overridden within the \fBres\.render()\fR call if need be:859+Which can then be overridden within the \fIres\.render()\fR call if need be:860 .861 .IP "" 4862 .863 .nf59 unmodified lines923 .924 .IP "" 0925 .926 .SS "View Partials"935-The Express view system has built\-in support for partials and collections, which are sort of "mini" views representing a document fragment\. For example rather than iterating in a view to display comments, we would use a partial with collection support:927+The 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:928 .929 .IP "" 4930 .931 .nf932 941-partial(\'comment\.haml\', { collection: comments });942-.943-.fi944-.945-.IP "" 0946-.947-.P948-To make things even less verbose we can assume the extension as \fI\.haml\fR when omitted, however if we wished we could use an ejs partial, within a haml view for example\.949-.950-.IP "" 4951-.952-.nf953-933 partial(\'comment\', { collection: comments });934 .935 .fi936 .937 .IP "" 0938 .939 .P961-And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:940+If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:941 .942 .IP "" 4943 .944 .nf7 unmodified lines952 .P953 When using the partial collection support a few "magic" variables are provided for free:954 .955 .IP "\(bu" 4977-\fIfirstInCollection\fR True if this is the first object956+\fIfirstInCollection\fR true if this is the first object957 .958 .IP "\(bu" 4980-\fIindexInCollection\fR Index of the object in the collection959+\fIindexInCollection\fR index of the object in the collection960 .961 .IP "\(bu" 4983-\fIlastInCollection\fR True if this is the last object962+\fIlastInCollection\fR true if this is the last object963 .964 .IP "\(bu" 4986-\fIcollectionLength\fR Length of the collection965+\fIcollectionLength\fR length of the collection966 .967 .IP "" 0968 .969 .P970 For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.971 .972 .P994-NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead\. For example do \fInot\fR implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates\.973+NOTE: 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 "Template Engines"976 Below are a few template engines commonly used with Express:977 .978 .IP "\(bu" 4979 Jade \fIhttp://jade\-lang\.com\fR haml\.js successor980 .981 .IP "\(bu" 41003-Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates1004-.1005-.IP "\(bu" 4982 EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript983 .984 .IP "\(bu" 4985 CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating3 unmodified lines989 .990 .IP "" 0991 .992 .SS "Session Support"1017-Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieDecoder\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.993+Sessions 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\.994 .995 .IP "" 4996 .997 .nf998 1023-app\.use(express\.cookieDecoder());1024-app\.use(express\.session());999+app\.use(express\.cookieParser());1000+app\.use(express\.session({ secret: "keyboard cat" }));1001 .1002 .fi1003 .1004 .IP "" 05 unmodified lines1010 .1011 .nf1012 1013 var RedisStore = require(\'connect\-redis\');1038-app\.use(express\.cookieDecoder());1039-app\.use(express\.session({ store: new RedisStore }));1014+app\.use(express\.cookieParser());1015+app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));1016 .1017 .fi1018 .1019 .IP "" 05 unmodified lines1025 .1026 .nf1027 1028 var RedisStore = require(\'connect\-redis\');1053-app\.use(express\.bodyDecoder());1054-app\.use(express\.cookieDecoder());1055-app\.use(express\.session({ store: new RedisStore }));1029+app\.use(express\.bodyParser());1030+app\.use(express\.cookieParser());1031+app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));1032 1033 app\.post(\'/add\-to\-cart\', function(req, res){1034 // Perhaps we posted several items with a form1059- // (use the bodyDecoder() middleware for this)1035+ // (use the bodyParser() middleware for this)1036 var items = req\.body\.items;1037 req\.session\.items = items;1038 res\.redirect(\'back\');1039 });12 unmodified lines1052 .1053 .IP "" 01054 .1055 .P1080-The \fIreq\.session\fR object also has methods such as \fISession#touch()\fR, \fISession#destroy()\fR, \fISession#regenerate()\fR among others to maintain and manipulate sessions\. For more information view the Connect Session \fIhttp://senchalabs\.github\.com/connect/session\.html\fR documentation\.1056+The \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\.1057 .1058 .SS "Migration Guide"1083-Pre\-beta Express developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.1059+Express 1\.x developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.1060 .1061 .SS "req\.header(key[, defaultValue])"1062 Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1063 .8 unmodified lines1072 .fi1073 .1074 .IP "" 01075 .1076+.P1077+The \fIReferrer\fR and \fIReferer\fR header fields are special\-cased, either will work:1078+.1079+.IP "" 41080+.1081+.nf1082+1083+// sent Referrer: http://google\.com1084+1085+req\.header(\'Referer\');1086+// => "http://google\.com"1087+1088+req\.header(\'Referrer\');1089+// => "http://google\.com"1090+.1091+.fi1092+.1093+.IP "" 01094+.1095 .SS "req\.accepts(type)"1096 Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1097 .1098 .P108 unmodified lines1207 .fi1208 .1209 .IP "" 01210 .1216-.SS "req\.param(name)"1217-Return the value of param \fIname\fR when present\.1211+.SS "req\.param(name[, default])"1212+Return the value of param \fIname\fR when present or \fIdefault\fR\.1213 .1214 .IP "\(bu" 41220-Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1215+Checks route params (\fIreq\.params\fR), ex: /user/:id1216 .1217 .IP "\(bu" 41218 Checks query string params (\fIreq\.query\fR), ex: ?id=121219 .2 unmodified lines1222 .1223 .IP "" 01224 .1225 .P1231-To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.1226+To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the _express\.bodyParser middleware\.1227 .1228 .SS "req\.flash(type[, msg])"1229 Queue flash \fImsg\fR of the given \fItype\fR\.1230 .74 unmodified lines1305 .nf1306 1307 var filename = \'path/to/image\.png\';1308 res\.contentType(filename);1314- // res\.headers[\'Content\-Type\'] is now "image/png"1309+ // Content\-Type is now "image/png"1310 .1311 .fi1312 .1313 .IP "" 010 unmodified lines1324 .fi1325 .1326 .IP "" 01327 .1333-.SS "res\.sendfile(path)"1328+.SS "res\.sendfile(path[, options[, callback]])"1329 Used by \fBres\.download()\fR to transfer an arbitrary file\.1330 .1331 .IP "" 41332 .5 unmodified lines1338 .1339 .IP "" 01340 .1341 .P1347-This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed\. When a callback is not given, and the file has \fBnot\fR been streamed, \fInext(err)\fR will be called on an exception\.1342+This 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\.1343 .1344 .IP "" 41345 .1346 .nf1347 1353-res\.sendfile(path, function(err, path){1348+res\.sendfile(path, function(err){1349 if (err) {1355- // handle the error1350+ next(err);1351 } else {1352 console\.log(\'transferred %s\', path);1353 }1354 });2 unmodified lines1357 .1358 .IP "" 01359 .1360 .P1366-When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.1361+Options may also be passed to the internal \fIfs\.createReadStream()\fR call, for example altering the \fIbufferSize\fR:1362 .1363+.IP "" 41364+.1365+.nf1366+1367+res\.sendfile(path, { bufferSize: 1024 }, function(err){1368+ // handle1369+});1370+.1371+.fi1372+.1373+.IP "" 01374+.1368-.SS "res\.download(file[, filename])"1375+.SS "res\.download(file[, filename[, callback]])"1376 Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1377 .1378 .IP "" 41379 .19 unmodified lines1399 .fi1400 .1401 .IP "" 01402 .1403+.P1404+An optional callback may be supplied as either the second or third argument, which is passed to \fIres\.sendfile()\fR:1405+.1406+.IP "" 41407+.1408+.nf1409+1410+res\.download(path, \'expenses\.doc\', function(err){1411+ // handle1412+});1413+.1414+.fi1415+.1416+.IP "" 01417+.1418 .SS "res\.send(body|status[, headers|status[, status]])"1397-The \fBres\.send()\fR method is a high level response utility allowing you to pass objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status code based responses\. The following are all valid uses:1419+The \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:1420 .1421 .IP "" 41422 .1423 .nf13 unmodified lines1437 .P1438 By 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\.1439 .1440 .P1419-Note that this method \fIend()\fR the response, so you will want to use node\'s \fIres\.writeHead()\fR / \fIres\.write()\fR for multiple writes or streaming\.1441+Note that this method \fIend()\fRs the response, so you will want to use node\'s \fIres\.write()\fR for multiple writes or streaming\.1442 .1443 .SS "res\.redirect(url[, status])"1444 Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1445 .14 unmodified lines1460 .P1461 Express 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 "/"\.1462 .1463 .SS "res\.cookie(name, val[, options])"1442-Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1464+Sets the given cookie \fIname\fR to \fIval\fR, with options \fIhttpOnly\fR, \fIsecure\fR, \fIexpires\fR etc\.1465 .1466 .IP "" 41467 .1468 .nf11 unmodified lines1480 .IP "" 41481 .1482 .nf1483 1462-app\.use(express\.cookieDecoder());1484+app\.use(express\.cookieParser());1485 1486 app\.get(\'/\', function(req, res){1465- // use req\.cookies\.rememberme1487+ // use req\.cookies\.rememberme1488 });1489 .1490 .fi1491 .15 unmodified lines1507 .SS "res\.render(view[, options[, fn]])"1508 Render \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\.1509 .1510 .P1489-Most engines accept one or more of the following options, both haml \fIhttp://github\.com/visionmedia/haml\.js\fR and jade \fIhttp://github\.com/visionmedia/jade\fR accept all:1511+The \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:1512 .1491-.IP "\(bu" 41492-\fIscope\fR Template evaluation context (value of \fIthis\fR)1513+.IP "" 41514 .1494-.IP "\(bu" 41495-\fIlocals\fR Object containing local variables1515+.nf1516+1517+var user = { name: \'tj\' };1518+res\.render(\'index\', { layout: false, user: user });1519 .1497-.IP "\(bu" 41498-\fIdebug\fR Output debugging information1520+.fi1521 .1500-.IP "\(bu" 41501-\fIstatus\fR Response status code, defaults to 2001502-.1503-.IP "\(bu" 41504-\fIheaders\fR Response headers object1505-.1522 .IP "" 01523 .1524 .SS "res\.partial(view[, options])"1525 Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.117 unmodified lines1643 .fi1644 .1645 .IP "" 01646 .1647+.P1648+This 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:1649+.1650+.IP "" 41651+.1652+.nf1653+1654+app\.get(\'/users\', function(req, res){1655+ if (req\.xhr) {1656+ // respond with the each user in the collection1657+ // passed to the "user" view1658+ res\.partial(\'user\', users);1659+ } else {1660+ // respond with layout, and users page1661+ // which internally does partial(\'user\', users)1662+ // along with other UI1663+ res\.render(\'users\', { users: users });1664+ }1665+});1666+.1667+.fi1668+.1669+.IP "" 01670+.1671 .SS "res\.local(name[, val])"1672 Get 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\.1673 .1674 .IP "" 463 unmodified lines1738 .fi1739 .1740 .IP "" 01741 .1742+.SS "app\.enabled(name)"1743+Check if setting \fIname\fR is enabled:1744+.1745+.IP "" 41746+.1747+.nf1748+1749+app\.enabled(\'view cache\');1750+// => false1751+1752+app\.enable(\'view cache\');1753+app\.enabled(\'view cache\');1754+// => true1755+.1756+.fi1757+.1758+.IP "" 01759+.1760 .SS "app\.disable(name)"1761 Disable the given setting \fIname\fR:1762 .1763 .IP "" 410 unmodified lines1774 .fi1775 .1776 .IP "" 01777 .1778+.SS "app\.disabled(name)"1779+Check if setting \fIname\fR is disabled:1780+.1781+.IP "" 41782+.1783+.nf1784+1785+app\.enable(\'view cache\');1786+1787+app\.disabled(\'view cache\');1788+// => false1789+1790+app\.disable(\'view cache\');1791+app\.disabled(\'view cache\');1792+// => true1793+.1794+.fi1795+.1796+.IP "" 01797+.1798 .SS "app\.configure(env|function[, function])"1799 Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1800 .1801 .IP "" 412 unmodified lines1814 .1815 .IP "" 01816 .1817 .SS "app\.redirect(name, val)"1740-For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1818+For use with \fIres\.redirect()\fR we can map redirects at the application level as shown below:1819 .1820 .IP "" 41821 .1822 .nf17 unmodified lines1840 .1841 .nf1842 1843 app\.redirect(\'comments\', function(req, res){1766- return \'/post/\' + req\.params\.id + \'/comments\';1844+ return \'/post/\' + req\.params\.id + \'/comments\';1845 });1846 .1847 .fi1848 .6 unmodified lines1855 .1856 .nf1857 1858 app\.get(\'/post/:id\', function(req, res){1781- res\.redirect(\'comments\');1859+ res\.redirect(\'comments\');1860 });1861 .1862 .fi1863 .1864 .IP "" 01865 .1866+.P1867+When 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:1868+.1869+.IP "" 41870+.1871+.nf1872+1873+res\.redirect(\'/posts\');1874+.1875+.fi1876+.1877+.IP "" 01878+.1879 .SS "app\.error(function)"1880 Adds 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:1881 .1882 .IP "" 41883 .1884 .nf1885 1886 app\.error(function(err, req, res, next){1796- res\.send(err\.message, 500);1887+ res\.send(err\.message, 500);1888 });1889 .1890 .fi1891 .1 unmodified line1893 .1894 .SS "app\.helpers(obj)"1895 Registers static view helpers\.1896 .1897+.P1898+app\.helpers({1899+.1900 .IP "" 41901 .1902 .nf1903 1810-app\.helpers({1811- name: function(first, last){ return first + \', \' + last },1812- firstName: \'tj\',1813- lastName: \'holowaychuk\'1904+ name: function(first, last){ return first + \', \' + last }1905+, firstName: \'tj\'1906+, lastName: \'holowaychuk\'1814-});1907 .1908 .fi1909 .1910 .IP "" 01911 .1912 .P1913+});1914+.1915+.P1916 Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1917 .1918 .IP "" 41919 .12 unmodified lines1932 .1933 .nf1934 1935 app\.dynamicHelpers({1841- session: function(req, res){1842- return req\.session;1843- }1936+ session: function(req, res){1937+ return req\.session;1938+ }1939 });1940 .1941 .fi1942 .22 unmodified lines1965 var app = express\.createServer(),1966 blog = express\.createServer();1967 1968 blog\.mounted(function(parent){1874- // parent is app1875- // "this" is blog1969+ // parent is app1970+ // "this" is blog1971 });1972 1973 app\.use(blog);1974 .27 unmodified lines2002 .2003 .IP "" 02004 .2005 .P1911-For engines that do not comply with the Express specification, we can also wrap their api this way\.2006+For engines that do not comply with the Express specification, we can also wrap their api this way\. Below we map \fI\.md\fR to render markdown files, rendering the html once since it will not change on subsequent calls, and support local substitution in the form of "{name}"\.2007 .2008 .IP "" 42009 .2010 .nf2011 1917- app\.register(\'\.foo\', {1918- render: function(str, options) {1919- // perhaps their api is1920- // return foo\.toHTML(str, options);1921- }1922- });2012+ app\.register(\'\.md\', {2013+ compile: function(str, options){2014+ var html = md\.toHTML(str);2015+ return function(locals){2016+ return html\.replace(/\e{([^}]+)\e}/g, function(_, name){2017+ return locals[name];2018+ });2019+ };2020+ }2021+ });2022 .2023 .fi2024 .2025 .IP "" 049 unmodified linesmodified:docs/guide.html+234 added-167 removed
178 unmodified lines179 </a>180 <div id="wrapper">181 <div id="container"><ul id="toc">182 <li><a href="#Installation">Installation</a></li>183-<li><a href="#Creating-An-Application">Creating An Application</a></li>183+<li><a href="#Creating-A-Server">Creating A Server</a></li>184+<li><a href="#Creating-An-HTTPS-Server">Creating An HTTPS Server</a></li>185 <li><a href="#Configuration">Configuration</a></li>186 <li><a href="#Settings">Settings</a></li>187 <li><a href="#Routing">Routing</a></li>188 <li><a href="#Passing-Route-Control">Passing Route Control</a></li>189 <li><a href="#Middleware">Middleware</a></li>190 <li><a href="#Route-Middleware">Route Middleware</a></li>191 <li><a href="#HTTP-Methods">HTTP Methods</a></li>192 <li><a href="#Error-Handling">Error Handling</a></li>192-<li><a href="#Route-Preconditions">Route Preconditions</a></li>193+<li><a href="#Route-Param-Pre-conditions">Route Param Pre-conditions</a></li>194 <li><a href="#View-Rendering">View Rendering</a></li>195 <li><a href="#View-Partials">View Partials</a></li>196 <li><a href="#Template-Engines">Template Engines</a></li>197 <li><a href="#Session-Support">Session Support</a></li>1 unmodified line199 <li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Request</a><ul class="section" id="section-Request">200 <li><a href="#req-header-key-defaultValue-">header()</a></li>201 <li><a href="#req-accepts-type-">accepts()</a></li>202 <li><a href="#req-is-type-">is()</a></li>202-<li><a href="#req-param-name-">param()</a></li>203+<li><a href="#req-param-name-default-">param()</a></li>204 <li><a href="#req-flash-type-msg-">flash()</a></li>205 <li><a href="#req-isXMLHttpRequest">isXMLHttpRequest</a></li>206 </ul></li>207 <li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">208 <li><a href="#res-header-key-val-">header()</a></li>209 <li><a href="#res-contentType-type-">contentType()</a></li>210 <li><a href="#res-attachment-filename-">attachment()</a></li>210-<li><a href="#res-sendfile-path-">sendfile()</a></li>211-<li><a href="#res-download-file-filename-">download()</a></li>211+<li><a href="#res-sendfile-path-options-callback-">sendfile()</a></li>212+<li><a href="#res-download-file-filename-callback-">download()</a></li>213 <li><a href="#res-send-body-status-headers-status-status-">send()</a></li>214 <li><a href="#res-redirect-url-status-">redirect()</a></li>215 <li><a href="#res-cookie-name-val-options-">cookie()</a></li>216 <li><a href="#res-clearCookie-name-">clearCookie()</a></li>3 unmodified lines220 </ul></li>221 <li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Server</a><ul class="section" id="section-Server">222 <li><a href="#app-set-name-val-">set()</a></li>223 <li><a href="#app-enable-name-">enable()</a></li>224+<li><a href="#app-enabled-name-">enabled()</a></li>225 <li><a href="#app-disable-name-">disable()</a></li>226+<li><a href="#app-disabled-name-">disabled()</a></li>227 <li><a href="#app-configure-env-function-function-">configure()</a></li>228 <li><a href="#app-redirect-name-val-">redirect()</a></li>229 <li><a href="#app-error-function-">error()</a></li>230 <li><a href="#app-helpers-obj-">helpers()</a></li>20 unmodified lines251 <code>guide</code>252 </p>253 <h3 id="Installation">Installation</h3>254 252-<p>curl:</p>253-254-<pre><code>$ curl -# http://expressjs.com/install.sh | sh255-</code></pre>256-257-<p>npm:</p>258-255 <pre><code>$ npm install express256 </code></pre>257 262-<h3 id="Creating-An-Application">Creating An Application</h3>258+<h3 id="Creating-A-Server">Creating A Server</h3>259 264-<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however265-follows the same idiom by providing <em>express.createServer()</em> as shown below. This means266-that you can utilize Express server's transparently with other libraries.</p>260+<p> To create an instance of the <em>express.HTTPServer</em>, simply invoke the <em>createServer()</em> method. With our instance <em>app</em> we can then define routes based on the HTTP verbs, in this example <em>app.get()</em>.</p>261 262 <pre><code>var app = require('express').createServer();263 264 app.get('/', function(req, res){271- res.send('hello world');265+ res.send('hello world');266 });267 268 app.listen(3000);269 </code></pre>270 271+<h3 id="Creating-An-HTTPS-Server">Creating An HTTPS Server</h3>272+273+<p> To initialize a <em>express.HTTPSServer</em> we do the same as above, however we274+ pass an options object, accepting <em>key</em>, <em>cert</em> and the others mentioned in node's <a href="http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer">https documentation</a>.</p>275+276+<pre><code> var app = require('express').createServer({ key: ... });277+</code></pre>278+279 <h3 id="Configuration">Configuration</h3>280 281 <p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers282 can use the <em>configure()</em> method to setup needs required by the current environment. When283 <em>configure()</em> is called without an environment name it will be run in <em>every</em> environment284 prior to the environment specific callback.</p>285 286 <p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces285-in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.287+in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.288 Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,287-otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>289+otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>290 291 <pre><code>app.configure(function(){292 app.use(express.methodOverride());291- app.use(express.bodyDecoder());293+ app.use(express.bodyParser());294 app.use(app.router);293- app.use(express.staticProvider(__dirname + '/public'));295 });296 297 app.configure('development', function(){298+ app.use(express.static(__dirname + '/public'));299 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));300 });301 302 app.configure('production', function(){303+ var oneYear = 31557600000;304+ app.use(express.static({ root: __dirname + '/public', maxAge: oneYear }));301- app.use(express.errorHandler());305+ app.use(express.errorHandler());306 });307 </code></pre>308 309 <p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>310 307-<pre><code>app.configure(function(){311+<pre><code> app.configure(function(){312 app.set('views', __dirname + '/views');313 app.set('views');310- // => "... views directory ..."314+ // => "/absolute/path/to/views"315 316 app.enable('some feature');317 // same as app.set('some feature', true);318 319 app.disable('some feature');320 // same as app.set('some feature', false);321+322+ app.enabled('some feature')323+ // => false317-});324+ });325 </code></pre>326 327 <p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>328 6 unmodified lines335 336 <p>Express supports the following settings out of the box:</p>337 338 <ul>332-<li><em>env</em> Application environment set internally, use <em>app.set('env')</em> on <em>Server#listen()</em></li>339 <li><em>home</em> Application base path used for <em>res.redirect()</em> and transparently handling mounted apps.</li>340 <li><em>views</em> Root views directory defaulting to <strong>CWD/views</strong></li>341 <li><em>view engine</em> Default view engine name for views rendered without extensions</li>342 <li><em>view options</em> An object specifying global view options</li>337-<li><em>stream threshold</em> Bytesize indicating when a file should be streamed for <em>res.sendfile()</em> using <em>fs.ReadStream()</em> and <em>sys.pump()</em>.</li>343 </ul>344 345 346 <h3 id="Routing">Routing</h3>69 unmodified lines416 /user/12417 /user/12.json418 </code></pre>419 415-<p>For example we can <strong>POST</strong> some json, and echo the json back using the <em>bodyDecoder</em> middleware which will parse json request bodies (as well as others), and place the result in <em>req.body</em>:</p>420+<p>For example we can <strong>POST</strong> some json, and echo the json back using the <em>bodyParser</em> middleware which will parse json request bodies (as well as others), and place the result in <em>req.body</em>:</p>421 422 <pre><code>var express = require('express')423 , app = express.createServer();424 420-app.use(express.bodyDecoder());425+app.use(express.bodyParser());426 427 app.post('/', function(req, res){428 res.send(req.body);429 });430 431 app.listen(3000);432 </code></pre>433 429-<p>Express 2.0.0-pre also supports named capture groups. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, however say for example we are limiting a user id to digits, we may use <em>'/user/:id(\d+)'</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>434+<p>Typically 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 <em>'/user/:id(\d+)'</em> which will <em>not</em> match unless the placeholder value contains only digits.</p>435 436 <h3 id="Passing-Route-Control">Passing Route Control</h3>437 438 <p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,439 the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,435-and middleware continue to be invoked. The same is true for several routes which have the same path defined, they will simply be executed in order until one does <em>not</em> call <em>next()</em>.</p>440+and middleware continue to be invoked in the order that they are added via <em>use()</em>. The same is true for several routes which have the same path defined, they will simply be executed in order until one does <em>not</em> call <em>next()</em> and decides to respond.</p>441 442 <pre><code>app.get('/users/:id?', function(req, res, next){443 var id = req.params.id;444 if (id) {7 unmodified lines452 // do something else453 });454 </code></pre>455 451-<p>Express 1.0 also introduces the <em>all()</em> method, which provides a route callback matching any HTTP method. This is useful in many ways, one example being the loading of resources before executing subsequent routes as shown below:</p>456+<p>The <em>app.all()</em> 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 <em>req.user</em>.</p>457 458 <pre><code>var express = require('express')459 , app = express.createServer();460 34 unmodified lines495 496 <pre><code> var express = require('express');497 498 var app = express.createServer(494- express.logger(),495- express.bodyDecoder()499+ express.logger()500+ , express.bodyParser()501 );502 </code></pre>503 499-<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks:</p>504+<p>Alternatively we can <em>use()</em> them which is useful when adding middleware within <em>configure()</em> blocks, in a progressive manor.</p>505 506 <pre><code>app.use(express.logger({ format: ':method :uri' }));507 </code></pre>508 509 <p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>510 511 <pre><code>var connect = require('connect');512 app.use(connect.logger());513+app.use(connect.bodyParser());514 </code></pre>515 516 <p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>517 518 <pre><code>app.use(express.logger());519+app.use(express.bodyParser());520 </code></pre>521 522 <h3 id="Route-Middleware">Route Middleware</h3>523 1 unmodified line525 526 <p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>527 528 <pre><code>app.get('/user/:id', function(req, res, next){522- loadUser(req.params.id, function(err, user){523- if (err) return next(err);524- res.send('Viewing user ' + user.name);525- });529+ loadUser(req.params.id, function(err, user){530+ if (err) return next(err);531+ res.send('Viewing user ' + user.name);532+ });533 });534 </code></pre>535 536 <p>To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time.</p>537 538 <pre><code>function loadUser(req, res, next) {532- // You would fetch your user from the db533- var user = users[req.params.id];534- if (user) {535- req.user = user;536- next();537- } else {538- next(new Error('Failed to load user ' + req.params.id));539- }539+ // You would fetch your user from the db540+ var user = users[req.params.id];541+ if (user) {542+ req.user = user;543+ next();544+ } else {545+ next(new Error('Failed to load user ' + req.params.id));546+ }547 }548 549 app.get('/user/:id', loadUser, function(req, res){543- res.send('Viewing user ' + req.user.name);550+ res.send('Viewing user ' + req.user.name);551 });552 </code></pre>553 554 <p>Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.</p>555 556 <pre><code>function andRestrictToSelf(req, res, next) {550- req.authenticatedUser.id == req.user.id551- ? next()552- : next(new Error('Unauthorized'));557+ req.authenticatedUser.id == req.user.id558+ ? next()559+ : next(new Error('Unauthorized'));560 }561 562 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){556- res.send('Editing user ' + req.user.name);563+ res.send('Editing user ' + req.user.name);564 });565 </code></pre>566 567 <p>Keeping in mind that middleware are simply functions, we can define function that <em>returns</em> the middleware in order to create a more expressive and flexible solution as shown below.</p>568 569 <pre><code>function andRestrictTo(role) {563- return function(req, res, next) {564- req.authenticatedUser.role == role565- ? next()566- : next(new Error('Unauthorized'));567- }570+ return function(req, res, next) {571+ req.authenticatedUser.role == role572+ ? next()573+ : next(new Error('Unauthorized'));574+ }575 }576 577 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){571- res.send('Deleted user ' + req.user.name);578+ res.send('Deleted user ' + req.user.name);579 });580 </code></pre>581 582 <p>Commonly used "stacks" of middleware can be passed as an array (<em>applied recursively</em>), which can be mixed and matched to any degree.</p>24 unmodified lines607 <input type="submit" value="Submit" />608 </form>609 </code></pre>610 604-<p>By default Express does not know what to do with this request body, so we should add the <em>bodyDecoder</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>611+<p>By default Express does not know what to do with this request body, so we should add the <em>bodyParser</em> middleware, which will parse <em>application/x-www-form-urlencoded</em> and <em>application/json</em> request bodies and place the variables in <em>req.body</em>. We can do this by "using" the middleware as shown below:</p>612 606-<pre><code>app.use(express.bodyDecoder());613+<pre><code>app.use(express.bodyParser());614 </code></pre>615 616 <p>Our route below will now have access to the <em>req.body.user</em> object which will contain the <em>name</em> and <em>email</em> properties when defined.</p>617 618 <pre><code>app.post('/', function(req, res){612- console.log(req.body.user);613- res.redirect('back');619+ console.log(req.body.user);620+ res.redirect('back');621 });622 </code></pre>623 617-<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyDecoder</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>624+<p>When using methods such as <em>PUT</em> with a form, we can utilize a hidden input named <em>_method</em>, which can be used to alter the HTTP method. To do so we first need the <em>methodOverride</em> middleware, which should be placed below <em>bodyParser</em> so that it can utilize it's <em>req.body</em> containing the form values.</p>625 619-<pre><code>app.use(express.bodyDecoder());626+<pre><code>app.use(express.bodyParser());627 app.use(express.methodOverride());628 </code></pre>629 630 <p>The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as <em>PUT</em> and <em>DELETE</em> can still be accessed by clients which can use them directly, although <em>methodOverride</em> provides a great solution for forms. Below shows what the usage of <em>PUT</em> might look like:</p>17 unmodified lines648 or passed to <em>next(err)</em>. Below is an example which serves different pages based on our649 ad-hoc <em>NotFound</em> exception:</p>650 651 <pre><code>function NotFound(msg){645- this.name = 'NotFound';646- Error.call(this, msg);647- Error.captureStackTrace(this, arguments.callee);652+ this.name = 'NotFound';653+ Error.call(this, msg);654+ Error.captureStackTrace(this, arguments.callee);655 }656 650-sys.inherits(NotFound, Error);657+NotFound.protoype.__proto__ = Error.prototype;658 659 app.get('/404', function(req, res){653- throw new NotFound;660+ throw new NotFound;661 });662 663 app.get('/500', function(req, res){657- throw new Error('keyboard cat!');664+ throw new Error('keyboard cat!');665 });666 </code></pre>667 668 <p>We can call <em>app.error()</em> several times as shown below.14 unmodified lines683 });684 </code></pre>685 686 <p>Here we assume all errors as 500 for the simplicity of680-this demo, however you can choose whatever you like</p>687+this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the <em>error.code</em> of <em>ENOENT</em>, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.</p>688 689 <pre><code>app.error(function(err, req, res){683- res.render('500.jade', {684- locals: {685- error: err686- } 687- });690+ res.render('500.jade', {691+ error: err692+ });693 });694 </code></pre>695 696 <p>Our apps could also utilize the Connect <em>errorHandler</em> middleware11 unmodified lines708 709 <p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>710 is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>711 707-<h3 id="Route-Preconditions">Route Preconditions</h3>712+<h3 id="Route-Param-Pre-conditions">Route Param Pre-conditions</h3>713 709-<p>Route placeholder pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for <em>/user/:id</em>,we might typically do something like below:</p>714+<p>Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for <em>/user/:id</em>, we might typically do something like below:</p>715 716 <pre><code>app.get('/user/:userId', function(req, res, next){717 User.get(req.params.userId, function(err, user){718 if (err) return next(err);1 unmodified line720 });721 }); 722 </code></pre>723 719-<p>With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>724+<p>With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke <em>app.param()</em> with the parameter name we wish to map to some middleware, as you can see we receive the <em>id</em> argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call <em>next()</em> to pass control to the next precondition or route handler.</p>725 726 <pre><code>app.param('userId', function(req, res, next, id){727 User.get(id, function(err, user){728 if (err) return next(err);22 unmodified lines751 </code></pre>752 753 <h3 id="View-Rendering">View Rendering</h3>754 750-<p>View filenames take the form <em>Express</em>.<em>ENGINE</em>, where <em>ENGINE</em> is the name755+<p>View filenames take the form "<name>.<engine>", where <engine> is the name756 of the module that will be required. For example the view <em>layout.ejs</em> will752-tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.render(str, options)</em> to comply with Express, however753-<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.</p>757+tell the view system to <em>require('ejs')</em>, the module being loaded must export the method <em>exports.compile(str, options)</em>, and return a <em>Function</em> to comply with Express. To alter this behaviour758+<em>app.register()</em> can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.</p>759 755-<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,756-and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as757-the <em>body</em> local variable in <em>layout.haml</em>.</p>760+<p>Below is an example using <a href="http://github.com/visionmedia/jade">Jade</a> to render <em>index.html</em>,761+and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as762+the <em>body</em> local variable in <em>layout.jade</em>.</p>763 764 <pre><code>app.get('/', function(req, res){760- res.render('index.haml', {761- locals: { title: 'My Site' }762- });765+ res.render('index.jade', { title: 'My Site' });766 });767 </code></pre>768 769 <p>The new <em>view engine</em> setting allows us to specify our default template engine,767-so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>770+so for example when using jade we could set:</p>771 772 <pre><code>app.set('view engine', 'jade');773 </code></pre>774 15 unmodified lines790 791 <p>Express also provides the <em>view options</em> setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:</p>792 793 <pre><code>app.set('view options', {791- layout: false794+ layout: false795 });796 </code></pre>797 795-<p>Which can then be overridden within the <code>res.render()</code> call if need be:</p>798+<p>Which can then be overridden within the <em>res.render()</em> call if need be:</p>799 800 <pre><code>res.render('myview.ejs', { layout: true });801 </code></pre>802 21 unmodified lines824 </code></pre>825 826 <h3 id="View-Partials">View Partials</h3>827 825-<p>The Express view system has built-in support for partials and collections, which are826-sort of "mini" views representing a document fragment. For example rather than iterating828+<p>The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating829 in a view to display comments, we would use a partial with collection support:</p>830 829-<pre><code>partial('comment.haml', { collection: comments });830-</code></pre>831-832-<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,833-however if we wished we could use an ejs partial, within a haml view for example.</p>834-831 <pre><code>partial('comment', { collection: comments });832 </code></pre>833 838-<p>And once again even further, when rendering a collection we can simply pass839-an array, if no other options are desired:</p>834+<p>If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>835 836 <pre><code>partial('comment', comments);837 </code></pre>838 839 <p>When using the partial collection support a few "magic" variables are provided840 for free:</p>841 842 <ul>848-<li><em>firstInCollection</em> True if this is the first object</li>849-<li><em>indexInCollection</em> Index of the object in the collection</li>850-<li><em>lastInCollection</em> True if this is the last object</li>851-<li><em>collectionLength</em> Length of the collection</li>843+<li><em>firstInCollection</em> true if this is the first object</li>844+<li><em>indexInCollection</em> index of the object in the collection</li>845+<li><em>lastInCollection</em> true if this is the last object</li>846+<li><em>collectionLength</em> length of the collection</li>847 </ul>848 849 850 <p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>851 857-<p>NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead. For example do <em>not</em> implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates.</p>852+<p>NOTE: 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.</p>853 854 <h3 id="Template-Engines">Template Engines</h3>855 856 <p>Below are a few template engines commonly used with Express:</p>857 858 <ul>859 <li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>865-<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>860 <li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>861 <li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>862 <li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>863 </ul>864 865 866 <h3 id="Session-Support">Session Support</h3>867 874-<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieDecoder</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>868+<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieParser</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>869 876-<pre><code>app.use(express.cookieDecoder());877-app.use(express.session());870+<pre><code>app.use(express.cookieParser());871+app.use(express.session({ secret: "keyboard cat" }));872 </code></pre>873 874 <p>By default the <em>session</em> middleware uses the memory store bundled with Connect, however many implementations exist. For example <a href="http://github.com/visionmedia/connect-redis">connect-redis</a> supplies a <a href="http://code.google.com/p/redis/">Redis</a> session store and can be used as shown below:</p>875 876 <pre><code>var RedisStore = require('connect-redis');883-app.use(express.cookieDecoder());884-app.use(express.session({ store: new RedisStore }));877+app.use(express.cookieParser());878+app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));879 </code></pre>880 881 <p>Now the <em>req.session</em> and <em>req.sessionStore</em> properties will be accessible to all routes and subsequent middleware. Properties on <em>req.session</em> are automatically saved on a response, so for example if we wish to shopping cart data:</p>882 883 <pre><code>var RedisStore = require('connect-redis');890-app.use(express.bodyDecoder());891-app.use(express.cookieDecoder());892-app.use(express.session({ store: new RedisStore }));884+app.use(express.bodyParser());885+app.use(express.cookieParser());886+app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));887 888 app.post('/add-to-cart', function(req, res){889 // Perhaps we posted several items with a form896- // (use the bodyDecoder() middleware for this)890+ // (use the bodyParser() middleware for this)891 var items = req.body.items;892 req.session.items = items;893 res.redirect('back');894 });8 unmodified lines903 res.render('shopping-cart');904 });905 </code></pre>906 913-<p>The <em>req.session</em> object also has methods such as <em>Session#touch()</em>, <em>Session#destroy()</em>, <em>Session#regenerate()</em> among others to maintain and manipulate sessions. For more information view the <a href="http://senchalabs.github.com/connect/session.html">Connect Session</a> documentation.</p>907+<p>The <em>req.session</em> object also has methods such as <em>Session#touch()</em>, <em>Session#destroy()</em>, <em>Session#regenerate()</em> among others to maintain and manipulate sessions. For more information view the <a href="http://senchalabs.github.com/connect/middleware-session.html">Connect Session</a> documentation.</p>908 909 <h3 id="Migration-Guide">Migration Guide</h3>910 917-<p> Pre-beta Express developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application.</p>911+<p> Express 1.x developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application.</p>912 913 <h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>914 915 <p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>2 unmodified lines918 req.header('host');919 req.header('Accept', '*/*');920 </code></pre>921 922+<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>923+924+<pre><code>// sent Referrer: http://google.com925+926+req.header('Referer');927+// => "http://google.com"928+929+req.header('Referrer');930+// => "http://google.com"931+</code></pre>932+933 <h3 id="req-accepts-type-">req.accepts(type)</h3>934 935 <p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>936 71 unmodified lines1008 1009 <pre><code>req.is('*/json');1010 </code></pre>1011 1007-<h3 id="req-param-name-">req.param(name)</h3>1012+<h3 id="req-param-name-default-">req.param(name[, default])</h3>1013 1009-<p>Return the value of param <em>name</em> when present.</p>1014+<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>1015 1016 <ul>1012-<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>1017+<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>1018 <li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1019 <li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1020 </ul>1021 1022 1023 <p>To utilize urlencoded request bodies, <em>req.body</em>1024 should be an object. This can be done by using1020-the <em>express.bodyDecoder</em> middleware.</p>1025+the _express.bodyParser middleware.</p>1026 1027 <h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>1028 1029 <p>Queue flash <em>msg</em> of the given <em>type</em>.</p>46 unmodified lines1076 <p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>1077 1078 <pre><code> var filename = 'path/to/image.png';1079 res.contentType(filename);1075- // res.headers['Content-Type'] is now "image/png"1080+ // Content-Type is now "image/png"1081 </code></pre>1082 1083 <h3 id="res-attachment-filename-">res.attachment([filename])</h3>1084 1 unmodified line1086 1087 <pre><code> res.attachment('path/to/my/image.png');1088 </code></pre>1089 1085-<h3 id="res-sendfile-path-">res.sendfile(path)</h3>1090+<h3 id="res-sendfile-path-options-callback-">res.sendfile(path[, options[, callback]])</h3>1091 1092 <p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>1093 1094 <pre><code>res.sendfile('path/to/my.file');1095 </code></pre>1096 1092-<p>This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has <strong>not</strong> been streamed, <em>next(err)</em> will be called on an exception.</p>1097+<p>This method accepts an optional callback which is called when1098+an error occurs, or when the transfer is complete. By default failures call <code>next(err)</code>, however when a callback is supplied you must do this explicitly, or act on the error.</p>1099 1094-<pre><code>res.sendfile(path, function(err, path){1100+<pre><code>res.sendfile(path, function(err){1101 if (err) {1096- // handle the error1102+ next(err);1103 } else {1104 console.log('transferred %s', path);1105 }1106 });1107 </code></pre>1108 1103-<p>When the filesize exceeds the <em>stream threshold</em> (defaulting to 32k), the file will be streamed using <em>fs.ReadStream</em> and <em>sys.pump()</em>.</p>1109+<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>1110 1105-<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>1111+<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1112+ // handle1113+});1114+</code></pre>1115 1116+<h3 id="res-download-file-filename-callback-">res.download(file[, filename[, callback]])</h3>1117+1118 <p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>1119 1120 <pre><code>res.download('path/to/image.png');1121 res.download('path/to/image.png', 'foo.png');4 unmodified lines1126 <pre><code>res.attachment(file);1127 res.sendfile(file);1128 </code></pre>1129 1130+<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>:</p>1131+1132+<pre><code>res.download(path, 'expenses.doc', function(err){1133+ // handle1134+});1135+</code></pre>1136+1137 <h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>1138 1121-<p>The <code>res.send()</code> method is a high level response utility allowing you to pass1122-objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status1123-code based responses. The following are all valid uses:</p>1139+<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1140+objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>1141 1142 <pre><code> res.send(); // 2041143 res.send(new Buffer('wahoo'));1144 res.send({ some: 'json' });6 unmodified lines1151 <p>By default the <em>Content-Type</em> response header is set, however if explicitly1152 assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1153 it will not be set again.</p>1154 1138-<p>Note that this method <em>end()</em> the response, so you will want to use node's <em>res.writeHead()</em> / <em>res.write()</em> for multiple writes or streaming.</p>1155+<p>Note that this method <em>end()</em>s the response, so you will want to use node's <em>res.write()</em> for multiple writes or streaming.</p>1156 1157 <h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>1158 1159 <p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>10 unmodified lines1170 the "home" setting and defaults to "/".</p>1171 1172 <h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>1173 1157-<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>1174+<p>Sets the given cookie <em>name</em> to <em>val</em>, with options <em>httpOnly</em>, <em>secure</em>, <em>expires</em> etc.</p>1175 1176 <pre><code>// "Remember me" for 15 minutes 1177 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1178 </code></pre>1179 1180 <p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>1181 1165-<pre><code>app.use(express.cookieDecoder());1182+<pre><code>app.use(express.cookieParser());1183 1184 app.get('/', function(req, res){1168- // use req.cookies.rememberme1185+ // use req.cookies.rememberme1186 });1187 </code></pre>1188 1189 <h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>8 unmodified lines1198 <p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1199 When a callback function is given a response will <em>not</em> be made1200 automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>1201 1185-<p> Most engines accept one or more of the following options,1186- both <a href="http://github.com/visionmedia/haml.js">haml</a> and <a href="http://github.com/visionmedia/jade">jade</a> accept all:</p>1202+<p>The <em>options</em> 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:</p>1203 1188-<ul>1189-<li><em>scope</em> Template evaluation context (value of <em>this</em>)</li>1190-<li><em>locals</em> Object containing local variables</li>1191-<li><em>debug</em> Output debugging information</li>1192-<li><em>status</em> Response status code, defaults to 200</li>1193-<li><em>headers</em> Response headers object</li>1194-</ul>1204+<pre><code>var user = { name: 'tj' };1205+res.render('index', { layout: false, user: user });1206+</code></pre>1207 1196-1208 <h3 id="res-partial-view-options-">res.partial(view[, options])</h3>1209 1210 <p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1211 to the view as a local variable.</p>64 unmodified lines1276 <pre><code>partial('movie', movie);1277 // => In view: movie.director1278 </code></pre>1279 1280+<p>This 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:</p>1281+1282+<pre><code>app.get('/users', function(req, res){1283+ if (req.xhr) {1284+ // respond with the each user in the collection1285+ // passed to the "user" view1286+ res.partial('user', users);1287+ } else {1288+ // respond with layout, and users page1289+ // which internally does partial('user', users)1290+ // along with other UI1291+ res.render('users', { users: users });1292+ }1293+});1294+</code></pre>1295+1296 <h3 id="res-local-name-val-">res.local(name[, val])</h3>1297 1298 <p>Get or set the given local variable <em>name</em>. The locals built up for a response are applied to those given to the view rendering methods such as <code>res.render()</code>.</p>1299 38 unmodified lines1338 app.enabled('some arbitrary setting');1339 // => true1340 </code></pre>1341 1342+<h3 id="app-enabled-name-">app.enabled(name)</h3>1343+1344+<p>Check if setting <em>name</em> is enabled:</p>1345+1346+<pre><code>app.enabled('view cache');1347+// => false1348+1349+app.enable('view cache');1350+app.enabled('view cache');1351+// => true1352+</code></pre>1353+1354 <h3 id="app-disable-name-">app.disable(name)</h3>1355 1356 <p>Disable the given setting <em>name</em>:</p>1357 4 unmodified lines1362 app.disabled('some setting');1363 // => false1364 </code></pre>1365 1366+<h3 id="app-disabled-name-">app.disabled(name)</h3>1367+1368+<p>Check if setting <em>name</em> is disabled:</p>1369+1370+<pre><code>app.enable('view cache');1371+1372+app.disabled('view cache');1373+// => false1374+1375+app.disable('view cache');1376+app.disabled('view cache');1377+// => true1378+</code></pre>1379+1380 <h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>1381 1382 <p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>1383 7 unmodified lines1391 </code></pre>1392 1393 <h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>1394 1342-<p>For use with <code>res.redirect()</code> we can map redirects at the application level as shown below:</p>1395+<p>For use with <em>res.redirect()</em> we can map redirects at the application level as shown below:</p>1396 1397 <pre><code>app.redirect('google', 'http://google.com');1398 </code></pre>1399 3 unmodified lines1403 1404 <p>We may also map dynamic redirects:</p>1405 1406 <pre><code>app.redirect('comments', function(req, res){1354- return '/post/' + req.params.id + '/comments';1407+ return '/post/' + req.params.id + '/comments';1408 });1409 </code></pre>1410 1411 <p>So now we may do the following, and the redirect will dynamically adjust to1412 the context of the request. If we called this route with <em>GET /post/12</em> our1413 redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>1414 1415 <pre><code>app.get('/post/:id', function(req, res){1363- res.redirect('comments');1416+ res.redirect('comments');1417 });1418 </code></pre>1419 1420+<p>When mounted, <em>res.redirect()</em> will respect the mount-point. For example if a blog app is mounted at <em>/blog</em>, the following will redirect to <em>/blog/posts</em>:</p>1421+1422+<pre><code>res.redirect('/posts');1423+</code></pre>1424+1425 <h3 id="app-error-function-">app.error(function)</h3>1426 1427 <p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1428 Note that we may set several error handlers by making several calls to this method, however the handler1429 should call <em>next(err)</em> if it does not wish to deal with the exception:</p>1430 1431 <pre><code>app.error(function(err, req, res, next){1374- res.send(err.message, 500);1432+ res.send(err.message, 500);1433 });1434 </code></pre>1435 1436 <h3 id="app-helpers-obj-">app.helpers(obj)</h3>1437 1438 <p>Registers static view helpers.</p>1439 1382-<pre><code>app.helpers({1383- name: function(first, last){ return first + ', ' + last },1384- firstName: 'tj',1385- lastName: 'holowaychuk'1386-});1440+<p> app.helpers({</p>1441+1442+<pre><code> name: function(first, last){ return first + ', ' + last }1443+, firstName: 'tj'1444+, lastName: 'holowaychuk'1445 </code></pre>1446 1447+<p> });</p>1448+1449 <p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1450 as well as the <em>name()</em> function exposed.</p>1451 1452 <pre><code><%= name(firstName, lastName) %>6 unmodified lines1459 evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1460 becomes the local variable it is associated with.</p>1461 1462 <pre><code>app.dynamicHelpers({1403- session: function(req, res){1404- return req.session;1405- }1463+ session: function(req, res){1464+ return req.session;1465+ }1466 });1467 </code></pre>1468 1469 <p>All views would now have <em>session</em> available so that session data can be accessed via <em>session.name</em> etc:</p>8 unmodified lines1478 <pre><code>var app = express.createServer(),1479 blog = express.createServer();1480 1481 blog.mounted(function(parent){1422- // parent is app1423- // "this" is blog1482+ // parent is app1483+ // "this" is blog1484 });1485 1486 app.use(blog);1487 </code></pre>15 unmodified lines1503 <pre><code> app.register('.haml', require('haml-js'));1504 </code></pre>1505 1506 <p>For engines that do not comply with the Express1447-specification, we can also wrap their api this way.</p>1507+specification, we can also wrap their api this way. Below1508+we map <em>.md</em> to render markdown files, rendering the html once1509+since it will not change on subsequent calls, and support local substitution1510+in the form of "{name}".</p>1511 1449-<pre><code> app.register('.foo', {1450- render: function(str, options) {1451- // perhaps their api is1452- // return foo.toHTML(str, options);1453- }1454- });1512+<pre><code> app.register('.md', {1513+ compile: function(str, options){1514+ var html = md.toHTML(str);1515+ return function(locals){1516+ return html.replace(/\{([^}]+)\}/g, function(_, name){1517+ return locals[name];1518+ });1519+ };1520+ }1521+ });1522 </code></pre>1523 1524 <h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>1525 30 unmodified linesmodified:docs/guide.md+243 added-184 removed
1 2 ### Installation3 4-curl:5-6- $ curl -# http://expressjs.com/install.sh | sh7-8-npm:9-4 $ npm install express5 12-### Creating An Application6+### Creating A Server7 14-The _express.Server_ now inherits from _http.Server_, however15-follows the same idiom by providing _express.createServer()_ as shown below. This means16-that you can utilize Express server's transparently with other libraries.8+ To create an instance of the _express.HTTPServer_, simply invoke the _createServer()_ method. With our instance _app_ we can then define routes based on the HTTP verbs, in this example _app.get()_.9 10 var app = require('express').createServer();19- 20- app.get('/', function(req, res){21- res.send('hello world');22- });23- 24- app.listen(3000);11+ 12+ app.get('/', function(req, res){13+ res.send('hello world');14+ });15+ 16+ app.listen(3000);17 18+### Creating An HTTPS Server19+20+ To initialize a _express.HTTPSServer_ we do the same as above, however we21+ pass an options object, accepting _key_, _cert_ and the others mentioned in node's [https documentation](http://nodejs.org/docs/v0.3.7/api/https.html#https.createServer).22+ 23+ var app = require('express').createServer({ key: ... });24+25 ### Configuration26 27 Express supports arbitrary environments, such as _production_ and _development_. Developers28 can use the _configure()_ method to setup needs required by the current environment. When29 _configure()_ is called without an environment name it will be run in _every_ environment 30 prior to the environment specific callback.31 32 In the example below we only _dumpExceptions_, and respond with exception stack traces34-in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.33+in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.34 Note the use of _app.router_, which can (optionally) be used to mount the application routes,36-otherwise the first call to _app.{get,put,del,post}()_ will mount the routes.35+otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.36 37 app.configure(function(){38 app.use(express.methodOverride());40- app.use(express.bodyDecoder());39+ app.use(express.bodyParser());40 app.use(app.router);41 });42 43 app.configure('development', function(){45- app.use(express.staticProvider(__dirname + '/public'));44+ app.use(express.static(__dirname + '/public'));45 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));46 });47 49- app.configure('production', function(){50- var oneYear = 31557600000;51- app.use(express.staticProvider({ root: __dirname + '/public', maxAge: oneYear }));52- app.use(express.errorHandler());53- });48+ app.configure('production', function(){49+ var oneYear = 31557600000;50+ app.use(express.static({ root: __dirname + '/public', maxAge: oneYear }));51+ app.use(express.errorHandler());52+ });53 54 For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:55 57- app.configure(function(){58- app.set('views', __dirname + '/views');59- app.set('views');60- // => "... views directory ..."61- 62- app.enable('some feature');63- // same as app.set('some feature', true);64- 65- app.disable('some feature');66- // same as app.set('some feature', false);67- });56+ app.configure(function(){57+ app.set('views', __dirname + '/views');58+ app.set('views');59+ // => "/absolute/path/to/views"60+ 61+ app.enable('some feature');62+ // same as app.set('some feature', true);63+ 64+ app.disable('some feature');65+ // same as app.set('some feature', false);66+ 67+ app.enabled('some feature')68+ // => false69+ });70 71 To alter the environment we can set the _NODE_ENV_ environment variable, for example:72 73 $ NODE_ENV=production node app.js3 unmodified lines77 ### Settings78 79 Express supports the following settings out of the box:80 79- * _env_ Application environment set internally, use _app.set('env')_ on _Server#listen()_81 * _home_ Application base path used for _res.redirect()_ and transparently handling mounted apps.82 * _views_ Root views directory defaulting to **CWD/views**83 * _view engine_ Default view engine name for views rendered without extensions84 * _view options_ An object specifying global view options66 unmodified lines151 "/user/:id.:format?"152 /user/12153 /user/12.json154 154-For example we can __POST__ some json, and echo the json back using the _bodyDecoder_ middleware which will parse json request bodies (as well as others), and place the result in _req.body_:155+For example we can __POST__ some json, and echo the json back using the _bodyParser_ middleware which will parse json request bodies (as well as others), and place the result in _req.body_:156 157 var express = require('express')158 , app = express.createServer();159 159- app.use(express.bodyDecoder());160+ app.use(express.bodyParser());161 162 app.post('/', function(req, res){163 res.send(req.body);164 });165 166 app.listen(3000);167 167-Express 2.0.0-pre also supports named capture groups. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, however say for example we are limiting a user id to digits, we may use _'/user/:id(\\d+)'_ which will _not_ match unless the placeholder value contains only digits.168+Typically 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 _'/user/:id(\\d+)'_ which will _not_ match unless the placeholder value contains only digits.169 170 ### Passing Route Control171 172 We may pass control to the next _matching_ route, by calling the _third_ argument,173 the _next()_ function. When a match cannot be made, control is passed back to Connect,173-and middleware continue to be invoked. The same is true for several routes which have the same path defined, they will simply be executed in order until one does _not_ call _next()_.174+and middleware continue to be invoked in the order that they are added via _use()_. The same is true for several routes which have the same path defined, they will simply be executed in order until one does _not_ call _next()_ and decides to respond.175 176 app.get('/users/:id?', function(req, res, next){177 var id = req.params.id;178 if (id) {6 unmodified lines185 app.get('/users', function(req, res){186 // do something else187 });188 188-Express 1.0 also introduces the _all()_ method, which provides a route callback matching any HTTP method. This is useful in many ways, one example being the loading of resources before executing subsequent routes as shown below:189+The _app.all()_ 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 _req.user_.190 191 var express = require('express')192 , app = express.createServer();193 33 unmodified lines227 228 var express = require('express');229 230 var app = express.createServer(230- express.logger(),231- express.bodyDecoder()231+ express.logger()232+ , express.bodyParser()233 );234 234-Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:235+Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.236 237 app.use(express.logger({ format: ':method :uri' }));238 239 Typically with connect middleware you would _require('connect')_ like so:240 241 var connect = require('connect');242 app.use(connect.logger());243+ app.use(connect.bodyParser());244 245 This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:246 247 app.use(express.logger());248+ app.use(express.bodyParser());249 250 ### Route Middleware251 252 Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.253 254 Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 255 256 app.get('/user/:id', function(req, res, next){254- loadUser(req.params.id, function(err, user){255- if (err) return next(err);256- res.send('Viewing user ' + user.name);257- });257+ loadUser(req.params.id, function(err, user){258+ if (err) return next(err);259+ res.send('Viewing user ' + user.name);260+ });261 });262 263 To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time. 264 265 function loadUser(req, res, next) {263- // You would fetch your user from the db264- var user = users[req.params.id];265- if (user) {266- req.user = user;267- next();268- } else {269- next(new Error('Failed to load user ' + req.params.id));270- }266+ // You would fetch your user from the db267+ var user = users[req.params.id];268+ if (user) {269+ req.user = user;270+ next();271+ } else {272+ next(new Error('Failed to load user ' + req.params.id));273+ }274 }275 276 app.get('/user/:id', loadUser, function(req, res){274- res.send('Viewing user ' + req.user.name);277+ res.send('Viewing user ' + req.user.name);278 });279 280 Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.281 282 function andRestrictToSelf(req, res, next) {280- req.authenticatedUser.id == req.user.id281- ? next()282- : next(new Error('Unauthorized'));283+ req.authenticatedUser.id == req.user.id284+ ? next()285+ : next(new Error('Unauthorized'));286 }287 288 app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){286- res.send('Editing user ' + req.user.name);289+ res.send('Editing user ' + req.user.name);290 });291 292 Keeping in mind that middleware are simply functions, we can define function that _returns_ the middleware in order to create a more expressive and flexible solution as shown below.293 294 function andRestrictTo(role) {292- return function(req, res, next) {293- req.authenticatedUser.role == role294- ? next()295- : next(new Error('Unauthorized'));296- }295+ return function(req, res, next) {296+ req.authenticatedUser.role == role297+ ? next()298+ : next(new Error('Unauthorized'));299+ }300 }301 302 app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){300- res.send('Deleted user ' + req.user.name);303+ res.send('Deleted user ' + req.user.name);304 });305 306 Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.307 21 unmodified lines329 <input type="text" name="user[email]" />330 <input type="submit" value="Submit" />331 </form>332 330-By default Express does not know what to do with this request body, so we should add the _bodyDecoder_ middleware, which will parse _application/x-www-form-urlencoded_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:333+By default Express does not know what to do with this request body, so we should add the _bodyParser_ middleware, which will parse _application/x-www-form-urlencoded_ and _application/json_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:334 332- app.use(express.bodyDecoder());335+ app.use(express.bodyParser());336 337 Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.338 339 app.post('/', function(req, res){337- console.log(req.body.user);338- res.redirect('back');340+ console.log(req.body.user);341+ res.redirect('back');342 });343 341-When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyDecoder_ so that it can utilize it's _req.body_ containing the form values.344+When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyParser_ so that it can utilize it's _req.body_ containing the form values.345 343- app.use(express.bodyDecoder());346+ app.use(express.bodyParser());347 app.use(express.methodOverride());348 349 The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as _PUT_ and _DELETE_ can still be accessed by clients which can use them directly, although _methodOverride_ provides a great solution for forms. Below shows what the usage of _PUT_ might look like:350 14 unmodified lines365 Express provides the _app.error()_ method which receives exceptions thrown within a route,366 or passed to _next(err)_. Below is an example which serves different pages based on our367 ad-hoc _NotFound_ exception:368 366- function NotFound(msg){367- this.name = 'NotFound';368- Error.call(this, msg);369- Error.captureStackTrace(this, arguments.callee);370- }369+ function NotFound(msg){370+ this.name = 'NotFound';371+ Error.call(this, msg);372+ Error.captureStackTrace(this, arguments.callee);373+ }374+ 375+ NotFound.protoype.__proto__ = Error.prototype;376+ 377+ app.get('/404', function(req, res){378+ throw new NotFound;379+ });380+ 381+ app.get('/500', function(req, res){382+ throw new Error('keyboard cat!');383+ });384 372- sys.inherits(NotFound, Error);373-374- app.get('/404', function(req, res){375- throw new NotFound;376- });377-378- app.get('/500', function(req, res){379- throw new Error('keyboard cat!');380- });381-385 We can call _app.error()_ several times as shown below.386 Here we check for an instanceof _NotFound_ and show the387 404 page, or we pass on to the next error handler.388 10 unmodified lines399 }400 });401 402 Here we assume all errors as 500 for the simplicity of400-this demo, however you can choose whatever you like403+this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the _error.code_ of _ENOENT_, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.404 402- app.error(function(err, req, res){403- res.render('500.jade', {404- locals: {405- error: err406- } 407- });408- });405+ app.error(function(err, req, res){406+ res.render('500.jade', {407+ error: err408+ });409+ });410 411 Our apps could also utilize the Connect _errorHandler_ middleware412 to report on exceptions. For example if we wish to output exceptions 413 in "development" mode to _stderr_ we can use:7 unmodified lines421 422 The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_423 is present, which is useful for developing apps that rely heavily on client-side JavaScript.424 424-### Route Preconditions425+### Route Param Pre-conditions426 426-Route placeholder pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_,we might typically do something like below:427+Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_, we might typically do something like below:428 429 app.get('/user/:userId', function(req, res, next){430 User.get(req.params.userId, function(err, user){431 if (err) return next(err);432 res.send('user ' + user.name);433 });434 }); 435 435-With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.436+With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.437 438 app.param('userId', function(req, res, next, id){439 User.get(id, function(err, user){440 if (err) return next(err);18 unmodified lines459 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });460 461 ### View Rendering462 462-View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name463+View filenames take the form "<name>.<engine>", where <engine> is the name464 of the module that will be required. For example the view _layout.ejs_ will464-tell the view system to _require('ejs')_, the module being loaded must export the method _exports.render(str, options)_ to comply with Express, however 465-_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by jade.465+tell the view system to _require('ejs')_, the module being loaded must export the method _exports.compile(str, options)_, and return a _Function_ to comply with Express. To alter this behaviour466+_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.467 467-Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,468-and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 469-the _body_ local variable in _layout.haml_.468+Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,469+and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 470+the _body_ local variable in _layout.jade_.471 472 app.get('/', function(req, res){472- res.render('index.haml', {473- locals: { title: 'My Site' }474- });473+ res.render('index.jade', { title: 'My Site' });474 });475 476 The new _view engine_ setting allows us to specify our default template engine,478-so for example when using [Jade](http://github.com/visionmedia/jade) we could set:477+so for example when using jade we could set:478 479 app.set('view engine', 'jade');480 481 Allowing us to render with:11 unmodified lines493 494 Express also provides the _view options_ setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:495 496 app.set('view options', {498- layout: false497+ layout: false498 });499 501-Which can then be overridden within the `res.render()` call if need be:500+Which can then be overridden within the _res.render()_ call if need be:501 502 res.render('myview.ejs', { layout: true });503 504 When an alternate layout is required, we may also specify a path. For example if we have _view engine_ set to _jade_ and a file named _./views/mylayout.jade_ we can simply pass:16 unmodified lines521 });522 523 ### View Partials524 526-The Express view system has built-in support for partials and collections, which are527-sort of "mini" views representing a document fragment. For example rather than iterating525+The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating526 in a view to display comments, we would use a partial with collection support:527 530- partial('comment.haml', { collection: comments });531-532-To make things even less verbose we can assume the extension as _.haml_ when omitted,533-however if we wished we could use an ejs partial, within a haml view for example.534-528 partial('comment', { collection: comments });529 537-And once again even further, when rendering a collection we can simply pass538-an array, if no other options are desired:530+If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:531 532 partial('comment', comments);533 534 When using the partial collection support a few "magic" variables are provided535 for free:536 545- * _firstInCollection_ True if this is the first object546- * _indexInCollection_ Index of the object in the collection547- * _lastInCollection_ True if this is the last object548- * _collectionLength_ Length of the collection537+ * _firstInCollection_ true if this is the first object538+ * _indexInCollection_ index of the object in the collection539+ * _lastInCollection_ true if this is the last object540+ * _collectionLength_ length of the collection541 542 For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).543 552-NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead. For example do _not_ implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates.544+NOTE: 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.545 546 ### Template Engines547 548 Below are a few template engines commonly used with Express:549 550 * [Jade](http://jade-lang.com) haml.js successor559- * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templates551 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript552 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating553 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node554 555 ### Session Support556 566-Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieDecoder_ middleware place above it, which will parse and populate cookie data to _req.cookies_.557+Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieParser_ middleware place above it, which will parse and populate cookie data to _req.cookies_.558 568- app.use(express.cookieDecoder());569- app.use(express.session());559+ app.use(express.cookieParser());560+ app.use(express.session({ secret: "keyboard cat" }));561 562 By default the _session_ middleware uses the memory store bundled with Connect, however many implementations exist. For example [connect-redis](http://github.com/visionmedia/connect-redis) supplies a [Redis](http://code.google.com/p/redis/) session store and can be used as shown below:563 564 var RedisStore = require('connect-redis');574- app.use(express.cookieDecoder());575- app.use(express.session({ store: new RedisStore }));565+ app.use(express.cookieParser());566+ app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));567 568 Now the _req.session_ and _req.sessionStore_ properties will be accessible to all routes and subsequent middleware. Properties on _req.session_ are automatically saved on a response, so for example if we wish to shopping cart data:569 570 var RedisStore = require('connect-redis');580- app.use(express.bodyDecoder());581- app.use(express.cookieDecoder());582- app.use(express.session({ store: new RedisStore }));571+ app.use(express.bodyParser());572+ app.use(express.cookieParser());573+ app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));574 575 app.post('/add-to-cart', function(req, res){576 // Perhaps we posted several items with a form586- // (use the bodyDecoder() middleware for this)577+ // (use the bodyParser() middleware for this)578 var items = req.body.items;579 req.session.items = items;580 res.redirect('back');581 });7 unmodified lines589 }590 res.render('shopping-cart');591 });592 602-The _req.session_ object also has methods such as _Session#touch()_, _Session#destroy()_, _Session#regenerate()_ among others to maintain and manipulate sessions. For more information view the [Connect Session](http://senchalabs.github.com/connect/session.html) documentation.593+The _req.session_ object also has methods such as _Session#touch()_, _Session#destroy()_, _Session#regenerate()_ among others to maintain and manipulate sessions. For more information view the [Connect Session](http://senchalabs.github.com/connect/middleware-session.html) documentation.594 595 ### Migration Guide596 606- Pre-beta Express developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.597+ Express 1.x developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.598 599 ### req.header(key[, defaultValue])600 601 Get the case-insensitive request header _key_, with optional _defaultValue_:1 unmodified line603 req.header('Host');604 req.header('host');605 req.header('Accept', '*/*');606 607+The _Referrer_ and _Referer_ header fields are special-cased, either will work:608+609+ // sent Referrer: http://google.com610+611+ req.header('Referer');612+ // => "http://google.com"613+614+ req.header('Referrer');615+ // => "http://google.com"616+617 ### req.accepts(type)618 619 Check if the _Accept_ header is present, and includes the given _type_.620 69 unmodified lines690 ### req.param(name[, default])691 692 Return the value of param _name_ when present or _default_.693 693- - Checks route placeholders (_req.params_), ex: /user/:id694+ - Checks route params (_req.params_), ex: /user/:id695 - Checks query string params (_req.query_), ex: ?id=12696 - Checks urlencoded body params (_req.body_), ex: id=12697 698 To utilize urlencoded request bodies, _req.body_699 should be an object. This can be done by using699-the _express.bodyDecoder_ middleware.700+the _express.bodyParser middleware.701 702 ### req.flash(type[, msg])703 704 Queue flash _msg_ of the given _type_.30 unmodified lines735 736 res.header('Content-Length');737 // => undefined738 738- res.header('Content-Length', 123);739+ res.header('Content-Length', 123);740 // => 123740-741+ 742 res.header('Content-Length');743 // => 123744 745 ### res.contentType(type)1 unmodified line747 Sets the _Content-Type_ response header to the given _type_.748 749 var filename = 'path/to/image.png';750 res.contentType(filename);750- // res.headers['Content-Type'] is now "image/png"751+ // Content-Type is now "image/png"752 753 ### res.attachment([filename])754 755 Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.756 757 res.attachment('path/to/my/image.png');758 758-### res.sendfile(path)759+### res.sendfile(path[, options[, callback]])760 761 Used by `res.download()` to transfer an arbitrary file. 762 763 res.sendfile('path/to/my.file');764 764-This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed. When a callback is not given, and the file has __not__ been streamed, _next(err)_ will be called on an exception.765+This method accepts an optional callback which is called when766+an error occurs, or when the transfer is complete. By default failures call `next(err)`, however when a callback is supplied you must do this explicitly, or act on the error.767 766- res.sendfile(path, function(err, path){768+ res.sendfile(path, function(err){769 if (err) {768- // handle the error770+ next(err);771 } else {772 console.log('transferred %s', path);773 }774 });775 774-### res.download(file[, filename])776+Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:777 778+ res.sendfile(path, { bufferSize: 1024 }, function(err){779+ // handle780+ });781+782+### res.download(file[, filename[, callback]])783+784 Transfer the given _file_ as an attachment with optional alternative _filename_.785 786 res.download('path/to/image.png');787 res.download('path/to/image.png', 'foo.png');2 unmodified lines790 791 res.attachment(file);792 res.sendfile(file);793 794+An optional callback may be supplied as either the second or third argument, which is passed to _res.sendfile()_:795+796+ res.download(path, 'expenses.doc', function(err){797+ // handle798+ });799+800 ### res.send(body|status[, headers|status[, status]])801 788-The `res.send()` method is a high level response utility allowing you to pass789-objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status790-code based responses. The following are all valid uses:802+The _res.send()_ method is a high level response utility allowing you to pass803+objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:804 805 res.send(); // 204806 res.send(new Buffer('wahoo'));807 res.send({ some: 'json' });5 unmodified lines813 By default the _Content-Type_ response header is set, however if explicitly814 assigned through `res.send()` or previously with `res.header()` or `res.contentType()`815 it will not be set again.816 804-Note that this method _end()_ the response, so you will want to use node's _res.writeHead()_ / _res.write()_ for multiple writes or streaming.817+Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.818 819 ### res.redirect(url[, status])820 821 Redirect to the given _url_ with a default response _status_ of 302.9 unmodified lines831 the "home" setting and defaults to "/".832 833 ### res.cookie(name, val[, options])834 822-Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.835+Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc.836 837 // "Remember me" for 15 minutes 838 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });839 840 To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:841 829- app.use(express.cookieDecoder());842+ app.use(express.cookieParser());843 844 app.get('/', function(req, res){832- // use req.cookies.rememberme845+ // use req.cookies.rememberme846 });847 848 ### res.clearCookie(name)849 6 unmodified lines856 Render _view_ with the given _options_ and optional callback _fn_.857 When a callback function is given a response will _not_ be made858 automatically, however otherwise a response of _200_ and _text/html_ is given.859 847- Most engines accept one or more of the following options,848- both [haml](http://github.com/visionmedia/haml.js) and [jade](http://github.com/visionmedia/jade) accept all:860+The _options_ 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:861 850- - _scope_ Template evaluation context (value of _this_)851- - _locals_ Object containing local variables852- - _debug_ Output debugging information853- - _status_ Response status code, defaults to 200854- - _headers_ Response headers object862+ var user = { name: 'tj' };863+ res.render('index', { layout: false, user: user });864 865 ### res.partial(view[, options])866 867 Render _view_ partial with the given _options_. This method is always available53 unmodified lines921 922 partial('movie', movie);923 // => In view: movie.director924 925+This 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:926+927+ app.get('/users', function(req, res){928+ if (req.xhr) {929+ // respond with the each user in the collection930+ // passed to the "user" view931+ res.partial('user', users);932+ } else {933+ // respond with layout, and users page934+ // which internally does partial('user', users)935+ // along with other UI936+ res.render('users', { users: users });937+ }938+ });939+940 ### res.local(name[, val])941 942 Get or set the given local variable _name_. The locals built up for a response are applied to those given to the view rendering methods such as `res.render()`.943 34 unmodified lines978 979 app.enabled('some arbitrary setting');980 // => true981 982+### app.enabled(name)983+984+Check if setting _name_ is enabled:985+986+ app.enabled('view cache');987+ // => false988+989+ app.enable('view cache');990+ app.enabled('view cache');991+ // => true992+993 ### app.disable(name)994 995 Disable the given setting _name_:996 3 unmodified lines1000 1001 app.disabled('some setting');1002 // => false1003 1004+### app.disabled(name)1005+1006+Check if setting _name_ is disabled:1007+1008+ app.enable('view cache');1009+1010+ app.disabled('view cache');1011+ // => false1012+1013+ app.disable('view cache');1014+ app.disabled('view cache');1015+ // => true1016+1017 ### app.configure(env|function[, function])1018 1019 Define a callback function for the given _env_ (or all environments) with callback _function_:1020 6 unmodified lines1027 });1028 1029 ### app.redirect(name, val)1030 983-For use with `res.redirect()` we can map redirects at the application level as shown below:1031+For use with _res.redirect()_ we can map redirects at the application level as shown below:1032 1033 app.redirect('google', 'http://google.com');1034 1035 Now in a route we may call:2 unmodified lines1038 1039 We may also map dynamic redirects:1040 1041 app.redirect('comments', function(req, res){994- return '/post/' + req.params.id + '/comments';1042+ return '/post/' + req.params.id + '/comments';1043 });1044 1045 So now we may do the following, and the redirect will dynamically adjust to1046 the context of the request. If we called this route with _GET /post/12_ our1047 redirect _Location_ would be _/post/12/comments_.1048 1049 app.get('/post/:id', function(req, res){1002- res.redirect('comments');1050+ res.redirect('comments');1051 });1052 1053+When mounted, _res.redirect()_ will respect the mount-point. For example if a blog app is mounted at _/blog_, the following will redirect to _/blog/posts_:1054+1055+ res.redirect('/posts');1056+1057 ### app.error(function)1058 1059 Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1060 Note that we may set several error handlers by making several calls to this method, however the handler1061 should call _next(err)_ if it does not wish to deal with the exception:1062 1063 app.error(function(err, req, res, next){1012- res.send(err.message, 500);1013- });1064+ res.send(err.message, 500);1065+ });1066 1067 ### app.helpers(obj)1068 1069 Registers static view helpers.1070 1019- app.helpers({1020- name: function(first, last){ return first + ', ' + last },1021- firstName: 'tj',1022- lastName: 'holowaychuk'1023- });1071+ app.helpers({1072+ name: function(first, last){ return first + ', ' + last }1073+ , firstName: 'tj'1074+ , lastName: 'holowaychuk'1075+ });1076 1077 Our view could now utilize the _firstName_ and _lastName_ variables,1078 as well as the _name()_ function exposed.1079 6 unmodified lines1086 evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1087 becomes the local variable it is associated with.1088 1089 app.dynamicHelpers({1038- session: function(req, res){1039- return req.session;1040- }1090+ session: function(req, res){1091+ return req.session;1092+ }1093 });1094 1095 All views would now have _session_ available so that session data can be accessed via _session.name_ etc:1096 6 unmodified lines1103 var app = express.createServer(),1104 blog = express.createServer();1105 1106 blog.mounted(function(parent){1055- // parent is app1056- // "this" is blog1107+ // parent is app1108+ // "this" is blog1109 });1110 1111 app.use(blog);1112 12 unmodified lines1125 1126 app.register('.haml', require('haml-js'));1127 1128 For engines that do not comply with the Express1077-specification, we can also wrap their api this way.1129+specification, we can also wrap their api this way. Below1130+we map _.md_ to render markdown files, rendering the html once1131+since it will not change on subsequent calls, and support local substitution1132+in the form of "{name}".1133 1079- app.register('.foo', {1080- render: function(str, options) {1081- // perhaps their api is1082- // return foo.toHTML(str, options);1083- }1084- });1134+ app.register('.md', {1135+ compile: function(str, options){1136+ var html = md.toHTML(str);1137+ return function(locals){1138+ return html.replace(/\{([^}]+)\}/g, function(_, name){1139+ return locals[name];1140+ });1141+ };1142+ }1143+ });1144 1145 ### app.listen([port[, host]])1146 1147 Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all20 unmodified linesmodified:docs/index.1+4 added-4 removed
1 .\" generated with Ronn/v0.7.32 .\" http://github.com/rtomayko/ronn/tree/0.7.33 .4-.TH "INDEX" "" "December 2010" "" ""4+.TH "INDEX" "" "March 2011" "" ""5 .6 .SH "NAME"7 \fBindex\fR8 .30 unmodified lines39 .IP "\(bu" 440 Content negotiation41 .42 .IP "\(bu" 443+Application mounting44+.45+.IP "\(bu" 446 Focus on high performance47 .48 .IP "\(bu" 449 View rendering and partials support40 unmodified lines90 .IP "\(bu" 491 Follow tjholowaychuk \fIhttp://twitter\.com/tjholowaychuk\fR on twitter for updates92 .93 .IP "\(bu" 491-Annotated source documentation \fIapi\.html\fR92-.93-.IP "\(bu" 494 View the Connect \fIhttp://github\.com/senchalabs/connect\fR repo for middleware usage95 .96 .IP "\(bu" 497 View the Connect Wiki \fIhttp://wiki\.github\.com/senchalabs/connect/\fR for contrib middleware12 unmodified linesmodified:docs/index.html+1 added-1 removed
210 unmodified lines211 <li>Redirection helpers</li>212 <li>Dynamic view helpers</li>213 <li>Application level view options</li>214 <li>Content negotiation</li>215+<li>Application mounting</li>216 <li>Focus on high performance</li>217 <li>View rendering and partials support</li>218 <li>Environment based configuration</li>219 <li>Session based flash notifications</li>19 unmodified lines239 240 <ul>241 <li><a href="http://groups.google.com/group/express-js">Google Group</a> for discussion</li>242 <li>Follow <a href="http://twitter.com/tjholowaychuk">tjholowaychuk</a> on twitter for updates</li>242-<li>Annotated source <a href="api.html">documentation</a></li>243 <li>View the <a href="http://github.com/senchalabs/connect">Connect</a> repo for middleware usage</li>244 <li>View the <a href="http://wiki.github.com/senchalabs/connect/">Connect Wiki</a> for contrib middleware</li>245 <li>View the <a href="http://github.com/visionmedia/express/tree/master/examples/">examples</a></li>246 <li>View the <a href="http://github.com/visionmedia/express">source</a></li>9 unmodified linesmodified:docs/index.md+1 added
12 unmodified lines13141516171819202122 unmodified lines12 unmodified lines * Redirection helpers * Dynamic view helpers * Application level view options * Content negotiation * Application mounting * Focus on high performance * View rendering and partials support * Environment based configuration * Session based flash notifications22 unmodified linesdeleted:examples/ejs/views/users/index.ejs-3 removed
1-<ul id="users">2- <%- partial('user', users) %>3-</ul>added:examples/ejs/views/users/index.html+3 added
123<ul id="users"> <%- partial('user', users) %></ul>No newline at end of filedeleted:examples/ejs/views/users/user.ejs-1 removed
1-<li><%= user.name %> <<%= user.email %>></li>added:examples/ejs/views/users/user.html+1 added
1+<li><%= user.name %> <<%= user.email %>></li>deleted:examples/ejs/views/layout.ejs-6 removed
1-<html>2- <body>3- <h1>Users</h1>4- <%- body %>5- </body>6-</html>added:examples/ejs/views/layout.html+6 added
1+<html>2+ <body>3+ <h1>Users</h1>4+ <%- body %>5+ </body>6+</html>modified:examples/ejs/app.js+6 added-1 removed
8 unmodified lines9 var express = require('../../lib/express');10 11 var app = express.createServer();12 13+// Register ejs as .html14+15+app.register('.html', require('ejs'));16+17 // Optional since express defaults to CWD/views18 19 app.set('views', __dirname + '/views');20+app.set('view engine', 'html');21 22 // Dummy users23 var users = [24 { name: 'tj', email: 'tj@sencha.com' }1 unmodified line26 , { name: 'aaron', email: 'aaron.heckmann+github@gmail.com' }27 ];28 29 app.get('/', function(req, res){25- res.render('users.ejs', { users: users });30+ res.render('users', { users: users });31 });32 33 app.listen(3000);34 console.log('Express app started on port 3000');added:examples/markdown/views/index.md+4 added
1+2+# {title}3+4+Just an example view rendered with _markdown_.added:examples/markdown/app.js+41 added
1+2+// Expose modules in ./support for demo purposes3+require.paths.unshift(__dirname + '/../../support');4+5+// $ npm install markdown6+7+/**8+ * Module dependencies.9+ */10+11+var express = require('../../lib/express')12+ , md = require('markdown').markdown;13+14+var app = express.createServer();15+16+// register .md so that markdown may comply17+// with the express view system by implementing18+// a .compile() method19+20+app.register('.md', {21+ compile: function(str, options){22+ var html = md.toHTML(str);23+ return function(locals){24+ return html.replace(/\{([^}]+)\}/g, function(_, name){25+ return locals[name];26+ });27+ };28+ }29+});30+31+// Optional since express defaults to CWD/views32+33+app.set('views', __dirname + '/views');34+app.set('view engine', 'md');35+36+app.get('/', function(req, res){37+ res.render('index', { layout: false, title: 'Markdown Example' });38+});39+40+app.listen(3000);41+console.log('Express app started on port 3000');modified:lib/view/view.js-10 removed
174 unmodified lines175 * of layout.hamljs, we can register the engine as ".haml":176 *177 * app.register('.haml', require('haml-js'));178 *179- * For engines that do not comply with the Express180- * specification, we can also wrap their api this way.181- *182- * app.register('.foo', {183- * render: function(str, options) {184- * // perhaps their api is185- * // return foo.toHTML(str, options);186- * }187- * });188- *179 * @param {String} ext180 * @param {Object} obj181 * @api public182 */5 unmodified lines