Skip to content
Myr

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

16 files+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"10curl:10.12.IP "" 413.11.nf1216$ curl \-# http://expressjs\.com/install\.sh | sh13$ npm install express14.15.fi16.20.IP "" 017.SS "Creating A Server"18To create an instance of the \fIexpress\.HTTPServer\fR, simply invoke the \fIcreateServer()\fR method\. With our instance \fIapp\fR we can then define routes based on the HTTP verbs, in this example \fIapp\.get()\fR\.19.22.P23npm:24.20.IP "" 421.22.nf2329$ npm install express24var app = require(\'express\')\.createServer();2526app\.get(\'/\', function(req, res){27 res\.send(\'hello world\');28});2930app\.listen(3000);31.32.fi33.34.IP "" 035.35.SS "Creating An Application"36The \fIexpress\.Server\fR now inherits from \fIhttp\.Server\fR, however follows the same idiom by providing \fIexpress\.createServer()\fR as shown below\. This means that you can utilize Express server\'s transparently with other libraries\.36.SS "Creating An HTTPS Server"37To initialize a \fIexpress\.HTTPSServer\fR we do the same as above, however we pass an options object, accepting \fIkey\fR, \fIcert\fR and the others mentioned in node\'s https documentation \fIhttp://nodejs\.org/docs/v0\.3\.7/api/https\.html#https\.createServer\fR\.38.39.IP "" 440.41.nf4242var app = require(\'express\')\.createServer();4344app\.get(\'/\', function(req, res){45 res\.send(\'hello world\');46});4748app\.listen(3000);43 var app = require(\'express\')\.createServer({ key: \.\.\. });44.45.fi46.47.IP "" 0
1 unmodified line
49.SS "Configuration"50Express supports arbitrary environments, such as \fIproduction\fR and \fIdevelopment\fR\. Developers can use the \fIconfigure()\fR method to setup needs required by the current environment\. When \fIconfigure()\fR is called without an environment name it will be run in \fIevery\fR environment prior to the environment specific callback\.51.52.P58In the example below we only \fIdumpExceptions\fR, and respond with exception stack traces in \fIdevelopment\fR mode, however for both environments we utilize \fImethodOverride\fR and \fIbodyDecoder\fR\. Note the use of \fIapp\.router\fR, which can (optionally) be used to mount the application routes, otherwise the first call to \fIapp\.{get,put,del,post}()\fR will mount the routes\.53In the example below we only \fIdumpExceptions\fR, and respond with exception stack traces in \fIdevelopment\fR mode, however for both environments we utilize \fImethodOverride\fR and \fIbodyParser\fR\. Note the use of \fIapp\.router\fR, which can (optionally) be used to mount the application routes, otherwise the first call to \fIapp\.get()\fR, \fIapp\.post()\fR, etc will mount the routes\.54.55.IP "" 456.57.nf5859app\.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});6465app\.configure(\'development\', function(){66 app\.use(express\.static(__dirname + \'/public\'));67 app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));68});6970app\.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 lines
83.IP "" 484.85.nf8690app\.configure(function(){87 app\.configure(function(){88 app\.set(\'views\', __dirname + \'/views\');89 app\.set(\'views\');93 // => "\.\.\. views directory \.\.\."90 // => "/absolute/path/to/views"9192 app\.enable(\'some feature\');93 // same as app\.set(\'some feature\', true);9495 app\.disable(\'some feature\');96 // same as app\.set(\'some feature\', false);9798 app\.enabled(\'some feature\')99 // => false100});100 });101.102.fi103.104.IP "" 0
17 unmodified lines
122.SS "Settings"123Express supports the following settings out of the box:124.125.IP "\(bu" 4126\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR127.128.IP "\(bu" 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\fR
3 unmodified lines
133.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"140Express utilizes the HTTP verbs to provide a meaningful, expressive routing API\. For example we may want to render a user\'s account for the path \fI/user/12\fR, this can be done by defining the route below\. The values associated to the named placeholders are available as \fBreq\.params\fR\.
101 unmodified lines
242.243.IP "" 0244.245.P252For 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:246For example we can \fBPOST\fR some json, and echo the json back using the \fIbodyParser\fR middleware which will parse json request bodies (as well as others), and place the result in \fIreq\.body\fR:247.248.IP "" 4249.250.nf251252var express = require(\'express\')253 , app = express\.createServer();254261app\.use(express\.bodyDecoder());255app\.use(express\.bodyParser());256257app\.post(\'/\', function(req, res){258 res\.send(req\.body);259});
4 unmodified lines
264.265.IP "" 0266.267.P274Express 2\.0\.0\-pre also supports named capture groups\. Typically we may use a "dump" placeholder such as "/user/:id" which has no restraints, however say for example we are limiting a user id to digits, we may use \fI\'/user/:id(\ed+)\'\fR which will \fInot\fR match unless the placeholder value contains only digits\.268Typically we may use a "dumb" placeholder such as "/user/:id" which has no restrictions, however say for example we are limiting a user id to digits, we may use \fI\'/user/:id(\ed+)\'\fR which will \fInot\fR match unless the placeholder value contains only digits\.269.270.SS "Passing Route Control"277We may pass control to the next \fImatching\fR route, by calling the \fIthird\fR argument, the \fInext()\fR function\. When a match cannot be made, control is passed back to Connect, and middleware continue to be invoked\. The same is true for several routes which have the same path defined, they will simply be executed in order until one does \fInot\fR call \fInext()\fR\.271We may pass control to the next \fImatching\fR route, by calling the \fIthird\fR argument, the \fInext()\fR function\. When a match cannot be made, control is passed back to Connect, and middleware continue to be invoked in the order that they are added via \fIuse()\fR\. The same is true for several routes which have the same path defined, they will simply be executed in order until one does \fInot\fR call \fInext()\fR and decides to respond\.272.273.IP "" 4274.275.nf
15 unmodified lines
291.292.IP "" 0293.294.P301Express 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:295The \fIapp\.all()\fR method is useful for applying the same logic for all HTTP verbs in a single call\. Below we use this to load a user from our fake database, and assign it to \fIreq\.user\fR\.296.297.IP "" 4298.299.nf
43 unmodified lines
343344 var express = require(\'express\');345346var app = express\.createServer(353 express\.logger(),354 express\.bodyDecoder()347 express\.logger()348 , express\.bodyParser()349 );350.351.fi352.353.IP "" 0354.355.P362Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:356Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks, in a progressive manor\.357.358.IP "" 4359.360.nf
12 unmodified lines
373.nf374375var connect = require(\'connect\');376app\.use(connect\.logger());377app\.use(connect\.bodyParser());378.379.fi380.381.IP "" 0
5 unmodified lines
387.388.nf389390app\.use(express\.logger());391app\.use(express\.bodyParser());392.393.fi394.395.IP "" 0
8 unmodified lines
404.405.nf406407app\.get(\'/user/:id\', function(req, res, next){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 lines
422.423.nf424425function 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}435436app\.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 lines
448.449.nf450451function 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}456457app\.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 lines
469.470.nf471472function 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}479480app\.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 lines
530.531.IP "" 0532.533.P538By default Express does not know what to do with this request body, so we should add the \fIbodyDecoder\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:534By default Express does not know what to do with this request body, so we should add the \fIbodyParser\fR middleware, which will parse \fIapplication/x\-www\-form\-urlencoded\fR and \fIapplication/json\fR request bodies and place the variables in \fIreq\.body\fR\. We can do this by "using" the middleware as shown below:535.536.IP "" 4537.538.nf539544app\.use(express\.bodyDecoder());540app\.use(express\.bodyParser());541.542.fi543.544.IP "" 0
5 unmodified lines
550.551.nf552553app\.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.P567When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyDecoder\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.563When using methods such as \fIPUT\fR with a form, we can utilize a hidden input named \fI_method\fR, which can be used to alter the HTTP method\. To do so we first need the \fImethodOverride\fR middleware, which should be placed below \fIbodyParser\fR so that it can utilize it\'s \fIreq\.body\fR containing the form values\.564.565.IP "" 4566.567.nf568573app\.use(express\.bodyDecoder());569app\.use(express\.bodyParser());570app\.use(express\.methodOverride());571.572.fi573.
29 unmodified lines
603.604.nf605606function 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}611616sys\.inherits(NotFound, Error);612NotFound\.protoype\.__proto__ = Error\.prototype;613614app\.get(\'/404\', function(req, res){619 throw new NotFound;615 throw new NotFound;616});617618app\.get(\'/500\', function(req, res){623 throw new Error(\'keyboard cat!\');619 throw new Error(\'keyboard cat!\');620});621.622.fi623.
21 unmodified lines
645.646.IP "" 0647.648.P653Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like649Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like\. For example when node performs filesystem syscalls, you may receive an error object with the \fIerror\.code\fR of \fIENOENT\fR, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired\.650.651.IP "" 4652.653.nf654655app\.error(function(err, req, res){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 lines
690.691.P692The \fIerrorHandler\fR middleware also responds with \fIjson\fR if \fIAccept: application/json\fR is present, which is useful for developing apps that rely heavily on client\-side JavaScript\.693.700.SS "Route Preconditions"701Route placeholder pre\-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls\. For example if you are constantly fetching common data for several routes, such as loading a user for \fI/user/:id\fR,we might typically do something like below:694.SS "Route Param Pre\-conditions"695Route param pre\-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls\. For example if you are constantly fetching common data for several routes, such as loading a user for \fI/user/:id\fR, we might typically do something like below:696.697.IP "" 4698.699.nf
9 unmodified lines
709.710.IP "" 0711.712.P719With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database\. Below we invoke \fIapp\.param()\fR with the parameter name we wish to map to some middleware, as you can see we receive the \fIid\fR argument which contains the placeholder value\. Using this we load the user and perform error handling as usual, and simple call \fInext()\fR to pass control to the next precondition or route handler\.713With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database\. Below we invoke \fIapp\.param()\fR with the parameter name we wish to map to some middleware, as you can see we receive the \fIid\fR argument which contains the placeholder value\. Using this we load the user and perform error handling as usual, and simple call \fInext()\fR to pass control to the next precondition or route handler\.714.715.IP "" 4716.717.nf
52 unmodified lines
770.771.IP "" 0772.773.SS "View Rendering"780View filenames take the form \fINAME\fR\.\fIENGINE\fR, where \fIENGINE\fR is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.render(str, options)\fR to comply with Express, however \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by jade\.774View filenames take the form "<name>\.<engine>", where <engine> is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.compile(str, options)\fR, and return a \fIFunction\fR to comply with Express\. To alter this behaviour \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by ejs\.775.776.P783Below is an example using Haml\.js \fIhttp://github\.com/visionmedia/haml\.js\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.html\fR will be passed as the \fIbody\fR local variable in \fIlayout\.haml\fR\.777Below is an example using Jade \fIhttp://github\.com/visionmedia/jade\fR to render \fIindex\.html\fR, and since we do not use \fIlayout: false\fR the rendered contents of \fIindex\.jade\fR will be passed as the \fIbody\fR local variable in \fIlayout\.jade\fR\.778.779.IP "" 4780.781.nf782783app\.get(\'/\', function(req, res){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.P800The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using Jade \fIhttp://github\.com/visionmedia/jade\fR we could set:792The new \fIview engine\fR setting allows us to specify our default template engine, so for example when using jade we could set:793.794.IP "" 4795.796.nf
50 unmodified lines
847.848.nf849850app\.set(\'view options\', {859 layout: false851 layout: false852});853.854.fi855.856.IP "" 0857.858.P867Which can then be overridden within the \fBres\.render()\fR call if need be:859Which can then be overridden within the \fIres\.render()\fR call if need be:860.861.IP "" 4862.863.nf
59 unmodified lines
923.924.IP "" 0925.926.SS "View Partials"935The Express view system has built\-in support for partials and collections, which are sort of "mini" views representing a document fragment\. For example rather than iterating in a view to display comments, we would use a partial with collection support:927The Express view system has built\-in support for partials and collections, which are "mini" views representing a document fragment\. For example rather than iterating in a view to display comments, we would use a partial with collection support:928.929.IP "" 4930.931.nf932941partial(\'comment\.haml\', { collection: comments });942.943.fi944.945.IP "" 0946.947.P948To make things even less verbose we can assume the extension as \fI\.haml\fR when omitted, however if we wished we could use an ejs partial, within a haml view for example\.949.950.IP "" 4951.952.nf953933partial(\'comment\', { collection: comments });934.935.fi936.937.IP "" 0938.939.P961And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:940If 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.nf
7 unmodified lines
952.P953When 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.P970For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.971.972.P994NOTE: 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\.973NOTE: 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"976Below are a few template engines commonly used with Express:977.978.IP "\(bu" 4979Jade \fIhttp://jade\-lang\.com\fR haml\.js successor980.981.IP "\(bu" 41003Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates1004.1005.IP "\(bu" 4982EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript983.984.IP "\(bu" 4985CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating
3 unmodified lines
989.990.IP "" 0991.992.SS "Session Support"1017Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieDecoder\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.993Sessions 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.nf9981023app\.use(express\.cookieDecoder());1024app\.use(express\.session());999app\.use(express\.cookieParser());1000app\.use(express\.session({ secret: "keyboard cat" }));1001.1002.fi1003.1004.IP "" 0
5 unmodified lines
1010.1011.nf10121013var RedisStore = require(\'connect\-redis\');1038app\.use(express\.cookieDecoder());1039app\.use(express\.session({ store: new RedisStore }));1014app\.use(express\.cookieParser());1015app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));1016.1017.fi1018.1019.IP "" 0
5 unmodified lines
1025.1026.nf10271028var RedisStore = require(\'connect\-redis\');1053app\.use(express\.bodyDecoder());1054app\.use(express\.cookieDecoder());1055app\.use(express\.session({ store: new RedisStore }));1029app\.use(express\.bodyParser());1030app\.use(express\.cookieParser());1031app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));10321033app\.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 lines
1052.1053.IP "" 01054.1055.P1080The \fIreq\.session\fR object also has methods such as \fISession#touch()\fR, \fISession#destroy()\fR, \fISession#regenerate()\fR among others to maintain and manipulate sessions\. For more information view the Connect Session \fIhttp://senchalabs\.github\.com/connect/session\.html\fR documentation\.1056The \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"1083Pre\-beta Express developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.1059Express 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])"1062Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1063.
8 unmodified lines
1072.fi1073.1074.IP "" 01075.1076.P1077The \fIReferrer\fR and \fIReferer\fR header fields are special\-cased, either will work:1078.1079.IP "" 41080.1081.nf10821083// sent Referrer: http://google\.com10841085req\.header(\'Referer\');1086// => "http://google\.com"10871088req\.header(\'Referrer\');1089// => "http://google\.com"1090.1091.fi1092.1093.IP "" 01094.1095.SS "req\.accepts(type)"1096Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1097.1098.P
108 unmodified lines
1207.fi1208.1209.IP "" 01210.1216.SS "req\.param(name)"1217Return the value of param \fIname\fR when present\.1211.SS "req\.param(name[, default])"1212Return the value of param \fIname\fR when present or \fIdefault\fR\.1213.1214.IP "\(bu" 41220Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1215Checks route params (\fIreq\.params\fR), ex: /user/:id1216.1217.IP "\(bu" 41218Checks query string params (\fIreq\.query\fR), ex: ?id=121219.
2 unmodified lines
1222.1223.IP "" 01224.1225.P1231To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.1226To 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])"1229Queue flash \fImsg\fR of the given \fItype\fR\.1230.
74 unmodified lines
1305.nf13061307 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 "" 0
10 unmodified lines
1324.fi1325.1326.IP "" 01327.1333.SS "res\.sendfile(path)"1328.SS "res\.sendfile(path[, options[, callback]])"1329Used by \fBres\.download()\fR to transfer an arbitrary file\.1330.1331.IP "" 41332.
5 unmodified lines
1338.1339.IP "" 01340.1341.P1347This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed\. When a callback is not given, and the file has \fBnot\fR been streamed, \fInext(err)\fR will be called on an exception\.1342This 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.nf13471353res\.sendfile(path, function(err, path){1348res\.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 lines
1357.1358.IP "" 01359.1360.P1366When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.1361Options may also be passed to the internal \fIfs\.createReadStream()\fR call, for example altering the \fIbufferSize\fR:1362.1363.IP "" 41364.1365.nf13661367res\.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]])"1376Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1377.1378.IP "" 41379.
19 unmodified lines
1399.fi1400.1401.IP "" 01402.1403.P1404An optional callback may be supplied as either the second or third argument, which is passed to \fIres\.sendfile()\fR:1405.1406.IP "" 41407.1408.nf14091410res\.download(path, \'expenses\.doc\', function(err){1411 // handle1412});1413.1414.fi1415.1416.IP "" 01417.1418.SS "res\.send(body|status[, headers|status[, status]])"1397The \fBres\.send()\fR method is a high level response utility allowing you to pass objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status code based responses\. The following are all valid uses:1419The \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.nf
13 unmodified lines
1437.P1438By 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.P1419Note that this method \fIend()\fR the response, so you will want to use node\'s \fIres\.writeHead()\fR / \fIres\.write()\fR for multiple writes or streaming\.1441Note 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])"1444Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1445.
14 unmodified lines
1460.P1461Express 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])"1442Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1464Sets the given cookie \fIname\fR to \fIval\fR, with options \fIhttpOnly\fR, \fIsecure\fR, \fIexpires\fR etc\.1465.1466.IP "" 41467.1468.nf
11 unmodified lines
1480.IP "" 41481.1482.nf14831462app\.use(express\.cookieDecoder());1484app\.use(express\.cookieParser());14851486app\.get(\'/\', function(req, res){1465 // use req\.cookies\.rememberme1487 // use req\.cookies\.rememberme1488});1489.1490.fi1491.
15 unmodified lines
1507.SS "res\.render(view[, options[, fn]])"1508Render \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.P1489Most engines accept one or more of the following options, both haml \fIhttp://github\.com/visionmedia/haml\.js\fR and jade \fIhttp://github\.com/visionmedia/jade\fR accept all:1511The \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.nf15161517var user = { name: \'tj\' };1518res\.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])"1525Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.
117 unmodified lines
1643.fi1644.1645.IP "" 01646.1647.P1648This 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.nf16531654app\.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])"1672Get 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 "" 4
63 unmodified lines
1738.fi1739.1740.IP "" 01741.1742.SS "app\.enabled(name)"1743Check if setting \fIname\fR is enabled:1744.1745.IP "" 41746.1747.nf17481749app\.enabled(\'view cache\');1750// => false17511752app\.enable(\'view cache\');1753app\.enabled(\'view cache\');1754// => true1755.1756.fi1757.1758.IP "" 01759.1760.SS "app\.disable(name)"1761Disable the given setting \fIname\fR:1762.1763.IP "" 4
10 unmodified lines
1774.fi1775.1776.IP "" 01777.1778.SS "app\.disabled(name)"1779Check if setting \fIname\fR is disabled:1780.1781.IP "" 41782.1783.nf17841785app\.enable(\'view cache\');17861787app\.disabled(\'view cache\');1788// => false17891790app\.disable(\'view cache\');1791app\.disabled(\'view cache\');1792// => true1793.1794.fi1795.1796.IP "" 01797.1798.SS "app\.configure(env|function[, function])"1799Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1800.1801.IP "" 4
12 unmodified lines
1814.1815.IP "" 01816.1817.SS "app\.redirect(name, val)"1740For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1818For use with \fIres\.redirect()\fR we can map redirects at the application level as shown below:1819.1820.IP "" 41821.1822.nf
17 unmodified lines
1840.1841.nf18421843app\.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 lines
1855.1856.nf18571858app\.get(\'/post/:id\', function(req, res){1781 res\.redirect(\'comments\');1859 res\.redirect(\'comments\');1860});1861.1862.fi1863.1864.IP "" 01865.1866.P1867When 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.nf18721873res\.redirect(\'/posts\');1874.1875.fi1876.1877.IP "" 01878.1879.SS "app\.error(function)"1880Adds 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.nf18851886app\.error(function(err, req, res, next){1796 res\.send(err\.message, 500);1887 res\.send(err\.message, 500);1888});1889.1890.fi1891.
1 unmodified line
1893.1894.SS "app\.helpers(obj)"1895Registers static view helpers\.1896.1897.P1898app\.helpers({1899.1900.IP "" 41901.1902.nf19031810app\.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.P1916Our 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 lines
1932.1933.nf19341935app\.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 lines
1965var app = express\.createServer(),1966 blog = express\.createServer();19671968blog\.mounted(function(parent){1874 // parent is app1875 // "this" is blog1969 // parent is app1970 // "this" is blog1971});19721973app\.use(blog);1974.
27 unmodified lines
2002.2003.IP "" 02004.2005.P1911For engines that do not comply with the Express specification, we can also wrap their api this way\.2006For 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.nf20111917 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 "" 0
49 unmodified lines
modified:docs/guide.html+234 added-167 removed
178 unmodified lines
179 </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 line
199<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 lines
220</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 lines
251 <code>guide</code>252</p>253<h3 id="Installation">Installation</h3>254252<p>curl:</p>253254<pre><code>$ curl -# http://expressjs.com/install.sh | sh255</code></pre>256257<p>npm:</p>258255<pre><code>$ npm install express256</code></pre>257262<h3 id="Creating-An-Application">Creating An Application</h3>258<h3 id="Creating-A-Server">Creating A Server</h3>259264<p>The <em>express.Server</em> now inherits from <em>http.Server</em>, however265follows the same idiom by providing <em>express.createServer()</em> as shown below. This means266that 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>261262<pre><code>var app = require('express').createServer();263264app.get('/', function(req, res){271 res.send('hello world');265 res.send('hello world');266});267268app.listen(3000);269</code></pre>270271<h3 id="Creating-An-HTTPS-Server">Creating An HTTPS Server</h3>272273<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>275276<pre><code> var app = require('express').createServer({ key: ... });277</code></pre>278279<h3 id="Configuration">Configuration</h3>280281<p>Express supports arbitrary environments, such as <em>production</em> and <em>development</em>. Developers282can 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> environment284prior to the environment specific callback.</p>285286<p>In the example below we only <em>dumpExceptions</em>, and respond with exception stack traces285in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyDecoder</em>.287in <em>development</em> mode, however for both environments we utilize <em>methodOverride</em> and <em>bodyParser</em>.288Note the use of <em>app.router</em>, which can (optionally) be used to mount the application routes,287otherwise the first call to <em>app.{get,put,del,post}()</em> will mount the routes.</p>289otherwise the first call to <em>app.get()</em>, <em>app.post()</em>, etc will mount the routes.</p>290291<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});296297app.configure('development', function(){298 app.use(express.static(__dirname + '/public'));299 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));300});301302app.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>308309<p>For internal and arbitrary settings Express provides the <em>set(key[, val])</em>, <em>enable(key)</em>, <em>disable(key)</em> methods:</p>310307<pre><code>app.configure(function(){311<pre><code> app.configure(function(){312 app.set('views', __dirname + '/views');313 app.set('views');310 // =&gt; "... views directory ..."314 // =&gt; "/absolute/path/to/views"315316 app.enable('some feature');317 // same as app.set('some feature', true);318319 app.disable('some feature');320 // same as app.set('some feature', false);321322 app.enabled('some feature')323 // =&gt; false317});324 });325</code></pre>326327<p>To alter the environment we can set the <em>NODE_ENV</em> environment variable, for example:</p>328
6 unmodified lines
335336<p>Express supports the following settings out of the box:</p>337338<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>344345346<h3 id="Routing">Routing</h3>
69 unmodified lines
416 /user/12417 /user/12.json418</code></pre>419415<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>421422<pre><code>var express = require('express')423 , app = express.createServer();424420app.use(express.bodyDecoder());425app.use(express.bodyParser());426427app.post('/', function(req, res){428 res.send(req.body);429});430431app.listen(3000);432</code></pre>433429<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>435436<h3 id="Passing-Route-Control">Passing Route Control</h3>437438<p>We may pass control to the next <em>matching</em> route, by calling the <em>third</em> argument,439the <em>next()</em> function. When a match cannot be made, control is passed back to Connect,435and 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>440and 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>441442<pre><code>app.get('/users/:id?', function(req, res, next){443 var id = req.params.id;444 if (id) {
7 unmodified lines
452 // do something else453});454</code></pre>455451<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>457458<pre><code>var express = require('express')459 , app = express.createServer();460
34 unmodified lines
495496<pre><code> var express = require('express');497498var app = express.createServer(494 express.logger(),495 express.bodyDecoder()499 express.logger()500 , express.bodyParser()501 );502</code></pre>503499<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>505506<pre><code>app.use(express.logger({ format: ':method :uri' }));507</code></pre>508509<p>Typically with connect middleware you would <em>require('connect')</em> like so:</p>510511<pre><code>var connect = require('connect');512app.use(connect.logger());513app.use(connect.bodyParser());514</code></pre>515516<p>This is somewhat annoying, so express re-exports these middleware properties, however they are <em>identical</em>:</p>517518<pre><code>app.use(express.logger());519app.use(express.bodyParser());520</code></pre>521522<h3 id="Route-Middleware">Route Middleware</h3>523
1 unmodified line
525526<p>Typically async data retrieval might look similar to below, where we take the <em>:id</em> parameter, and attempt loading a user.</p>527528<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>535536<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>537538<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}548549app.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>553554<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>555556<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}561562app.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>566567<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>568569<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}576577app.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>581582<p>Commonly used "stacks" of middleware can be passed as an array (<em>applied recursively</em>), which can be mixed and matched to any degree.</p>
24 unmodified lines
607 &lt;input type="submit" value="Submit" /&gt;608 &lt;/form&gt;609</code></pre>610604<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>612606<pre><code>app.use(express.bodyDecoder());613<pre><code>app.use(express.bodyParser());614</code></pre>615616<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>617618<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>623617<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>625619<pre><code>app.use(express.bodyDecoder());626<pre><code>app.use(express.bodyParser());627app.use(express.methodOverride());628</code></pre>629630<p>The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as <em>PUT</em> and <em>DELETE</em> can still be accessed by clients which can use them directly, although <em>methodOverride</em> provides a great solution for forms. Below shows what the usage of <em>PUT</em> might look like:</p>
17 unmodified lines
648or passed to <em>next(err)</em>. Below is an example which serves different pages based on our649ad-hoc <em>NotFound</em> exception:</p>650651<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}656650sys.inherits(NotFound, Error);657NotFound.protoype.__proto__ = Error.prototype;658659app.get('/404', function(req, res){653 throw new NotFound;660 throw new NotFound;661});662663app.get('/500', function(req, res){657 throw new Error('keyboard cat!');664 throw new Error('keyboard cat!');665});666</code></pre>667668<p>We can call <em>app.error()</em> several times as shown below.
14 unmodified lines
683});684</code></pre>685686<p>Here we assume all errors as 500 for the simplicity of680this demo, however you can choose whatever you like</p>687this 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>688689<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>695696<p>Our apps could also utilize the Connect <em>errorHandler</em> middleware
11 unmodified lines
708709<p>The <em>errorHandler</em> middleware also responds with <em>json</em> if <em>Accept: application/json</em>710is present, which is useful for developing apps that rely heavily on client-side JavaScript.</p>711707<h3 id="Route-Preconditions">Route Preconditions</h3>712<h3 id="Route-Param-Pre-conditions">Route Param Pre-conditions</h3>713709<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>715716<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 line
720 });721}); 722</code></pre>723719<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>725726<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 lines
751</code></pre>752753<h3 id="View-Rendering">View Rendering</h3>754750<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 "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name756of the module that will be required. For example the view <em>layout.ejs</em> will752tell 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>757tell 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>759755<p>Below is an example using <a href="http://github.com/visionmedia/haml.js">Haml.js</a> to render <em>index.html</em>,756and since we do not use <em>layout: false</em> the rendered contents of <em>index.html</em> will be passed as757the <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>,761and since we do not use <em>layout: false</em> the rendered contents of <em>index.jade</em> will be passed as762the <em>body</em> local variable in <em>layout.jade</em>.</p>763764<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>768769<p>The new <em>view engine</em> setting allows us to specify our default template engine,767so for example when using <a href="http://github.com/visionmedia/jade">Jade</a> we could set:</p>770so for example when using jade we could set:</p>771772<pre><code>app.set('view engine', 'jade');773</code></pre>774
15 unmodified lines
790791<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>792793<pre><code>app.set('view options', {791 layout: false794 layout: false795});796</code></pre>797795<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>799800<pre><code>res.render('myview.ejs', { layout: true });801</code></pre>802
21 unmodified lines
824</code></pre>825826<h3 id="View-Partials">View Partials</h3>827825<p>The Express view system has built-in support for partials and collections, which are826sort 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 iterating829in a view to display comments, we would use a partial with collection support:</p>830829<pre><code>partial('comment.haml', { collection: comments });830</code></pre>831832<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,833however if we wished we could use an ejs partial, within a haml view for example.</p>834831<pre><code>partial('comment', { collection: comments });832</code></pre>833838<p>And once again even further, when rendering a collection we can simply pass839an 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>835836<pre><code>partial('comment', comments);837</code></pre>838839<p>When using the partial collection support a few "magic" variables are provided840for free:</p>841842<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>848849850<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>851857<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>853854<h3 id="Template-Engines">Template Engines</h3>855856<p>Below are a few template engines commonly used with Express:</p>857858<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>864865866<h3 id="Session-Support">Session Support</h3>867874<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>869876<pre><code>app.use(express.cookieDecoder());877app.use(express.session());870<pre><code>app.use(express.cookieParser());871app.use(express.session({ secret: "keyboard cat" }));872</code></pre>873874<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>875876<pre><code>var RedisStore = require('connect-redis');883app.use(express.cookieDecoder());884app.use(express.session({ store: new RedisStore }));877app.use(express.cookieParser());878app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));879</code></pre>880881<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>882883<pre><code>var RedisStore = require('connect-redis');890app.use(express.bodyDecoder());891app.use(express.cookieDecoder());892app.use(express.session({ store: new RedisStore }));884app.use(express.bodyParser());885app.use(express.cookieParser());886app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));887888app.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 lines
903 res.render('shopping-cart');904});905</code></pre>906913<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>908909<h3 id="Migration-Guide">Migration Guide</h3>910917<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>912913<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>914915<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>
2 unmodified lines
918req.header('host');919req.header('Accept', '*/*');920</code></pre>921922<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>923924<pre><code>// sent Referrer: http://google.com925926req.header('Referer');927// =&gt; "http://google.com"928929req.header('Referrer');930// =&gt; "http://google.com"931</code></pre>932933<h3 id="req-accepts-type-">req.accepts(type)</h3>934935<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>936
71 unmodified lines
10081009<pre><code>req.is('*/json');1010</code></pre>10111007<h3 id="req-param-name-">req.param(name)</h3>1012<h3 id="req-param-name-default-">req.param(name[, default])</h3>10131009<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>10151016<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>102110221023<p>To utilize urlencoded request bodies, <em>req.body</em>1024should be an object. This can be done by using1020the <em>express.bodyDecoder</em> middleware.</p>1025the _express.bodyParser middleware.</p>10261027<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>10281029<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>
46 unmodified lines
1076<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>10771078<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>10821083<h3 id="res-attachment-filename-">res.attachment([filename])</h3>1084
1 unmodified line
10861087<pre><code> res.attachment('path/to/my/image.png');1088</code></pre>10891085<h3 id="res-sendfile-path-">res.sendfile(path)</h3>1090<h3 id="res-sendfile-path-options-callback-">res.sendfile(path[, options[, callback]])</h3>10911092<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>10931094<pre><code>res.sendfile('path/to/my.file');1095</code></pre>10961092<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 when1098an 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>10991094<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>11081103<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>11101105<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>11151116<h3 id="res-download-file-filename-callback-">res.download(file[, filename[, callback]])</h3>11171118<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>11191120<pre><code>res.download('path/to/image.png');1121res.download('path/to/image.png', 'foo.png');
4 unmodified lines
1126<pre><code>res.attachment(file);1127res.sendfile(file);1128</code></pre>11291130<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>:</p>11311132<pre><code>res.download(path, 'expenses.doc', function(err){1133 // handle1134});1135</code></pre>11361137<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>11381121<p>The <code>res.send()</code> method is a high level response utility allowing you to pass1122objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status1123code 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 pass1140objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>11411142<pre><code> res.send(); // 2041143 res.send(new Buffer('wahoo'));1144 res.send({ some: 'json' });
6 unmodified lines
1151<p>By default the <em>Content-Type</em> response header is set, however if explicitly1152assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1153it will not be set again.</p>11541138<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>11561157<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>11581159<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>
10 unmodified lines
1170the "home" setting and defaults to "/".</p>11711172<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>11731157<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>11751176<pre><code>// "Remember me" for 15 minutes 1177res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1178</code></pre>11791180<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>11811165<pre><code>app.use(express.cookieDecoder());1182<pre><code>app.use(express.cookieParser());11831184app.get('/', function(req, res){1168 // use req.cookies.rememberme1185 // use req.cookies.rememberme1186});1187</code></pre>11881189<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>
8 unmodified lines
1198<p>Render <em>view</em> with the given <em>options</em> and optional callback <em>fn</em>.1199When a callback function is given a response will <em>not</em> be made1200automatically, however otherwise a response of <em>200</em> and <em>text/html</em> is given.</p>12011185<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>12031188<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' };1205res.render('index', { layout: false, user: user });1206</code></pre>120711961208<h3 id="res-partial-view-options-">res.partial(view[, options])</h3>12091210<p>Render <em>view</em> partial with the given <em>options</em>. This method is always available1211to the view as a local variable.</p>
64 unmodified lines
1276<pre><code>partial('movie', movie);1277// =&gt; In view: movie.director1278</code></pre>12791280<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>12811282<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>12951296<h3 id="res-local-name-val-">res.local(name[, val])</h3>12971298<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 lines
1338app.enabled('some arbitrary setting');1339// =&gt; true1340</code></pre>13411342<h3 id="app-enabled-name-">app.enabled(name)</h3>13431344<p>Check if setting <em>name</em> is enabled:</p>13451346<pre><code>app.enabled('view cache');1347// =&gt; false13481349app.enable('view cache');1350app.enabled('view cache');1351// =&gt; true1352</code></pre>13531354<h3 id="app-disable-name-">app.disable(name)</h3>13551356<p>Disable the given setting <em>name</em>:</p>1357
4 unmodified lines
1362app.disabled('some setting');1363// =&gt; false1364</code></pre>13651366<h3 id="app-disabled-name-">app.disabled(name)</h3>13671368<p>Check if setting <em>name</em> is disabled:</p>13691370<pre><code>app.enable('view cache');13711372app.disabled('view cache');1373// =&gt; false13741375app.disable('view cache');1376app.disabled('view cache');1377// =&gt; true1378</code></pre>13791380<h3 id="app-configure-env-function-function-">app.configure(env|function[, function])</h3>13811382<p>Define a callback function for the given <em>env</em> (or all environments) with callback <em>function</em>:</p>1383
7 unmodified lines
1391</code></pre>13921393<h3 id="app-redirect-name-val-">app.redirect(name, val)</h3>13941342<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>13961397<pre><code>app.redirect('google', 'http://google.com');1398</code></pre>1399
3 unmodified lines
14031404<p>We may also map dynamic redirects:</p>14051406<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>14101411<p>So now we may do the following, and the redirect will dynamically adjust to1412the context of the request. If we called this route with <em>GET /post/12</em> our1413redirect <em>Location</em> would be <em>/post/12/comments</em>.</p>14141415<pre><code>app.get('/post/:id', function(req, res){1363 res.redirect('comments');1416 res.redirect('comments');1417});1418</code></pre>14191420<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>14211422<pre><code>res.redirect('/posts');1423</code></pre>14241425<h3 id="app-error-function-">app.error(function)</h3>14261427<p>Adds an error handler <em>function</em> which will receive the exception as the first parameter as shown below.1428Note that we may set several error handlers by making several calls to this method, however the handler1429should call <em>next(err)</em> if it does not wish to deal with the exception:</p>14301431<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>14351436<h3 id="app-helpers-obj-">app.helpers(obj)</h3>14371438<p>Registers static view helpers.</p>14391382<pre><code>app.helpers({1383 name: function(first, last){ return first + ', ' + last },1384 firstName: 'tj',1385 lastName: 'holowaychuk'1386});1440<p> app.helpers({</p>14411442<pre><code> name: function(first, last){ return first + ', ' + last }1443, firstName: 'tj'1444, lastName: 'holowaychuk'1445</code></pre>14461447<p> });</p>14481449<p>Our view could now utilize the <em>firstName</em> and <em>lastName</em> variables,1450as well as the <em>name()</em> function exposed.</p>14511452<pre><code>&lt;%= name(firstName, lastName) %>
6 unmodified lines
1459evaluated against the <em>Server</em> instance before a view is rendered. The <em>return value</em> of this function1460becomes the local variable it is associated with.</p>14611462<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>14681469<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 lines
1478<pre><code>var app = express.createServer(),1479 blog = express.createServer();14801481blog.mounted(function(parent){1422 // parent is app1423 // "this" is blog1482 // parent is app1483 // "this" is blog1484});14851486app.use(blog);1487</code></pre>
15 unmodified lines
1503<pre><code> app.register('.haml', require('haml-js'));1504</code></pre>15051506<p>For engines that do not comply with the Express1447specification, we can also wrap their api this way.</p>1507specification, we can also wrap their api this way. Below1508we map <em>.md</em> to render markdown files, rendering the html once1509since it will not change on subsequent calls, and support local substitution1510in the form of "{name}".</p>15111449<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>15231524<h3 id="app-listen-port-host-">app.listen([port[, host]])</h3>1525
30 unmodified lines
modified:docs/guide.md+243 added-184 removed
12### Installation34curl:56 $ curl -# http://expressjs.com/install.sh | sh78npm:94 $ npm install express512### Creating An Application6### Creating A Server714The _express.Server_ now inherits from _http.Server_, however15follows the same idiom by providing _express.createServer()_ as shown below. This means16that 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()_.910 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);1718### Creating An HTTPS Server1920 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: ... });2425### Configuration2627Express supports arbitrary environments, such as _production_ and _development_. Developers28can 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 30prior to the environment specific callback.3132In the example below we only _dumpExceptions_, and respond with exception stack traces34in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyDecoder_.33in _development_ mode, however for both environments we utilize _methodOverride_ and _bodyParser_.34Note the use of _app.router_, which can (optionally) be used to mount the application routes,36otherwise the first call to _app.{get,put,del,post}()_ will mount the routes.35otherwise the first call to _app.get()_, _app.post()_, etc will mount the routes.3637 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 });5354For internal and arbitrary settings Express provides the _set(key[, val])_, _enable(key)_, _disable(key)_ methods:5557 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 });7071To alter the environment we can set the _NODE_ENV_ environment variable, for example:7273 $ NODE_ENV=production node app.js
3 unmodified lines
77### Settings7879Express supports the following settings out of the box:8079 * _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 options
66 unmodified lines
151 "/user/:id.:format?"152 /user/12153 /user/12.json154154For 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_:155For 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_:156157 var express = require('express')158 , app = express.createServer();159159 app.use(express.bodyDecoder());160 app.use(express.bodyParser());161162 app.post('/', function(req, res){163 res.send(req.body);164 });165166 app.listen(3000);167167Express 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.168Typically 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.169170### Passing Route Control171172We may pass control to the next _matching_ route, by calling the _third_ argument,173the _next()_ function. When a match cannot be made, control is passed back to Connect,173and 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()_.174and 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.175176 app.get('/users/:id?', function(req, res, next){177 var id = req.params.id;178 if (id) {
6 unmodified lines
185 app.get('/users', function(req, res){186 // do something else187 });188188Express 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:189The _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_.190191 var express = require('express')192 , app = express.createServer();193
33 unmodified lines
227228 var express = require('express');229230 var app = express.createServer(230 express.logger(),231 express.bodyDecoder()231 express.logger()232 , express.bodyParser()233 );234234Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks:235Alternatively we can _use()_ them which is useful when adding middleware within _configure()_ blocks, in a progressive manor.236237 app.use(express.logger({ format: ':method :uri' }));238239Typically with connect middleware you would _require('connect')_ like so:240241 var connect = require('connect');242 app.use(connect.logger());243 app.use(connect.bodyParser());244245This is somewhat annoying, so express re-exports these middleware properties, however they are _identical_:246247 app.use(express.logger());248 app.use(express.bodyParser());249250### Route Middleware251252Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.253254Typically async data retrieval might look similar to below, where we take the _:id_ parameter, and attempt loading a user. 255256 app.get('/user/:id', function(req, res, next){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 });262263To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time. 264265 function loadUser(req, res, next) {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 });279280Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.281282 function andRestrictToSelf(req, res, next) {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 });291292Keeping in mind that middleware are simply functions, we can define function that _returns_ the middleware in order to create a more expressive and flexible solution as shown below.293294 function andRestrictTo(role) {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 });305306Commonly used "stacks" of middleware can be passed as an array (_applied recursively_), which can be mixed and matched to any degree.307
21 unmodified lines
329 <input type="text" name="user[email]" />330 <input type="submit" value="Submit" />331 </form>332330By default Express does not know what to do with this request body, so we should add the _bodyDecoder_ middleware, which will parse _application/x-www-form-urlencoded_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:333By default Express does not know what to do with this request body, so we should add the _bodyParser_ middleware, which will parse _application/x-www-form-urlencoded_ and _application/json_ request bodies and place the variables in _req.body_. We can do this by "using" the middleware as shown below:334332 app.use(express.bodyDecoder());335 app.use(express.bodyParser());336337Our route below will now have access to the _req.body.user_ object which will contain the _name_ and _email_ properties when defined.338339 app.post('/', function(req, res){337 console.log(req.body.user);338 res.redirect('back');340 console.log(req.body.user);341 res.redirect('back');342 });343341When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyDecoder_ so that it can utilize it's _req.body_ containing the form values.344When using methods such as _PUT_ with a form, we can utilize a hidden input named _\_method_, which can be used to alter the HTTP method. To do so we first need the _methodOverride_ middleware, which should be placed below _bodyParser_ so that it can utilize it's _req.body_ containing the form values.345343 app.use(express.bodyDecoder());346 app.use(express.bodyParser());347 app.use(express.methodOverride());348349The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as _PUT_ and _DELETE_ can still be accessed by clients which can use them directly, although _methodOverride_ provides a great solution for forms. Below shows what the usage of _PUT_ might look like:350
14 unmodified lines
365Express provides the _app.error()_ method which receives exceptions thrown within a route,366or passed to _next(err)_. Below is an example which serves different pages based on our367ad-hoc _NotFound_ exception:368366 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 });384372 sys.inherits(NotFound, Error);373374 app.get('/404', function(req, res){375 throw new NotFound;376 });377378 app.get('/500', function(req, res){379 throw new Error('keyboard cat!');380 });381385We can call _app.error()_ several times as shown below.386Here we check for an instanceof _NotFound_ and show the387404 page, or we pass on to the next error handler.388
10 unmodified lines
399 }400 });401402Here we assume all errors as 500 for the simplicity of400this demo, however you can choose whatever you like403this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the _error.code_ of _ENOENT_, meaning "no such file or directory", we can utilize this in our error handling and display a page specific to this if desired.404402 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 });410411Our apps could also utilize the Connect _errorHandler_ middleware412to report on exceptions. For example if we wish to output exceptions 413in "development" mode to _stderr_ we can use:
7 unmodified lines
421422The _errorHandler_ middleware also responds with _json_ if _Accept: application/json_423is present, which is useful for developing apps that rely heavily on client-side JavaScript.424424### Route Preconditions425### Route Param Pre-conditions426426Route placeholder pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_,we might typically do something like below:427Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for _/user/:id_, we might typically do something like below:428429 app.get('/user/:userId', function(req, res, next){430 User.get(req.params.userId, function(err, user){431 if (err) return next(err);432 res.send('user ' + user.name);433 });434 }); 435435With route preconditions our placeholders can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.436With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke _app.param()_ with the parameter name we wish to map to some middleware, as you can see we receive the _id_ argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call _next()_ to pass control to the next precondition or route handler.437438 app.param('userId', function(req, res, next, id){439 User.get(id, function(err, user){440 if (err) return next(err);
18 unmodified lines
459 app.param(['from', 'to'], function(n){ return parseInt(n, 10); });460461### View Rendering462462View filenames take the form _NAME_._ENGINE_, where _ENGINE_ is the name463View filenames take the form "&lt;name&gt;.&lt;engine&gt;", where &lt;engine&gt; is the name464of the module that will be required. For example the view _layout.ejs_ will464tell 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.465tell the view system to _require('ejs')_, the module being loaded must export the method _exports.compile(str, options)_, and return a _Function_ to comply with Express. To alter this behaviour466_app.register()_ can be used to map engines to file extensions, so that for example "foo.html" can be rendered by ejs.467467Below is an example using [Haml.js](http://github.com/visionmedia/haml.js) to render _index.html_,468and since we do not use _layout: false_ the rendered contents of _index.html_ will be passed as 469the _body_ local variable in _layout.haml_.468Below is an example using [Jade](http://github.com/visionmedia/jade) to render _index.html_,469and since we do not use _layout: false_ the rendered contents of _index.jade_ will be passed as 470the _body_ local variable in _layout.jade_.471472 app.get('/', function(req, res){472 res.render('index.haml', {473 locals: { title: 'My Site' }474 });473 res.render('index.jade', { title: 'My Site' });474 });475476The new _view engine_ setting allows us to specify our default template engine,478so for example when using [Jade](http://github.com/visionmedia/jade) we could set:477so for example when using jade we could set:478479 app.set('view engine', 'jade');480481Allowing us to render with:
11 unmodified lines
493494Express also provides the _view options_ setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:495496 app.set('view options', {498 layout: false497 layout: false498 });499501Which can then be overridden within the `res.render()` call if need be:500Which can then be overridden within the _res.render()_ call if need be:501502 res.render('myview.ejs', { layout: true });503504When an alternate layout is required, we may also specify a path. For example if we have _view engine_ set to _jade_ and a file named _./views/mylayout.jade_ we can simply pass:
16 unmodified lines
521 });522523### View Partials524526The Express view system has built-in support for partials and collections, which are527sort of "mini" views representing a document fragment. For example rather than iterating525The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating526in a view to display comments, we would use a partial with collection support:527530 partial('comment.haml', { collection: comments });531532To make things even less verbose we can assume the extension as _.haml_ when omitted,533however if we wished we could use an ejs partial, within a haml view for example.534528 partial('comment', { collection: comments });529537And once again even further, when rendering a collection we can simply pass538an array, if no other options are desired:530If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:531532 partial('comment', comments);533534When using the partial collection support a few "magic" variables are provided535for free:536545 * _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 collection541542For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).543552NOTE: 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.544NOTE: 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.545546### Template Engines547548Below are a few template engines commonly used with Express:549550 * [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 node554555### Session Support556566Sessions 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_.557Sessions 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_.558568 app.use(express.cookieDecoder());569 app.use(express.session());559 app.use(express.cookieParser());560 app.use(express.session({ secret: "keyboard cat" }));561562By 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:563564 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 }));567568Now 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:569570 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 }));574575 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 lines
589 }590 res.render('shopping-cart');591 });592602The _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.593The _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.594595### Migration Guide596606 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.598599### req.header(key[, defaultValue])600601Get the case-insensitive request header _key_, with optional _defaultValue_:
1 unmodified line
603 req.header('Host');604 req.header('host');605 req.header('Accept', '*/*');606607The _Referrer_ and _Referer_ header fields are special-cased, either will work:608609 // sent Referrer: http://google.com610611 req.header('Referer');612 // => "http://google.com"613614 req.header('Referrer');615 // => "http://google.com"616617### req.accepts(type)618619Check if the _Accept_ header is present, and includes the given _type_.620
69 unmodified lines
690### req.param(name[, default])691692Return the value of param _name_ when present or _default_.693693 - 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=12697698To utilize urlencoded request bodies, _req.body_699should be an object. This can be done by using699the _express.bodyDecoder_ middleware.700the _express.bodyParser middleware.701702### req.flash(type[, msg])703704Queue flash _msg_ of the given _type_.
30 unmodified lines
735736 res.header('Content-Length');737 // => undefined738738 res.header('Content-Length', 123);739 res.header('Content-Length', 123);740 // => 123740741 742 res.header('Content-Length');743 // => 123744745### res.contentType(type)
1 unmodified line
747Sets the _Content-Type_ response header to the given _type_.748749 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"752753### res.attachment([filename])754755Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.756757 res.attachment('path/to/my/image.png');758758### res.sendfile(path)759### res.sendfile(path[, options[, callback]])760761Used by `res.download()` to transfer an arbitrary file. 762763 res.sendfile('path/to/my.file');764764This 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.765This method accepts an optional callback which is called when766an 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.767766 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 });775774### res.download(file[, filename])776Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:777778 res.sendfile(path, { bufferSize: 1024 }, function(err){779 // handle780 });781782### res.download(file[, filename[, callback]])783784Transfer the given _file_ as an attachment with optional alternative _filename_.785786 res.download('path/to/image.png');787 res.download('path/to/image.png', 'foo.png');
2 unmodified lines
790791 res.attachment(file);792 res.sendfile(file);793794An optional callback may be supplied as either the second or third argument, which is passed to _res.sendfile()_:795796 res.download(path, 'expenses.doc', function(err){797 // handle798 });799800### res.send(body|status[, headers|status[, status]])801788The `res.send()` method is a high level response utility allowing you to pass789objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status790code based responses. The following are all valid uses:802The _res.send()_ method is a high level response utility allowing you to pass803objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:804805 res.send(); // 204806 res.send(new Buffer('wahoo'));807 res.send({ some: 'json' });
5 unmodified lines
813By default the _Content-Type_ response header is set, however if explicitly814assigned through `res.send()` or previously with `res.header()` or `res.contentType()`815it will not be set again.816804Note that this method _end()_ the response, so you will want to use node's _res.writeHead()_ / _res.write()_ for multiple writes or streaming.817Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.818819### res.redirect(url[, status])820821Redirect to the given _url_ with a default response _status_ of 302.
9 unmodified lines
831the "home" setting and defaults to "/".832833### res.cookie(name, val[, options])834822Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.835Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc.836837 // "Remember me" for 15 minutes 838 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });839840To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:841829 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 });847848### res.clearCookie(name)849
6 unmodified lines
856Render _view_ with the given _options_ and optional callback _fn_.857When a callback function is given a response will _not_ be made858automatically, however otherwise a response of _200_ and _text/html_ is given.859847 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:860The _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:861850 - _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 });864865### res.partial(view[, options])866867Render _view_ partial with the given _options_. This method is always available
53 unmodified lines
921922 partial('movie', movie);923 // => In view: movie.director924925This 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:926927 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 });939940### res.local(name[, val])941942Get 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 lines
978979 app.enabled('some arbitrary setting');980 // => true981982### app.enabled(name)983984Check if setting _name_ is enabled:985986 app.enabled('view cache');987 // => false988989 app.enable('view cache');990 app.enabled('view cache');991 // => true992993### app.disable(name)994995Disable the given setting _name_:996
3 unmodified lines
1000 1001 app.disabled('some setting');1002 // => false10031004### app.disabled(name)10051006Check if setting _name_ is disabled:10071008 app.enable('view cache');10091010 app.disabled('view cache');1011 // => false10121013 app.disable('view cache');1014 app.disabled('view cache');1015 // => true10161017### app.configure(env|function[, function])10181019Define a callback function for the given _env_ (or all environments) with callback _function_:1020
6 unmodified lines
1027 });10281029### app.redirect(name, val)1030983For use with `res.redirect()` we can map redirects at the application level as shown below:1031For use with _res.redirect()_ we can map redirects at the application level as shown below:10321033 app.redirect('google', 'http://google.com');10341035Now in a route we may call:
2 unmodified lines
10381039We may also map dynamic redirects:10401041 app.redirect('comments', function(req, res){994 return '/post/' + req.params.id + '/comments';1042 return '/post/' + req.params.id + '/comments';1043 });10441045So now we may do the following, and the redirect will dynamically adjust to1046the context of the request. If we called this route with _GET /post/12_ our1047redirect _Location_ would be _/post/12/comments_.10481049 app.get('/post/:id', function(req, res){1002 res.redirect('comments');1050 res.redirect('comments');1051 });10521053When 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_:10541055 res.redirect('/posts');10561057### app.error(function)10581059Adds an error handler _function_ which will receive the exception as the first parameter as shown below.1060Note that we may set several error handlers by making several calls to this method, however the handler1061should call _next(err)_ if it does not wish to deal with the exception:10621063 app.error(function(err, req, res, next){1012 res.send(err.message, 500);1013 });1064 res.send(err.message, 500);1065 });10661067### app.helpers(obj)10681069Registers static view helpers.10701019 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 });10761077Our view could now utilize the _firstName_ and _lastName_ variables,1078as well as the _name()_ function exposed.1079
6 unmodified lines
1086evaluated against the _Server_ instance before a view is rendered. The _return value_ of this function1087becomes the local variable it is associated with.10881089 app.dynamicHelpers({1038 session: function(req, res){1039 return req.session;1040 }1090 session: function(req, res){1091 return req.session;1092 }1093 });10941095All views would now have _session_ available so that session data can be accessed via _session.name_ etc:1096
6 unmodified lines
1103 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 lines
11251126 app.register('.haml', require('haml-js'));11271128For engines that do not comply with the Express1077specification, we can also wrap their api this way.1129specification, we can also wrap their api this way. Below1130we map _.md_ to render markdown files, rendering the html once1131since it will not change on subsequent calls, and support local substitution1132in the form of "{name}".11331079 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 });11441145### app.listen([port[, host]])11461147Bind the app server to the given _port_, which defaults to 3000. When _host_ is omitted all
20 unmodified lines
modified: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 lines
39.IP "\(bu" 440Content negotiation41.42.IP "\(bu" 443Application mounting44.45.IP "\(bu" 446Focus on high performance47.48.IP "\(bu" 449View rendering and partials support
40 unmodified lines
90.IP "\(bu" 491Follow tjholowaychuk \fIhttp://twitter\.com/tjholowaychuk\fR on twitter for updates92.93.IP "\(bu" 491Annotated source documentation \fIapi\.html\fR92.93.IP "\(bu" 494View the Connect \fIhttp://github\.com/senchalabs/connect\fR repo for middleware usage95.96.IP "\(bu" 497View the Connect Wiki \fIhttp://wiki\.github\.com/senchalabs/connect/\fR for contrib middleware
12 unmodified lines
modified:docs/index.html+1 added-1 removed
210 unmodified lines
211<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 lines
239240<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 lines
modified:docs/index.md+1 added
deleted: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
deleted:examples/ejs/views/users/user.ejs-1 removed
1<li><%= user.name %> &lt;<%= user.email %>&gt;</li>
added:examples/ejs/views/users/user.html+1 added
1<li><%= user.name %> &lt;<%= user.email %>&gt;</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 lines
9var express = require('../../lib/express');1011var app = express.createServer();1213// Register ejs as .html1415app.register('.html', require('ejs'));1617// Optional since express defaults to CWD/views1819app.set('views', __dirname + '/views');20app.set('view engine', 'html');2122// Dummy users23var users = [24 { name: 'tj', email: 'tj@sencha.com' }
1 unmodified line
26 , { name: 'aaron', email: 'aaron.heckmann+github@gmail.com' }27];2829app.get('/', function(req, res){25 res.render('users.ejs', { users: users });30 res.render('users', { users: users });31});3233app.listen(3000);34console.log('Express app started on port 3000');
added:examples/markdown/views/index.md+4 added
12# {title}34Just an example view rendered with _markdown_.
added:examples/markdown/app.js+41 added
12// Expose modules in ./support for demo purposes3require.paths.unshift(__dirname + '/../../support');45// $ npm install markdown67/**8 * Module dependencies.9 */1011var express = require('../../lib/express')12 , md = require('markdown').markdown;1314var app = express.createServer();1516// register .md so that markdown may comply17// with the express view system by implementing18// a .compile() method1920app.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});3031// Optional since express defaults to CWD/views3233app.set('views', __dirname + '/views');34app.set('view engine', 'md');3536app.get('/', function(req, res){37 res.render('index', { layout: false, title: 'Markdown Example' });38});3940app.listen(3000);41console.log('Express app started on port 3000');
modified:lib/view/view.js-10 removed
174 unmodified lines
175 * 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