guide.1
This file
Path
docs/guide.1
1,871 lines · 38.8 KiB
Last changed by
Rebuilt docsTj Holowaychukbefore adoptiond017c3e
History of this fileTake it
1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "GUIDE" "" "November 2010" "" ""5.6.SH "NAME"7\fBguide\fR8.9.SS "Installation"10curl:11.12.IP "" 413.14.nf1516$ curl \-# http://expressjs\.com/install\.sh | sh17.18.fi19.20.IP "" 021.22.P23npm:24.25.IP "" 426.27.nf2829$ npm install express30.31.fi32.33.IP "" 034.35.P36git clone, first update the submodules:37.38.IP "" 439.40.nf4142$ git submodule update \-\-init43$ make install44$ make install\-support45.46.fi47.48.IP "" 049.50.SS "Creating An Application"51The \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\.52.53.IP "" 454.55.nf5657var app = require(\'express\')\.createServer();5859app\.get(\'/\', function(req, res){60 res\.send(\'hello world\');61});6263app\.listen(3000);64.65.fi66.67.IP "" 068.69.SS "Configuration"70Express 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\.71.72.P73In 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\.74.75.IP "" 476.77.nf7879app\.configure(function(){80 app\.use(express\.methodOverride());81 app\.use(express\.bodyDecoder());82 app\.use(app\.router);83 app\.use(express\.staticProvider(__dirname + \'/public\'));84});8586app\.configure(\'development\', function(){87 app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));88});8990app\.configure(\'production\', function(){91 app\.use(express\.errorHandler());92});93.94.fi95.96.IP "" 097.98.P99For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:100.101.IP "" 4102.103.nf104105app\.configure(function(){106 app\.set(\'views\', __dirname + \'/views\');107 app\.set(\'views\');108 // => "\.\.\. views directory \.\.\."109110 app\.enable(\'some feature\');111 // same as app\.set(\'some feature\', true);112113 app\.disable(\'some feature\');114 // same as app\.set(\'some feature\', false);115});116.117.fi118.119.IP "" 0120.121.P122To alter the environment we can set the \fINODE_ENV\fR environment variable, for example:123.124.IP "" 4125.126.nf127128$ NODE_ENV=production node app\.js129.130.fi131.132.IP "" 0133.134.P135This is \fIvery\fR important, as many caching mechanisms are \fIonly enabled\fR when in production\.136.137.SS "Settings"138Express supports the following settings out of the box:139.140.IP "\(bu" 4141\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR142.143.IP "\(bu" 4144\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.145.146.IP "\(bu" 4147\fIviews\fR Root views directory defaulting to \fBCWD/views\fR148.149.IP "\(bu" 4150\fIview engine\fR Default view engine name for views rendered without extensions151.152.IP "\(bu" 4153\fIview options\fR An object specifying global view options154.155.IP "\(bu" 4156\fIpartials\fR Root view partials directory defaulting to \fIviews\fR/partials\.157.158.IP "\(bu" 4159\fIstream threshold\fR Bytesize indicating when a file should be streamed for \fIres\.sendfile()\fR using \fIfs\.ReadStream()\fR and \fIsys\.pump()\fR\.160.161.IP "" 0162.163.SS "Routing"164Express 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\.165.166.IP "" 4167.168.nf169170app\.get(\'/user/:id\', function(req, res){171 res\.send(\'user \' + req\.params\.id);172});173.174.fi175.176.IP "" 0177.178.P179A route is simple a string which is compiled to a \fIRegExp\fR internally\. For example when \fI/user/:id\fR is compiled, a simplified version of the regexp may look similar to:180.181.IP "" 4182.183.nf184185\e/user\e/([^\e/]+)\e/?186.187.fi188.189.IP "" 0190.191.P192Regular expression literals may also be passed for complex uses\. Since capture groups with literal \fIRegExp\fR\'s are anonymous we can access them directly \fBreq\.params\fR\.193.194.IP "" 4195.196.nf197198app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){199 res\.send(req\.params);200});201.202.fi203.204.IP "" 0205.206.P207Curl requests against the previously defined route:208.209.IP "" 4210.211.nf212213 $ curl http://dev:3000/user214 [null,null]215 $ curl http://dev:3000/users216 [null,null]217 $ curl http://dev:3000/users/1218 ["1",null]219 $ curl http://dev:3000/users/1\.\.15220 ["1","15"]221.222.fi223.224.IP "" 0225.226.P227Below are some route examples, and the associated paths that they may consume:228.229.IP "" 4230.231.nf232233 "/user/:id"234 /user/12235236 "/users/:id?"237 /users/5238 /users239240 "/files/*"241 /files/jquery\.js242 /files/javascripts/jquery\.js243244 "/file/*\.*"245 /files/jquery\.js246 /files/javascripts/jquery\.js247248 "/user/:id/:operation?"249 /user/1250 /user/1/edit251252 "/products\.:format"253 /products\.json254 /products\.xml255256 "/products\.:format?"257 /products\.json258 /products\.xml259 /products260.261.fi262.263.IP "" 0264.265.P266For 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:267.268.IP "" 4269.270.nf271272var express = require(\'express\')273 , app = express\.createServer();274275app\.use(express\.bodyDecoder());276277app\.post(\'/\', function(req, res){278 res\.send(req\.body);279});280281app\.listen(3000);282.283.fi284.285.IP "" 0286.287.SS "Passing Route Control"288We 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\.289.290.IP "" 4291.292.nf293294app\.get(\'/users/:id?\', function(req, res, next){295 var id = req\.params\.id;296 if (id) {297 // do something298 } else {299 next();300 }301});302303app\.get(\'/users\', function(req, res){304 // do something else305});306.307.fi308.309.IP "" 0310.311.P312Express 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:313.314.IP "" 4315.316.nf317318var express = require(\'express\')319 , app = express\.createServer();320321var users = [{ name: \'tj\' }];322323app\.all(\'/user/:id/:op?\', function(req, res, next){324 req\.user = users[req\.params\.id];325 if (req\.user) {326 next();327 } else {328 next(new Error(\'cannot find user \' + req\.params\.id));329 }330});331332app\.get(\'/user/:id\', function(req, res){333 res\.send(\'viewing \' + req\.user\.name);334});335336app\.get(\'/user/:id/edit\', function(req, res){337 res\.send(\'editing \' + req\.user\.name);338});339340app\.put(\'/user/:id\', function(req, res){341 res\.send(\'updating \' + req\.user\.name);342});343344app\.get(\'*\', function(req, res){345 res\.send(\'what???\', 404);346});347348app\.listen(3000);349.350.fi351.352.IP "" 0353.354.SS "Middleware"355Middleware via Connect \fIhttp://github\.com/senchalabs/connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:356.357.IP "" 4358.359.nf360361 var express = require(\'express\');362363var app = express\.createServer(364 express\.logger(),365 express\.bodyDecoder()366 );367.368.fi369.370.IP "" 0371.372.P373Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:374.375.IP "" 4376.377.nf378379app\.use(express\.logger({ format: \':method :uri\' }));380.381.fi382.383.IP "" 0384.385.P386Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:387.388.IP "" 4389.390.nf391392var connect = require(\'connect\');393app\.use(connect\.logger());394.395.fi396.397.IP "" 0398.399.P400This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:401.402.IP "" 4403.404.nf405406app\.use(express\.logger());407.408.fi409.410.IP "" 0411.412.SS "Route Middleware"413Routes 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\.414.415.P416Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.417.418.IP "" 4419.420.nf421422app\.get(\'/user/:id\', function(req, res, next){423 loadUser(req\.params\.id, function(err, user){424 if (err) return next(err);425 res\.send(\'Viewing user \' + user\.name);426 });427});428.429.fi430.431.IP "" 0432.433.P434To 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\.435.436.IP "" 4437.438.nf439440function loadUser(req, res, next) {441 // You would fetch your user from the db442 var user = users[req\.params\.id];443 if (user) {444 req\.user = user;445 next();446 } else {447 next(new Error(\'Failed to load user \' + req\.params\.id));448 }449}450451app\.get(\'/user/:id\', loadUser, function(req, res){452 res\.send(\'Viewing user \' + req\.user\.name);453});454.455.fi456.457.IP "" 0458.459.P460Multiple 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\.461.462.IP "" 4463.464.nf465466function andRestrictToSelf(req, res, next) {467 req\.authenticatedUser\.id == req\.user\.id468 ? next()469 : next(new Error(\'Unauthorized\'));470}471472app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){473 res\.send(\'Editing user \' + req\.user\.name);474});475.476.fi477.478.IP "" 0479.480.P481Keeping in mind that middleware are simply functions, we can define function that \fIreturns\fR the middleware in order to create a more expressive and flexible solution as shown below\.482.483.IP "" 4484.485.nf486487function andRestrictTo(role) {488 return function(req, res, next) {489 req\.authenticatedUser\.role == role490 ? next()491 : next(new Error(\'Unauthorized\'));492 }493}494495app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){496 res\.send(\'Deleted user \' + req\.user\.name);497});498.499.fi500.501.IP "" 0502.503.P504Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.505.506.IP "" 4507.508.nf509510var a = [middleware1, middleware2]511 , b = [middleware3, middleware4]512 , all = [a, b];513514app\.get(\'/foo\', a, function(){});515app\.get(\'/bar\', a, function(){});516517app\.get(\'/\', a, middleware3, middleware4, function(){});518app\.get(\'/\', a, b, function(){});519app\.get(\'/\', all, function(){});520.521.fi522.523.IP "" 0524.525.P526For this example in full, view the route middleware example \fIhttp://github\.com/visionmedia/express/blob/master/examples/route\-middleware/app\.js\fR in the repository\.527.528.SS "HTTP Methods"529We have seen \fIapp\.get()\fR a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as \fIapp\.post()\fR, \fIapp\.del()\fR, etc\.530.531.P532A common example for \fIPOST\fR usage, is when "submitting" a form\. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it\.533.534.IP "" 4535.536.nf537538 <form method="post" action="/">539 <input type="text" name="user[name]" />540 <input type="text" name="user[email]" />541 <input type="submit" value="Submit" />542 </form>543.544.fi545.546.IP "" 0547.548.P549By 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:550.551.IP "" 4552.553.nf554555app\.use(express\.bodyDecoder());556.557.fi558.559.IP "" 0560.561.P562Our route below will now have access to the \fIreq\.body\.user\fR object which will contain the \fIname\fR and \fIemail\fR properties when defined\.563.564.IP "" 4565.566.nf567568app\.post(\'/\', function(req, res){569 console\.log(req\.body\.user);570 res\.redirect(\'back\');571});572.573.fi574.575.IP "" 0576.577.P578When 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\.579.580.IP "" 4581.582.nf583584app\.use(express\.bodyDecoder());585app\.use(express\.methodOverride());586.587.fi588.589.IP "" 0590.591.P592The reason that these are not always defaults, is simply because these are not required for Express to be fully functional\. Depending on the needs of your application, you may not need these at all, your methods such as \fIPUT\fR and \fIDELETE\fR can still be accessed by clients which can use them directly, although \fImethodOverride\fR provides a great solution for forms\. Below shows what the usage of \fIPUT\fR might look like:593.594.IP "" 4595.596.nf597598<form method="post" action="/">599 <input type="hidden" name="_method" value="put" />600 <input type="text" name="user[name]" />601 <input type="text" name="user[email]" />602 <input type="submit" value="Submit" />603</form>604605app\.put(\'/\', function(){606 console\.log(req\.body\.user);607 res\.redirect(\'back\');608});609.610.fi611.612.IP "" 0613.614.SS "Error Handling"615Express provides the \fIapp\.error()\fR method which receives exceptions thrown within a route, or passed to \fInext(err)\fR\. Below is an example which serves different pages based on our ad\-hoc \fINotFound\fR exception:616.617.IP "" 4618.619.nf620621function NotFound(msg){622 this\.name = \'NotFound\';623 Error\.call(this, msg);624 Error\.captureStackTrace(this, arguments\.callee);625}626627sys\.inherits(NotFound, Error);628629app\.get(\'/404\', function(req, res){630 throw new NotFound;631});632633app\.get(\'/500\', function(req, res){634 throw new Error(\'keyboard cat!\');635});636.637.fi638.639.IP "" 0640.641.P642We can call \fIapp\.error()\fR several times as shown below\. Here we check for an instanceof \fINotFound\fR and show the 404 page, or we pass on to the next error handler\.643.644.P645Note that these handlers can be defined anywhere, as they will be placed below the route handlers on \fIlisten()\fR\. This allows for definition within \fIconfigure()\fR blocks so we can handle exceptions in different ways based on the environment\.646.647.IP "" 4648.649.nf650651app\.error(function(err, req, res, next){652 if (err instanceof NotFound) {653 res\.render(\'404\.jade\');654 } else {655 next(err);656 }657});658.659.fi660.661.IP "" 0662.663.P664Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like665.666.IP "" 4667.668.nf669670app\.error(function(err, req, res){671 res\.render(\'500\.jade\', {672 locals: {673 error: err674 }675 });676});677.678.fi679.680.IP "" 0681.682.P683Our apps could also utilize the Connect \fIerrorHandler\fR middleware to report on exceptions\. For example if we wish to output exceptions in "development" mode to \fIstderr\fR we can use:684.685.IP "" 4686.687.nf688689app\.use(express\.errorHandler({ dumpExceptions: true }));690.691.fi692.693.IP "" 0694.695.P696Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:697.698.IP "" 4699.700.nf701702app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));703.704.fi705.706.IP "" 0707.708.P709The \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\.710.711.SS "View Rendering"712View 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\.713.714.P715Below 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\.716.717.IP "" 4718.719.nf720721app\.get(\'/\', function(req, res){722 res\.render(\'index\.haml\', {723 locals: { title: \'My Site\' }724 });725});726.727.fi728.729.IP "" 0730.731.P732The 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:733.734.IP "" 4735.736.nf737738app\.set(\'view engine\', \'jade\');739.740.fi741.742.IP "" 0743.744.P745Allowing us to render with:746.747.IP "" 4748.749.nf750751res\.render(\'index\');752.753.fi754.755.IP "" 0756.757.P758vs:759.760.IP "" 4761.762.nf763764res\.render(\'index\.jade\');765.766.fi767.768.IP "" 0769.770.P771When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:772.773.IP "" 4774.775.nf776777res\.render(\'another\-page\.ejs\');778.779.fi780.781.IP "" 0782.783.P784Express also provides the \fIview options\fR setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:785.786.IP "" 4787.788.nf789790app\.set(\'view options\', {791 layout: false792});793.794.fi795.796.IP "" 0797.798.P799Which can then be overridden within the \fBres\.render()\fR call if need be:800.801.IP "" 4802.803.nf804805res\.render(\'myview\.ejs\', { layout: true });806.807.fi808.809.IP "" 0810.811.P812When an alternate layout is required, we may also specify a path\. For example if we have \fIview engine\fR set to \fIjade\fR and a file named \fI\./views/mylayout\.jade\fR we can simply pass:813.814.IP "" 4815.816.nf817818res\.render(\'page\', { layout: \'mylayout\' });819.820.fi821.822.IP "" 0823.824.P825Otherwise we must specify the extension:826.827.IP "" 4828.829.nf830831res\.render(\'page\', { layout: \'mylayout\.jade\' });832.833.fi834.835.IP "" 0836.837.P838These paths may also be absolute:839.840.IP "" 4841.842.nf843844res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });845.846.fi847.848.IP "" 0849.850.P851A good example of this is specifying custom \fIejs\fR opening and closing tags:852.853.IP "" 4854.855.nf856857app\.set(\'view options\', {858 open: \'{{\',859 close: \'}}\'860});861.862.fi863.864.IP "" 0865.866.SS "View Partials"867The 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:868.869.IP "" 4870.871.nf872873partial(\'comment\.haml\', { collection: comments });874.875.fi876.877.IP "" 0878.879.P880To 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\.881.882.IP "" 4883.884.nf885886partial(\'comment\', { collection: comments });887.888.fi889.890.IP "" 0891.892.P893And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:894.895.IP "" 4896.897.nf898899partial(\'comment\', comments);900.901.fi902.903.IP "" 0904.905.P906When using the partial collection support a few "magic" variables are provided for free:907.908.IP "\(bu" 4909\fIfirstInCollection\fR True if this is the first object910.911.IP "\(bu" 4912\fIindexInCollection\fR Index of the object in the collection913.914.IP "\(bu" 4915\fIlastInCollection\fR True if this is the last object916.917.IP "\(bu" 4918\fIcollectionLength\fR Length of the collection919.920.IP "" 0921.922.P923For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.924.925.SS "Template Engines"926Below are a few template engines commonly used with Express:927.928.IP "\(bu" 4929Jade \fIhttp://jade\-lang\.com\fR haml\.js successor930.931.IP "\(bu" 4932Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates933.934.IP "\(bu" 4935EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript936.937.IP "\(bu" 4938CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating939.940.IP "\(bu" 4941jQuery Templates \fIhttps://github\.com/kof/node\-jqtpl\fR for node942.943.IP "" 0944.945.SS "Session Support"946Sessions 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\.947.948.IP "" 4949.950.nf951952app\.use(express\.cookieDecoder());953app\.use(express\.session());954.955.fi956.957.IP "" 0958.959.P960By default the \fIsession\fR middleware uses the memory store bundled with Connect, however many implementations exist\. For example connect\-redis \fIhttp://github\.com/visionmedia/connect\-redis\fR supplies a Redis \fIhttp://code\.google\.com/p/redis/\fR session store and can be used as shown below:961.962.IP "" 4963.964.nf965966var RedisStore = require(\'connect\-redis\');967app\.use(express\.cookieDecoder());968app\.use(express\.session({ store: new RedisStore }));969.970.fi971.972.IP "" 0973.974.P975Now the \fIreq\.session\fR and \fIreq\.sessionStore\fR properties will be accessible to all routes and subsequent middleware\. Properties on \fIreq\.session\fR are automatically saved on a response, so for example if we wish to shopping cart data:976.977.IP "" 4978.979.nf980981var RedisStore = require(\'connect\-redis\');982app\.use(express\.bodyDecoder());983app\.use(express\.cookieDecoder());984app\.use(express\.session({ store: new RedisStore }));985986app\.post(\'/add\-to\-cart\', function(req, res){987 // Perhaps we posted several items with a form988 // (use the bodyDecoder() middleware for this)989 var items = req\.body\.items;990 req\.session\.items = items;991 res\.redirect(\'back\');992});993994app\.get(\'/add\-to\-cart\', function(req, res){995 // When redirected back to GET /add\-to\-cart996 // we could check req\.session\.items && req\.session\.items\.length997 // to print out a message998 if (req\.session\.items && req\.session\.items\.length) {999 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);1000 }1001 res\.render(\'shopping\-cart\');1002});1003.1004.fi1005.1006.IP "" 01007.1008.P1009The \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\.1010.1011.SS "Migration Guide"1012Pre\-beta Express developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.1013.1014.SS "req\.header(key[, defaultValue])"1015Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1016.1017.IP "" 41018.1019.nf10201021req\.header(\'Host\');1022req\.header(\'host\');1023req\.header(\'Accept\', \'*/*\');1024.1025.fi1026.1027.IP "" 01028.1029.SS "req\.accepts(type)"1030Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1031.1032.P1033When the \fIAccept\fR header is not present \fItrue\fR is returned\. Otherwise the given \fItype\fR is matched by an exact match, and then subtypes\. You may pass the subtype such as "html" which is then converted internally to "text/html" using the mime lookup table\.1034.1035.IP "" 41036.1037.nf10381039// Accept: text/html1040req\.accepts(\'html\');1041// => true10421043// Accept: text/*; application/json1044req\.accepts(\'html\');1045req\.accepts(\'text/html\');1046req\.accepts(\'text/plain\');1047req\.accepts(\'application/json\');1048// => true10491050req\.accepts(\'image/png\');1051req\.accepts(\'png\');1052// => false1053.1054.fi1055.1056.IP "" 01057.1058.SS "req\.is(type)"1059Check if the incoming request contains the \fIContent\-Type\fR header field, and it contains the give mime \fItype\fR\.1060.1061.IP "" 41062.1063.nf10641065 // With Content\-Type: text/html; charset=utf\-81066 req\.is(\'html\');1067 req\.is(\'text/html\');1068 // => true10691070 // When Content\-Type is application/json1071 req\.is(\'json\');1072 req\.is(\'application/json\');1073 // => true10741075 req\.is(\'html\');1076 // => false1077.1078.fi1079.1080.IP "" 01081.1082.P1083Ad\-hoc callbacks can also be registered with Express, to perform assertions again the request, for example if we need an expressive way to check if our incoming request is an image, we can register \fI"an image"\fR callback:1084.1085.IP "" 41086.1087.nf10881089 app\.is(\'an image\', function(req){1090 return 0 == req\.headers[\'content\-type\']\.indexOf(\'image\');1091 });1092.1093.fi1094.1095.IP "" 01096.1097.P1098Now within our route callbacks, we can use to to assert content types such as \fI"image/jpeg"\fR, \fI"image/png"\fR, etc\.1099.1100.IP "" 41101.1102.nf11031104 app\.post(\'/image/upload\', function(req, res, next){1105 if (req\.is(\'an image\')) {1106 // do something1107 } else {1108 next();1109 }1110 });1111.1112.fi1113.1114.IP "" 01115.1116.P1117Keep in mind this method is \fInot\fR limited to checking \fIContent\-Type\fR, you can perform any request assertion you wish\.1118.1119.P1120Wildcard matches can also be made, simplifying our example above for \fI"an image"\fR, by asserting the \fIsubtype\fR only:1121.1122.IP "" 41123.1124.nf11251126req\.is(\'image/*\');1127.1128.fi1129.1130.IP "" 01131.1132.P1133We may also assert the \fItype\fR as shown below, which would return true for \fI"application/json"\fR, and \fI"text/json"\fR\.1134.1135.IP "" 41136.1137.nf11381139req\.is(\'*/json\');1140.1141.fi1142.1143.IP "" 01144.1145.SS "req\.param(name)"1146Return the value of param \fIname\fR when present\.1147.1148.IP "\(bu" 41149Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1150.1151.IP "\(bu" 41152Checks query string params (\fIreq\.query\fR), ex: ?id=121153.1154.IP "\(bu" 41155Checks urlencoded body params (\fIreq\.body\fR), ex: id=121156.1157.IP "" 01158.1159.P1160To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.1161.1162.SS "req\.flash(type[, msg])"1163Queue flash \fImsg\fR of the given \fItype\fR\.1164.1165.IP "" 41166.1167.nf11681169req\.flash(\'info\', \'email sent\');1170req\.flash(\'error\', \'email delivery failed\');1171req\.flash(\'info\', \'email re\-sent\');1172// => 211731174req\.flash(\'info\');1175// => [\'email sent\', \'email re\-sent\']11761177req\.flash(\'info\');1178// => []11791180req\.flash();1181// => { error: [\'email delivery failed\'], info: [] }1182.1183.fi1184.1185.IP "" 01186.1187.P1188Flash notification message may also utilize formatters, by default only the %s string formatter is available:1189.1190.IP "" 41191.1192.nf11931194req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1195.1196.fi1197.1198.IP "" 01199.1200.SS "req\.isXMLHttpRequest"1201Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1202.1203.IP "" 41204.1205.nf12061207req\.xhr1208req\.isXMLHttpRequest1209.1210.fi1211.1212.IP "" 01213.1214.SS "res\.header(key[, val])"1215Get or set the response header \fIkey\fR\.1216.1217.IP "" 41218.1219.nf12201221res\.header(\'Content\-Length\');1222// => undefined12231224res\.header(\'Content\-Length\', 123);1225// => 12312261227res\.header(\'Content\-Length\');1228// => 1231229.1230.fi1231.1232.IP "" 01233.1234.SS "res\.contentType(type)"1235Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1236.1237.IP "" 41238.1239.nf12401241 var filename = \'path/to/image\.png\';1242 res\.contentType(filename);1243 // res\.headers[\'Content\-Type\'] is now "image/png"1244.1245.fi1246.1247.IP "" 01248.1249.SS "res\.attachment([filename])"1250Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1251.1252.IP "" 41253.1254.nf12551256 res\.attachment(\'path/to/my/image\.png\');1257.1258.fi1259.1260.IP "" 01261.1262.SS "res\.sendfile(path)"1263Used by \fBres\.download()\fR to transfer an arbitrary file\.1264.1265.IP "" 41266.1267.nf12681269res\.sendfile(\'path/to/my\.file\');1270.1271.fi1272.1273.IP "" 01274.1275.P1276This 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\.1277.1278.IP "" 41279.1280.nf12811282res\.sendfile(path, function(err, path){1283 if (err) {1284 // handle the error1285 } else {1286 console\.log(\'transferred %s\', path);1287 }1288});1289.1290.fi1291.1292.IP "" 01293.1294.P1295When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.1296.1297.SS "res\.download(file[, filename])"1298Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1299.1300.IP "" 41301.1302.nf13031304res\.download(\'path/to/image\.png\');1305res\.download(\'path/to/image\.png\', \'foo\.png\');1306.1307.fi1308.1309.IP "" 01310.1311.P1312This is equivalent to:1313.1314.IP "" 41315.1316.nf13171318res\.attachment(file);1319res\.sendfile(file);1320.1321.fi1322.1323.IP "" 01324.1325.SS "res\.send(body|status[, headers|status[, status]])"1326The \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:1327.1328.IP "" 41329.1330.nf13311332 res\.send(); // 2041333 res\.send(new Buffer(\'wahoo\'));1334 res\.send({ some: \'json\' });1335 res\.send(\'<p>some html</p>\');1336 res\.send(\'Sorry, cant find that\', 404);1337 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1338 res\.send(404);1339.1340.fi1341.1342.IP "" 01343.1344.P1345By 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\.1346.1347.SS "res\.redirect(url[, status])"1348Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1349.1350.IP "" 41351.1352.nf13531354res\.redirect(\'/\', 301);1355res\.redirect(\'/account\');1356res\.redirect(\'http://google\.com\');1357res\.redirect(\'home\');1358res\.redirect(\'back\');1359.1360.fi1361.1362.IP "" 01363.1364.P1365Express 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 "/"\.1366.1367.SS "res\.cookie(name, val[, options])"1368Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1369.1370.IP "" 41371.1372.nf13731374// "Remember me" for 15 minutes1375res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1376.1377.fi1378.1379.IP "" 01380.1381.P1382To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1383.1384.IP "" 41385.1386.nf13871388app\.use(express\.cookieDecoder());13891390app\.get(\'/\', function(req, res){1391 // use req\.cookies\.rememberme1392});1393.1394.fi1395.1396.IP "" 01397.1398.SS "res\.clearCookie(name)"1399Clear cookie \fIname\fR by setting "expires" far in the past\.1400.1401.IP "" 41402.1403.nf14041405res\.clearCookie(\'rememberme\');1406.1407.fi1408.1409.IP "" 01410.1411.SS "res\.render(view[, options[, fn]])"1412Render \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\.1413.1414.P1415Most 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:1416.1417.IP "\(bu" 41418\fIscope\fR Template evaluation context (value of \fIthis\fR)1419.1420.IP "\(bu" 41421\fIlocals\fR Object containing local variables1422.1423.IP "\(bu" 41424\fIdebug\fR Output debugging information1425.1426.IP "\(bu" 41427\fIstatus\fR Response status code, defaults to 2001428.1429.IP "\(bu" 41430\fIheaders\fR Response headers object1431.1432.IP "" 01433.1434.SS "res\.partial(view[, options])"1435Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1436.1437.IP "\(bu" 41438\fIobject\fR the object named by \fIas\fR or derived from the view name1439.1440.IP "\(bu" 41441\fIas\fR Variable name for each \fIcollection\fR or \fIobject\fR value, defaults to the view name\.1442.1443.IP "\(bu" 41444as: \'something\' will add the \fIsomething\fR local variable1445.1446.IP "\(bu" 41447as: this will use the collection value as the template context1448.1449.IP "\(bu" 41450as: global will merge the collection value\'s properties with \fIlocals\fR1451.1452.IP "" 014531454.1455.IP "\(bu" 41456\fIcollection\fR Array of objects, the name is derived from the view name itself\. For example \fIvideo\.html\fR will have a object \fIvideo\fR available to it\.1457.1458.IP "" 01459.1460.P1461The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1462.1463.IP "" 41464.1465.nf14661467partial(\'theatre/movie\.jade\', { collection: movies });1468partial(\'theatre/movie\.jade\', movies);1469partial(\'movie\.jade\', { collection: movies });1470partial(\'movie\.jade\', movies);1471partial(\'movie\', movies);1472// In view: movie\.director1473.1474.fi1475.1476.IP "" 01477.1478.P1479To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1480.1481.IP "" 41482.1483.nf14841485partial(\'movie\', { collection: movies, as: \'video\' });1486// In view: video\.director1487.1488.fi1489.1490.IP "" 01491.1492.P1493Also we can make our movie the value of \fIthis\fR within our view so that instead of \fImovie\.director\fR we could use \fIthis\.director\fR\.1494.1495.IP "" 41496.1497.nf14981499partial(\'movie\', { collection: movies, as: this });1500// In view: this\.director1501.1502.fi1503.1504.IP "" 01505.1506.P1507Another alternative is to "explode" the properties of the collection item into pseudo globals (local variables) by using \fIas: global\fR, which again is syntactic sugar:1508.1509.IP "" 41510.1511.nf15121513partial(\'movie\', { collection: movies, as: global });1514// In view: director1515.1516.fi1517.1518.IP "" 01519.1520.P1521This same logic applies to a single partial object usage:1522.1523.IP "" 41524.1525.nf15261527partial(\'movie\', { object: movie, as: this });1528// In view: this\.director15291530partial(\'movie\', { object: movie, as: global });1531// In view: director15321533partial(\'movie\', { object: movie, as: \'video\' });1534// In view: video\.director15351536partial(\'movie\', { object: movie });1537// In view: movie\.director1538.1539.fi1540.1541.IP "" 01542.1543.P1544When a non\-collection (does \fInot\fR have \fI\.length\fR) is passed as the second argument, it is assumed to be the \fIobject\fR, after which the object\'s local variable name is derived from the view name:1545.1546.IP "" 41547.1548.nf15491550partial(\'movie\', movie);1551// => In view: movie\.director1552.1553.fi1554.1555.IP "" 01556.1557.SS "app\.set(name[, val])"1558Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1559.1560.IP "" 41561.1562.nf15631564app\.set(\'views\', __dirname + \'/views\');1565app\.set(\'views\');1566// => \.\.\.path\.\.\.1567.1568.fi1569.1570.IP "" 01571.1572.P1573Alternatively you may simply access the settings via \fIapp\.settings\fR:1574.1575.IP "" 41576.1577.nf15781579app\.settings\.views1580// => \.\.\.path\.\.\.1581.1582.fi1583.1584.IP "" 01585.1586.SS "app\.enable(name)"1587Enable the given setting \fIname\fR:1588.1589.IP "" 41590.1591.nf15921593app\.enable(\'some arbitrary setting\');1594app\.set(\'some arbitrary setting\');1595// => true1596.1597.fi1598.1599.IP "" 01600.1601.SS "app\.disable(name)"1602Disable the given setting \fIname\fR:1603.1604.IP "" 41605.1606.nf16071608app\.disable(\'some setting\');1609app\.set(\'some setting\');1610// => false1611.1612.fi1613.1614.IP "" 01615.1616.SS "app\.configure(env|function[, function])"1617Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1618.1619.IP "" 41620.1621.nf16221623app\.configure(function(){1624 // executed for each env1625});16261627app\.configure(\'development\', function(){1628 // executed for \'development\' only1629});1630.1631.fi1632.1633.IP "" 01634.1635.SS "app\.redirect(name, val)"1636For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1637.1638.IP "" 41639.1640.nf16411642app\.redirect(\'google\', \'http://google\.com\');1643.1644.fi1645.1646.IP "" 01647.1648.P1649Now in a route we may call:1650.1651.P1652res\.redirect(\'google\');1653.1654.P1655We may also map dynamic redirects:1656.1657.IP "" 41658.1659.nf16601661app\.redirect(\'comments\', function(req, res){1662 return \'/post/\' + req\.params\.id + \'/comments\';1663});1664.1665.fi1666.1667.IP "" 01668.1669.P1670So now we may do the following, and the redirect will dynamically adjust to the context of the request\. If we called this route with \fIGET /post/12\fR our redirect \fILocation\fR would be \fI/post/12/comments\fR\.1671.1672.IP "" 41673.1674.nf16751676app\.get(\'/post/:id\', function(req, res){1677 res\.redirect(\'comments\');1678});1679.1680.fi1681.1682.IP "" 01683.1684.SS "app\.error(function)"1685Adds 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:1686.1687.IP "" 41688.1689.nf16901691app\.error(function(err, req, res, next){1692 res\.send(err\.message, 500);1693});1694.1695.fi1696.1697.IP "" 01698.1699.SS "app\.helpers(obj)"1700Registers static view helpers\.1701.1702.IP "" 41703.1704.nf17051706app\.helpers({1707 name: function(first, last){ return first + \', \' + last },1708 firstName: \'tj\',1709 lastName: \'holowaychuk\'1710});1711.1712.fi1713.1714.IP "" 01715.1716.P1717Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1718.1719.IP "" 41720.1721.nf17221723<%= name(firstName, lastName) %>1724.1725.fi1726.1727.IP "" 01728.1729.SS "app\.dynamicHelpers(obj)"1730Registers dynamic view helpers\. Dynamic view helpers are simply functions which accept \fIreq\fR, \fIres\fR, and are evaluated against the \fIServer\fR instance before a view is rendered\. The \fIreturn value\fR of this function becomes the local variable it is associated with\.1731.1732.IP "" 41733.1734.nf17351736app\.dynamicHelpers({1737 session: function(req, res){1738 return req\.session;1739 }1740});1741.1742.fi1743.1744.IP "" 01745.1746.P1747All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1748.1749.IP "" 41750.1751.nf17521753<%= session\.name %>1754.1755.fi1756.1757.IP "" 01758.1759.SS "app\.mounted(fn)"1760Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1761.1762.IP "" 41763.1764.nf17651766var app = express\.createServer(),1767 blog = express\.createServer();17681769blog\.mounted(function(parent){1770 // parent is app1771 // "this" is blog1772});17731774app\.use(blog);1775.1776.fi1777.1778.IP "" 01779.1780.SS "app\.register(ext, exports)"1781Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:1782.1783.IP "" 41784.1785.nf17861787 app\.register(\'\.html\', require(\'jade\'));1788.1789.fi1790.1791.IP "" 01792.1793.P1794This is also useful for libraries that may not match extensions correctly\. For example my haml\.js library is installed from npm as "hamljs" so instead of layout\.hamljs, we can register the engine as "\.haml":1795.1796.IP "" 41797.1798.nf17991800 app\.register(\'\.haml\', require(\'haml\-js\'));1801.1802.fi1803.1804.IP "" 01805.1806.P1807For engines that do not comply with the Express specification, we can also wrap their api this way\.1808.1809.IP "" 41810.1811.nf18121813 app\.register(\'\.foo\', {1814 render: function(str, options) {1815 // perhaps their api is1816 // return foo\.toHTML(str, options);1817 }1818 });1819.1820.fi1821.1822.IP "" 01823.1824.SS "app\.listen([port[, host]])"1825Bind the app server to the given \fIport\fR, which defaults to 3000\. When \fIhost\fR is omitted all connections will be accepted via \fIINADDR_ANY\fR\.1826.1827.IP "" 41828.1829.nf18301831app\.listen();1832app\.listen(3000);1833app\.listen(3000, \'n\.n\.n\.n\');1834.1835.fi1836.1837.IP "" 01838.1839.P1840The \fIport\fR argument may also be a string representing the path to a unix domain socket:1841.1842.IP "" 41843.1844.nf18451846app\.listen(\'/tmp/express\.sock\');1847.1848.fi1849.1850.IP "" 01851.1852.P1853Then try it out:1854.1855.IP "" 41856.1857.nf18581859$ telnet /tmp/express\.sock1860GET / HTTP/1\.118611862HTTP/1\.1 200 OK1863Content\-Type: text/plain1864Content\-Length: 1118651866Hello World1867.1868.fi1869.1870.IP "" 01871