guide.1
This file
Path
docs/guide.1
1,647 lines · 34.1 KiB
Last changed by
Regenerated docsTj Holowaychukbefore adoption0faac20
History of this fileTake it
1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "GUIDE" "" "October 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.SS "Settings"135Express supports the following settings out of the box:136.137.IP "\(bu" 4138\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR139.140.IP "\(bu" 4141\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.142.143.IP "\(bu" 4144\fIviews\fR Root views directory defaulting to \fBCWD/views\fR145.146.IP "\(bu" 4147\fIview engine\fR Default view engine name for views rendered without extensions148.149.IP "\(bu" 4150\fIview options\fR An object specifying global view options151.152.IP "\(bu" 4153\fIpartials\fR Root view partials directory defaulting to \fIviews\fR/partials\.154.155.IP "\(bu" 4156\fIstream threshold\fR Bytesize indicating when a file should be streamed for \fIres\.sendfile()\fR using \fIfs\.ReadStream()\fR and \fIsys\.pump()\fR\.157.158.IP "" 0159.160.SS "Routing"161Express 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\.162.163.IP "" 4164.165.nf166167app\.get(\'/user/:id\', function(req, res){168 res\.send(\'user \' + req\.params\.id);169});170.171.fi172.173.IP "" 0174.175.P176A 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:177.178.IP "" 4179.180.nf181182\e/user\e/([^\e/]+)\e/?183.184.fi185.186.IP "" 0187.188.P189Regular 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\.190.191.IP "" 4192.193.nf194195app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){196 res\.send(req\.params);197});198.199.fi200.201.IP "" 0202.203.P204Curl requests against the previously defined route:205.206.IP "" 4207.208.nf209210 $ curl http://dev:3000/user211 [null,null]212 $ curl http://dev:3000/users213 [null,null]214 $ curl http://dev:3000/users/1215 ["1",null]216 $ curl http://dev:3000/users/1\.\.15217 ["1","15"]218.219.fi220.221.IP "" 0222.223.P224Below are some route examples, and the associated paths that they may consume:225.226.IP "" 4227.228.nf229230 "/user/:id"231 /user/12232233 "/users/:id?"234 /users/5235 /users236237 "/files/*"238 /files/jquery\.js239 /files/javascripts/jquery\.js240241 "/file/*\.*"242 /files/jquery\.js243 /files/javascripts/jquery\.js244245 "/user/:id/:operation?"246 /user/1247 /user/1/edit248249 "/products\.:format"250 /products\.json251 /products\.xml252253 "/products\.:format?"254 /products\.json255 /products\.xml256 /products257.258.fi259.260.IP "" 0261.262.SS "Passing Route Control"263We 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\.264.265.IP "" 4266.267.nf268269app\.get(\'/users/:id?\', function(req, res, next){270 var id = req\.params\.id;271 if (id) {272 // do something273 } else {274 next();275 }276});277278app\.get(\'/users\', function(req, res){279 // do something else280});281.282.fi283.284.IP "" 0285.286.SS "Middleware"287Middleware 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:288.289.IP "" 4290.291.nf292293 var express = require(\'express\');294295var app = express\.createServer(296 express\.logger(),297 express\.bodyDecoder()298 );299.300.fi301.302.IP "" 0303.304.P305Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:306.307.IP "" 4308.309.nf310311app\.use(express\.logger({ format: \':method :uri\' }));312.313.fi314.315.IP "" 0316.317.P318Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:319.320.IP "" 4321.322.nf323324var connect = require(\'connect\');325app\.use(connect\.logger());326.327.fi328.329.IP "" 0330.331.P332This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:333.334.IP "" 4335.336.nf337338app\.use(express\.logger());339.340.fi341.342.IP "" 0343.344.SS "Route Middleware"345Routes 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\.346.347.P348Typically async data retrieval might look similar to below, where we take the \fI:id\fR parameter, and attempt loading a user\.349.350.IP "" 4351.352.nf353354app\.get(\'/user/:id\', function(req, res, next){355 loadUser(req\.params\.id, function(err, user){356 if (err) return next(err);357 res\.send(\'Viewing user \' + user\.name);358 });359});360.361.fi362.363.IP "" 0364.365.P366To 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\.367.368.IP "" 4369.370.nf371372function loadUser(req, res, next) {373 // You would fetch your user from the db374 var user = users[req\.params\.id];375 if (user) {376 req\.user = user;377 next();378 } else {379 next(new Error(\'Failed to load user \' + req\.params\.id));380 }381}382383app\.get(\'/user/:id\', loadUser, function(req, res){384 res\.send(\'Viewing user \' + req\.user\.name);385});386.387.fi388.389.IP "" 0390.391.P392Multiple 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\.393.394.IP "" 4395.396.nf397398function andRestrictToSelf(req, res, next) {399 req\.authenticatedUser\.id == req\.user\.id400 ? next()401 : next(new Error(\'Unauthorized\'));402}403404app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){405 res\.send(\'Editing user \' + req\.user\.name);406});407.408.fi409.410.IP "" 0411.412.P413Keeping 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\.414.415.IP "" 4416.417.nf418419function andRestrictTo(role) {420 return function(req, res, next) {421 req\.authenticatedUser\.role == role422 ? next()423 : next(new Error(\'Unauthorized\'));424 }425}426427app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){428 res\.send(\'Deleted user \' + req\.user\.name);429});430.431.fi432.433.IP "" 0434.435.P436Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.437.438.IP "" 4439.440.nf441442var a = [middleware1, middleware2]443 , b = [middleware3, middleware4]444 , all = [a, b];445446app\.get(\'/foo\', a, function(){});447app\.get(\'/bar\', a, function(){});448449app\.get(\'/\', a, middleware3, middleware4, function(){});450app\.get(\'/\', a, b, function(){});451app\.get(\'/\', all, function(){});452.453.fi454.455.IP "" 0456.457.P458For 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\.459.460.SS "HTTP Methods"461We 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\.462.463.P464A 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\.465.466.P467.468.IP "" 4469.470.nf471472 <input type="text" name="user[name]" />473 <input type="text" name="user[email]" />474 <input type="submit" value="Submit" />475.476.fi477.478.IP "" 0479.480.P481.482.P483By 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:484.485.IP "" 4486.487.nf488489app\.use(express\.bodyDecoder());490.491.fi492.493.IP "" 0494.495.P496Our 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\.497.498.IP "" 4499.500.nf501502app\.post(\'/\', function(req, res){503 console\.log(req\.body\.user);504 res\.redirect(\'back\');505});506.507.fi508.509.IP "" 0510.511.P512When 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\.513.514.IP "" 4515.516.nf517518app\.use(express\.bodyDecoder());519app\.use(express\.methodOverride());520.521.fi522.523.IP "" 0524.525.P526The 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:527.528.IP "" 4529.530.nf531532<form method="post" action="/">533 <input type="hidden" name="_method" value="put" />534 <input type="text" name="user[name]" />535 <input type="text" name="user[email]" />536 <input type="submit" value="Submit" />537</form>538539app\.put(\'/\', function(){540 console\.log(req\.body\.user);541 res\.redirect(\'back\');542});543.544.fi545.546.IP "" 0547.548.SS "Error Handling"549Express 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:550.551.IP "" 4552.553.nf554555function NotFound(msg){556 this\.name = \'NotFound\';557 Error\.call(this, msg);558 Error\.captureStackTrace(this, arguments\.callee);559}560561sys\.inherits(NotFound, Error);562563app\.get(\'/404\', function(req, res){564 throw new NotFound;565});566567app\.get(\'/500\', function(req, res){568 throw new Error(\'keyboard cat!\');569});570.571.fi572.573.IP "" 0574.575.P576We 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\.577.578.P579Note 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\.580.581.IP "" 4582.583.nf584585app\.error(function(err, req, res, next){586 if (err instanceof NotFound) {587 res\.render(\'404\.jade\');588 } else {589 next(err);590 }591});592.593.fi594.595.IP "" 0596.597.P598Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like599.600.IP "" 4601.602.nf603604app\.error(function(err, req, res){605 res\.render(\'500\.jade\', {606 locals: {607 error: err608 }609 });610});611.612.fi613.614.IP "" 0615.616.P617Our 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:618.619.IP "" 4620.621.nf622623app\.use(express\.errorHandler({ dumpExceptions: true }));624.625.fi626.627.IP "" 0628.629.P630Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:631.632.IP "" 4633.634.nf635636app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));637.638.fi639.640.IP "" 0641.642.P643The \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\.644.645.SS "View Rendering"646View 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\.647.648.P649Below 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\.650.651.IP "" 4652.653.nf654655app\.get(\'/\', function(req, res){656 res\.render(\'index\.haml\', {657 locals: { title: \'My Site\' }658 });659});660.661.fi662.663.IP "" 0664.665.P666The 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:667.668.IP "" 4669.670.nf671672app\.set(\'view engine\', \'jade\');673.674.fi675.676.IP "" 0677.678.P679Allowing us to render with:680.681.IP "" 4682.683.nf684685res\.render(\'index\');686.687.fi688.689.IP "" 0690.691.P692vs:693.694.IP "" 4695.696.nf697698res\.render(\'index\.jade\');699.700.fi701.702.IP "" 0703.704.P705When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:706.707.IP "" 4708.709.nf710711res\.render(\'another\-page\.ejs\');712.713.fi714.715.IP "" 0716.717.P718Express 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:719.720.IP "" 4721.722.nf723724app\.set(\'view options\', {725 layout: false726});727.728.fi729.730.IP "" 0731.732.P733Which can then be overridden within the \fBres\.render()\fR call if need be:734.735.IP "" 4736.737.nf738739res\.render(\'myview\.ejs\', { layout: true });740.741.fi742.743.IP "" 0744.745.P746When 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:747.748.IP "" 4749.750.nf751752res\.render(\'page\', { layout: \'mylayout\' });753.754.fi755.756.IP "" 0757.758.P759Otherwise we must specify the extension:760.761.IP "" 4762.763.nf764765res\.render(\'page\', { layout: \'mylayout\.jade\' });766.767.fi768.769.IP "" 0770.771.P772These paths may also be absolute:773.774.IP "" 4775.776.nf777778res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });779.780.fi781.782.IP "" 0783.784.P785A good example of this is specifying custom \fIejs\fR opening and closing tags:786.787.IP "" 4788.789.nf790791app\.set(\'view options\', {792 open: \'{{\',793 close: \'}}\'794});795.796.fi797.798.IP "" 0799.800.SS "View Partials"801The 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:802.803.IP "" 4804.805.nf806807partial(\'comment\.haml\', { collection: comments });808.809.fi810.811.IP "" 0812.813.P814To 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\.815.816.IP "" 4817.818.nf819820partial(\'comment\', { collection: comments });821.822.fi823.824.IP "" 0825.826.P827And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:828.829.IP "" 4830.831.nf832833partial(\'comments\', comments);834.835.fi836.837.IP "" 0838.839.P840When using the partial collection support a few "magic" variables are provided for free:841.842.IP "\(bu" 4843\fIfirstInCollection\fR True if this is the first object844.845.IP "\(bu" 4846\fIindexInCollection\fR Index of the object in the collection847.848.IP "\(bu" 4849\fIlastInCollection\fR True if this is the last object850.851.IP "" 0852.853.SS "Template Engines"854Below are a few template engines commonly used with Express:855.856.IP "\(bu" 4857Jade \fIhttp://jade\-lang\.com\fR haml\.js successor858.859.IP "\(bu" 4860Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates861.862.IP "\(bu" 4863EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript864.865.IP "" 0866.867.SS "Session Support"868Sessions 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\.869.870.IP "" 4871.872.nf873874app\.use(express\.cookieDecoder());875app\.use(express\.session());876.877.fi878.879.IP "" 0880.881.P882By 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:883.884.IP "" 4885.886.nf887888var RedisStore = require(\'connect\-redis\');889app\.use(express\.cookieDecoder());890app\.use(express\.session({ store: new RedisStore }));891.892.fi893.894.IP "" 0895.896.P897Now 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:898.899.IP "" 4900.901.nf902903var RedisStore = require(\'connect\-redis\');904app\.use(express\.cookieDecoder());905app\.use(express\.session({ store: new RedisStore }));906app\.use(express\.bodyDecoder());907908app\.post(\'/add\-to\-cart\', function(req, res){909 // Perhaps we posted several items with a form910 // (use the bodyDecoder() middleware for this)911 var items = req\.body\.items;912 req\.session\.items = items;913 res\.redirect(\'back\');914});915916app\.get(\'/add\-to\-cart\', function(req, res){917 // When redirected back to GET /add\-to\-cart918 // we could check req\.session\.items && req\.session\.items\.length919 // to print out a message920 if (req\.session\.items && req\.session\.items\.length) {921 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);922 }923 res\.render(\'shopping\-cart\');924});925.926.fi927.928.IP "" 0929.930.P931The \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\.932.933.SS "req\.header(key[, defaultValue])"934Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:935.936.IP "" 4937.938.nf939940req\.header(\'Host\');941req\.header(\'host\');942req\.header(\'Accept\', \'*/*\');943.944.fi945.946.IP "" 0947.948.SS "req\.accepts(type)"949Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.950.951.P952When 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\.953.954.IP "" 4955.956.nf957958// Accept: text/html959req\.accepts(\'html\');960// => true961962// Accept: text/*; application/json963req\.accepts(\'html\');964req\.accepts(\'text/html\');965req\.accepts(\'text/plain\');966req\.accepts(\'application/json\');967// => true968969req\.accepts(\'image/png\');970req\.accepts(\'png\');971// => false972.973.fi974.975.IP "" 0976.977.SS "req\.param(name)"978Return the value of param \fIname\fR when present\.979.980.IP "\(bu" 4981Checks route placeholders (\fIreq\.params\fR), ex: /user/:id982.983.IP "\(bu" 4984Checks query string params (\fIreq\.query\fR), ex: ?id=12985.986.IP "\(bu" 4987Checks urlencoded body params (\fIreq\.body\fR), ex: id=12988.989.IP "" 0990.991.P992To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.993.994.SS "req\.flash(type[, msg])"995Queue flash \fImsg\fR of the given \fItype\fR\.996.997.IP "" 4998.999.nf10001001req\.flash(\'info\', \'email sent\');1002req\.flash(\'error\', \'email delivery failed\');1003req\.flash(\'info\', \'email re\-sent\');1004// => 210051006req\.flash(\'info\');1007// => [\'email sent\', \'email re\-sent\']10081009req\.flash(\'info\');1010// => []10111012req\.flash();1013// => { error: [\'email delivery failed\'], info: [] }1014.1015.fi1016.1017.IP "" 01018.1019.P1020Flash notification message may also utilize formatters, by default only the %s string formatter is available:1021.1022.IP "" 41023.1024.nf10251026req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1027.1028.fi1029.1030.IP "" 01031.1032.SS "req\.isXMLHttpRequest"1033Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1034.1035.IP "" 41036.1037.nf10381039req\.xhr1040req\.isXMLHttpRequest1041.1042.fi1043.1044.IP "" 01045.1046.SS "res\.header(key[, val])"1047Get or set the response header \fIkey\fR\.1048.1049.IP "" 41050.1051.nf10521053res\.header(\'Content\-Length\');1054// => undefined10551056res\.header(\'Content\-Length\', 123);1057// => 12310581059res\.header(\'Content\-Length\');1060// => 1231061.1062.fi1063.1064.IP "" 01065.1066.SS "res\.contentType(type)"1067Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1068.1069.IP "" 41070.1071.nf10721073 var filename = \'path/to/image\.png\';1074 res\.contentType(filename);1075 // res\.headers[\'Content\-Type\'] is now "image/png"1076.1077.fi1078.1079.IP "" 01080.1081.SS "res\.attachment([filename])"1082Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1083.1084.IP "" 41085.1086.nf10871088 res\.attachment(\'path/to/my/image\.png\');1089.1090.fi1091.1092.IP "" 01093.1094.SS "res\.sendfile(path)"1095Used by \fBres\.download()\fR to transfer an arbitrary file\.1096.1097.IP "" 41098.1099.nf11001101res\.sendfile(\'path/to/my\.file\');1102.1103.fi1104.1105.IP "" 01106.1107.P1108This 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\.1109.1110.IP "" 41111.1112.nf11131114res\.sendfile(path, function(err, path){1115 if (err) {1116 // handle the error1117 } else {1118 console\.log(\'transferred %s\', path);1119 }1120});1121.1122.fi1123.1124.IP "" 01125.1126.P1127When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.1128.1129.SS "res\.download(file[, filename])"1130Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1131.1132.IP "" 41133.1134.nf11351136res\.download(\'path/to/image\.png\');1137res\.download(\'path/to/image\.png\', \'foo\.png\');1138.1139.fi1140.1141.IP "" 01142.1143.P1144This is equivalent to:1145.1146.IP "" 41147.1148.nf11491150res\.attachment(file);1151res\.sendfile(file);1152.1153.fi1154.1155.IP "" 01156.1157.SS "res\.send(body|status[, headers|status[, status]])"1158The \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:1159.1160.IP "" 41161.1162.nf11631164 res\.send(); // 2041165 res\.send(new Buffer(\'wahoo\'));1166 res\.send({ some: \'json\' });1167 res\.send(\'<p>some html</p>\');1168 res\.send(\'Sorry, cant find that\', 404);1169 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1170 res\.send(404);1171.1172.fi1173.1174.IP "" 01175.1176.P1177By 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\.1178.1179.SS "res\.redirect(url[, status])"1180Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1181.1182.IP "" 41183.1184.nf11851186res\.redirect(\'/\', 301);1187res\.redirect(\'/account\');1188res\.redirect(\'http://google\.com\');1189res\.redirect(\'home\');1190res\.redirect(\'back\');1191.1192.fi1193.1194.IP "" 01195.1196.P1197Express 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 "/"\.1198.1199.SS "res\.cookie(name, val[, options])"1200Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1201.1202.IP "" 41203.1204.nf12051206// "Remember me" for 15 minutes1207res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1208.1209.fi1210.1211.IP "" 01212.1213.P1214To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1215.1216.IP "" 41217.1218.nf12191220app\.use(express\.cookieDecoder());12211222app\.get(\'/\', function(req, res){1223 // use req\.cookies\.rememberme1224});1225.1226.fi1227.1228.IP "" 01229.1230.SS "res\.clearCookie(name)"1231Clear cookie \fIname\fR by setting "expires" far in the past\.1232.1233.IP "" 41234.1235.nf12361237res\.clearCookie(\'rememberme\');1238.1239.fi1240.1241.IP "" 01242.1243.SS "res\.render(view[, options[, fn]])"1244Render \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\.1245.1246.P1247Most 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:1248.1249.IP "\(bu" 41250\fIscope\fR Template evaluation context (value of \fIthis\fR)1251.1252.IP "\(bu" 41253\fIlocals\fR Object containing local variables1254.1255.IP "\(bu" 41256\fIdebug\fR Output debugging information1257.1258.IP "\(bu" 41259\fIstatus\fR Response status code, defaults to 2001260.1261.IP "\(bu" 41262\fIheaders\fR Response headers object1263.1264.IP "" 01265.1266.SS "res\.partial(view[, options])"1267Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1268.1269.IP "\(bu" 41270\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.1271.1272.IP "\(bu" 41273as: \'something\' will add the \fIsomething\fR local variable1274.1275.IP "\(bu" 41276as: this will use the collection value as the template context1277.1278.IP "\(bu" 41279as: global will merge the collection value\'s properties with \fIlocals\fR1280.1281.IP "" 012821283.1284.IP "\(bu" 41285\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\.1286.1287.IP "" 01288.1289.P1290The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1291.1292.IP "" 41293.1294.nf12951296partial(\'movie\.jade\', { collection: movies });1297partial(\'movie\.jade\', movies);1298partial(\'movie\', movies);1299// In view: movie\.director1300.1301.fi1302.1303.IP "" 01304.1305.P1306To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1307.1308.IP "" 41309.1310.nf13111312partial(\'movie\', { collection: movies, as: \'video\' });1313// In view: video\.director1314.1315.fi1316.1317.IP "" 01318.1319.P1320Also 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\.1321.1322.IP "" 41323.1324.nf13251326partial(\'movie\', { collection: movies, as: this });1327// In view: this\.director1328.1329.fi1330.1331.IP "" 01332.1333.P1334Another 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:1335.1336.IP "" 41337.1338.nf13391340partials(\'movie\', { collection: movies, as: global });1341// In view: director1342.1343.fi1344.1345.IP "" 01346.1347.SS "app\.set(name[, val])"1348Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1349.1350.IP "" 41351.1352.nf13531354app\.set(\'views\', __dirname + \'/views\');1355app\.set(\'views\');1356// => \.\.\.path\.\.\.1357.1358.fi1359.1360.IP "" 01361.1362.SS "app\.enable(name)"1363Enable the given setting \fIname\fR:1364.1365.IP "" 41366.1367.nf13681369app\.enable(\'some arbitrary setting\');1370app\.set(\'some arbitrary setting\');1371// => true1372.1373.fi1374.1375.IP "" 01376.1377.SS "app\.disable(name)"1378Disable the given setting \fIname\fR:1379.1380.IP "" 41381.1382.nf13831384app\.disable(\'some setting\');1385app\.set(\'some setting\');1386// => false1387.1388.fi1389.1390.IP "" 01391.1392.SS "app\.configure(env|function[, function])"1393Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1394.1395.IP "" 41396.1397.nf13981399app\.configure(function(){1400 // executed for each env1401});14021403app\.configure(\'development\', function(){1404 // executed for \'development\' only1405});1406.1407.fi1408.1409.IP "" 01410.1411.SS "app\.redirect(name, val)"1412For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1413.1414.IP "" 41415.1416.nf14171418app\.redirect(\'google\', \'http://google\.com\');1419.1420.fi1421.1422.IP "" 01423.1424.P1425Now in a route we may call:1426.1427.P1428res\.redirect(\'google\');1429.1430.P1431We may also map dynamic redirects:1432.1433.IP "" 41434.1435.nf14361437app\.redirect(\'comments\', function(req, res){1438 return \'/post/\' + req\.params\.id + \'/comments\';1439});1440.1441.fi1442.1443.IP "" 01444.1445.P1446So 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\.1447.1448.IP "" 41449.1450.nf14511452app\.get(\'/post/:id\', function(req, res){1453 res\.redirect(\'comments\');1454});1455.1456.fi1457.1458.IP "" 01459.1460.SS "app\.error(function)"1461Adds 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:1462.1463.IP "" 41464.1465.nf14661467app\.error(function(err, req, res, next){1468 res\.send(err\.message, 500);1469});1470.1471.fi1472.1473.IP "" 01474.1475.SS "app\.helpers(obj)"1476Registers static view helpers\.1477.1478.IP "" 41479.1480.nf14811482app\.helpers({1483 name: function(first, last){ return first + \', \' + last },1484 firstName: \'tj\',1485 lastName: \'holowaychuk\'1486});1487.1488.fi1489.1490.IP "" 01491.1492.P1493Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1494.1495.IP "" 41496.1497.nf14981499<%= name(firstName, lastName) %>1500.1501.fi1502.1503.IP "" 01504.1505.SS "app\.dynamicHelpers(obj)"1506Registers 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\.1507.1508.IP "" 41509.1510.nf15111512app\.dynamicHelpers({1513 session: function(req, res){1514 return req\.session;1515 }1516});1517.1518.fi1519.1520.IP "" 01521.1522.P1523All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1524.1525.IP "" 41526.1527.nf15281529<%= session\.name %>1530.1531.fi1532.1533.IP "" 01534.1535.SS "app\.mounted(fn)"1536Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1537.1538.IP "" 41539.1540.nf15411542var app = express\.createServer(),1543 blog = express\.createServer();15441545blog\.mounted(function(parent){1546 // parent is app1547 // "this" is blog1548});15491550app\.use(blog);1551.1552.fi1553.1554.IP "" 01555.1556.SS "app\.register(ext, exports)"1557Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:1558.1559.IP "" 41560.1561.nf15621563 app\.register(\'\.html\', require(\'jade\'));1564.1565.fi1566.1567.IP "" 01568.1569.P1570This 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":1571.1572.IP "" 41573.1574.nf15751576 app\.register(\'\.haml\', require(\'haml\-js\'));1577.1578.fi1579.1580.IP "" 01581.1582.P1583For engines that do not comply with the Express specification, we can also wrap their api this way\.1584.1585.IP "" 41586.1587.nf15881589 app\.register(\'\.foo\', {1590 render: function(str, options) {1591 // perhaps their api is1592 // foo\.toHTML(str, options);1593 }1594 });1595.1596.fi1597.1598.IP "" 01599.1600.SS "app\.listen([port[, host]])"1601Bind 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\.1602.1603.IP "" 41604.1605.nf16061607app\.listen();1608app\.listen(3000);1609app\.listen(3000, \'n\.n\.n\.n\');1610.1611.fi1612.1613.IP "" 01614.1615.P1616The \fIport\fR argument may also be a string representing the path to a unix domain socket:1617.1618.IP "" 41619.1620.nf16211622app\.listen(\'/tmp/express\.sock\');1623.1624.fi1625.1626.IP "" 01627.1628.P1629Then try it out:1630.1631.IP "" 41632.1633.nf16341635$ telnet /tmp/express\.sock1636GET / HTTP/1\.116371638HTTP/1\.1 200 OK1639Content\-Type: text/plain1640Content\-Length: 1116411642Hello World1643.1644.fi1645.1646.IP "" 01647