guide.1
This file
Path
docs/guide.1
1,700 lines · 34.2 KiB
Last changed by
Regenerated docsTj Holowaychukbefore adoption090debe
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 ":id" parameter, and attempt loading a user\.349.350.P351app\.get(\'/user/:id\', function(req, res, next){352.353.IP "" 4354.355.nf356357 loadUser(req\.params\.id, function(err, user){358 if (err) return next(err);359 res\.send(\'Viewing user \' + user\.name);360 });361.362.fi363.364.IP "" 0365.366.P367});368.369.P370To 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\.371.372.P373function loadUser(req, res, next) {374.375.IP "" 4376.377.nf378379 // You would fetch your user from the db380 var user = users[req\.params\.id];381 if (user) {382 req\.user = user;383 next();384 } else {385 next(new Error(\'Failed to load user \' + req\.params\.id));386 }387.388.fi389.390.IP "" 0391.392.P393}394.395.P396app\.get(\'/user/:id\', loadUser, function(req, res){397.398.IP "" 4399.400.nf401402 res\.send(\'Viewing user \' + req\.user\.name);403.404.fi405.406.IP "" 0407.408.P409});410.411.P412Multiple 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\.413.414.P415function andRestrictToSelf(req, res, next) {416.417.IP "" 4418.419.nf420421 req\.authenticatedUser\.id == req\.user\.id422 ? next()423 : next(new Error(\'Unauthorized\'));424.425.fi426.427.IP "" 0428.429.P430}431.432.P433app\.get(\'/user/:id/edit\', loadUser, andRestrictToSelf, function(req, res){434.435.IP "" 4436.437.nf438439 res\.send(\'Editing user \' + req\.user\.name);440.441.fi442.443.IP "" 0444.445.P446});447.448.P449Keeping 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\.450.451.P452function andRestrictTo(role) {453.454.IP "" 4455.456.nf457458 return function(req, res, next) {459 req\.authenticatedUser\.role == role460 ? next()461 : next(new Error(\'Unauthorized\'));462 }463.464.fi465.466.IP "" 0467.468.P469}470.471.P472app\.del(\'/user/:id\', loadUser, andRestrictTo(\'admin\'), function(req, res){473.474.IP "" 4475.476.nf477478 res\.send(\'Deleted user \' + req\.user\.name);479.480.fi481.482.IP "" 0483.484.P485});486.487.P488Commonly used "stacks" of middleware can be passed as an array (\fIapplied recursively\fR), which can be mixed and matched to any degree\.489.490.P491var a = [middleware1, middleware2]492.493.IP "" 4494.495.nf496497, b = [middleware3, middleware4]498, all = [a, b];499.500.fi501.502.IP "" 0503.504.P505app\.get(\'/foo\', a, function(){}); app\.get(\'/bar\', a, function(){});506.507.P508app\.get(\'/\', a, middleware3, middleware4, function(){}); app\.get(\'/\', a, b, function(){}); app\.get(\'/\', all, function(){});509.510.P511For this example in full, view the route middleware example \fIhttp://github\.com/visionmedia/express/blob/master/examples/route\-middleware/app\.js\fR in the repository\.512.513.SS "HTTP Methods"514We have seen \fIapp\.get()\fR a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as \fIapp\.post()\fR, \fIapp\.del()\fR, etc\.515.516.P517A common example for \fIPOST\fR usage, is when "submitting" a form\. Below we simply set our form method to "post" in our html, and control will be given to the route we have defined below it\.518.519.P520.521.IP "" 4522.523.nf524525 <input type="text" name="user[name]" />526 <input type="text" name="user[email]" />527 <input type="submit" value="Submit" />528.529.fi530.531.IP "" 0532.533.P534.535.P536By 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:537.538.IP "" 4539.540.nf541542app\.use(express\.bodyDecoder());543.544.fi545.546.IP "" 0547.548.P549Our 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\.550.551.IP "" 4552.553.nf554555app\.post(\'/\', function(req, res){556 console\.log(req\.body\.user);557 res\.redirect(\'back\');558});559.560.fi561.562.IP "" 0563.564.P565When 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\.566.567.IP "" 4568.569.nf570571app\.use(express\.bodyDecoder());572app\.use(express\.methodOverride());573.574.fi575.576.IP "" 0577.578.P579The 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:580.581.IP "" 4582.583.nf584585<form method="post" action="/">586 <input type="hidden" name="_method" value="put" />587 <input type="text" name="user[name]" />588 <input type="text" name="user[email]" />589 <input type="submit" value="Submit" />590</form>591592app\.put(\'/\', function(){593 console\.log(req\.body\.user);594 res\.redirect(\'back\');595});596.597.fi598.599.IP "" 0600.601.SS "Error Handling"602Express 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:603.604.IP "" 4605.606.nf607608function NotFound(msg){609 this\.name = \'NotFound\';610 Error\.call(this, msg);611 Error\.captureStackTrace(this, arguments\.callee);612}613614sys\.inherits(NotFound, Error);615616app\.get(\'/404\', function(req, res){617 throw new NotFound;618});619620app\.get(\'/500\', function(req, res){621 throw new Error(\'keyboard cat!\');622});623.624.fi625.626.IP "" 0627.628.P629We 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\.630.631.P632Note 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\.633.634.IP "" 4635.636.nf637638app\.error(function(err, req, res, next){639 if (err instanceof NotFound) {640 res\.render(\'404\.jade\');641 } else {642 next(err);643 }644});645.646.fi647.648.IP "" 0649.650.P651Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like652.653.IP "" 4654.655.nf656657app\.error(function(err, req, res){658 res\.render(\'500\.jade\', {659 locals: {660 error: err661 }662 });663});664.665.fi666.667.IP "" 0668.669.P670Our 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:671.672.IP "" 4673.674.nf675676app\.use(express\.errorHandler({ dumpExceptions: true }));677.678.fi679.680.IP "" 0681.682.P683Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:684.685.IP "" 4686.687.nf688689app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));690.691.fi692.693.IP "" 0694.695.P696The \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\.697.698.SS "View Rendering"699View 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\.700.701.P702Below 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\.703.704.IP "" 4705.706.nf707708app\.get(\'/\', function(req, res){709 res\.render(\'index\.haml\', {710 locals: { title: \'My Site\' }711 });712});713.714.fi715.716.IP "" 0717.718.P719The 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:720.721.IP "" 4722.723.nf724725app\.set(\'view engine\', \'jade\');726.727.fi728.729.IP "" 0730.731.P732Allowing us to render with:733.734.IP "" 4735.736.nf737738res\.render(\'index\');739.740.fi741.742.IP "" 0743.744.P745vs:746.747.IP "" 4748.749.nf750751res\.render(\'index\.jade\');752.753.fi754.755.IP "" 0756.757.P758When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:759.760.IP "" 4761.762.nf763764res\.render(\'another\-page\.ejs\');765.766.fi767.768.IP "" 0769.770.P771Express 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:772.773.IP "" 4774.775.nf776777app\.set(\'view options\', {778 layout: false779});780.781.fi782.783.IP "" 0784.785.P786Which can then be overridden within the \fBres\.render()\fR call if need be:787.788.IP "" 4789.790.nf791792res\.render(\'myview\.ejs\', { layout: true });793.794.fi795.796.IP "" 0797.798.P799When 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:800.801.IP "" 4802.803.nf804805res\.render(\'page\', { layout: \'mylayout\' });806.807.fi808.809.IP "" 0810.811.P812Otherwise we must specify the extension:813.814.IP "" 4815.816.nf817818res\.render(\'page\', { layout: \'mylayout\.jade\' });819.820.fi821.822.IP "" 0823.824.P825These paths may also be absolute:826.827.IP "" 4828.829.nf830831res\.render(\'page\', { layout: __dirname + \'/\.\./\.\./mylayout\.jade\' });832.833.fi834.835.IP "" 0836.837.P838A good example of this is specifying custom \fIejs\fR opening and closing tags:839.840.IP "" 4841.842.nf843844app\.set(\'view options\', {845 open: \'{{\',846 close: \'}}\'847});848.849.fi850.851.IP "" 0852.853.SS "View Partials"854The 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:855.856.IP "" 4857.858.nf859860partial(\'comment\.haml\', { collection: comments });861.862.fi863.864.IP "" 0865.866.P867To 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\.868.869.IP "" 4870.871.nf872873partial(\'comment\', { collection: comments });874.875.fi876.877.IP "" 0878.879.P880And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:881.882.IP "" 4883.884.nf885886partial(\'comments\', comments);887.888.fi889.890.IP "" 0891.892.P893When using the partial collection support a few "magic" variables are provided for free:894.895.IP "\(bu" 4896\fIfirstInCollection\fR True if this is the first object897.898.IP "\(bu" 4899\fIindexInCollection\fR Index of the object in the collection900.901.IP "\(bu" 4902\fIlastInCollection\fR True if this is the last object903.904.IP "" 0905.906.SS "Template Engines"907Below are a few template engines commonly used with Express:908.909.IP "\(bu" 4910Jade \fIhttp://jade\-lang\.com\fR haml\.js successor911.912.IP "\(bu" 4913Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates914.915.IP "\(bu" 4916EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript917.918.IP "" 0919.920.SS "Session Support"921Sessions 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\.922.923.IP "" 4924.925.nf926927app\.use(express\.cookieDecoder());928app\.use(express\.session());929.930.fi931.932.IP "" 0933.934.P935By 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:936.937.IP "" 4938.939.nf940941var RedisStore = require(\'connect\-redis\');942app\.use(express\.cookieDecoder());943app\.use(express\.session({ store: new RedisStore }));944.945.fi946.947.IP "" 0948.949.P950Now 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:951.952.IP "" 4953.954.nf955956var RedisStore = require(\'connect\-redis\');957app\.use(express\.cookieDecoder());958app\.use(express\.session({ store: new RedisStore }));959app\.use(express\.bodyDecoder());960961app\.post(\'/add\-to\-cart\', function(req, res){962 // Perhaps we posted several items with a form963 // (use the bodyDecoder() middleware for this)964 var items = req\.body\.items;965 req\.session\.items = items;966 res\.redirect(\'back\');967});968969app\.get(\'/add\-to\-cart\', function(req, res){970 // When redirected back to GET /add\-to\-cart971 // we could check req\.session\.items && req\.session\.items\.length972 // to print out a message973 if (req\.session\.items && req\.session\.items\.length) {974 req\.flash(\'info\', \'You have %s items in your cart\', req\.session\.items\.length);975 }976 res\.render(\'shopping\-cart\');977});978.979.fi980.981.IP "" 0982.983.P984The \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\.985.986.SS "req\.header(key[, defaultValue])"987Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:988.989.IP "" 4990.991.nf992993req\.header(\'Host\');994req\.header(\'host\');995req\.header(\'Accept\', \'*/*\');996.997.fi998.999.IP "" 01000.1001.SS "req\.accepts(type)"1002Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1003.1004.P1005When 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\.1006.1007.IP "" 41008.1009.nf10101011// Accept: text/html1012req\.accepts(\'html\');1013// => true10141015// Accept: text/*; application/json1016req\.accepts(\'html\');1017req\.accepts(\'text/html\');1018req\.accepts(\'text/plain\');1019req\.accepts(\'application/json\');1020// => true10211022req\.accepts(\'image/png\');1023req\.accepts(\'png\');1024// => false1025.1026.fi1027.1028.IP "" 01029.1030.SS "req\.param(name)"1031Return the value of param \fIname\fR when present\.1032.1033.IP "\(bu" 41034Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1035.1036.IP "\(bu" 41037Checks query string params (\fIreq\.query\fR), ex: ?id=121038.1039.IP "\(bu" 41040Checks urlencoded body params (\fIreq\.body\fR), ex: id=121041.1042.IP "" 01043.1044.P1045To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.1046.1047.SS "req\.flash(type[, msg])"1048Queue flash \fImsg\fR of the given \fItype\fR\.1049.1050.IP "" 41051.1052.nf10531054req\.flash(\'info\', \'email sent\');1055req\.flash(\'error\', \'email delivery failed\');1056req\.flash(\'info\', \'email re\-sent\');1057// => 210581059req\.flash(\'info\');1060// => [\'email sent\', \'email re\-sent\']10611062req\.flash(\'info\');1063// => []10641065req\.flash();1066// => { error: [\'email delivery failed\'], info: [] }1067.1068.fi1069.1070.IP "" 01071.1072.P1073Flash notification message may also utilize formatters, by default only the %s string formatter is available:1074.1075.IP "" 41076.1077.nf10781079req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);1080.1081.fi1082.1083.IP "" 01084.1085.SS "req\.isXMLHttpRequest"1086Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:1087.1088.IP "" 41089.1090.nf10911092req\.xhr1093req\.isXMLHttpRequest1094.1095.fi1096.1097.IP "" 01098.1099.SS "res\.header(key[, val])"1100Get or set the response header \fIkey\fR\.1101.1102.IP "" 41103.1104.nf11051106res\.header(\'Content\-Length\');1107// => undefined11081109res\.header(\'Content\-Length\', 123);1110// => 12311111112res\.header(\'Content\-Length\');1113// => 1231114.1115.fi1116.1117.IP "" 01118.1119.SS "res\.contentType(type)"1120Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.1121.1122.IP "" 41123.1124.nf11251126 var filename = \'path/to/image\.png\';1127 res\.contentType(filename);1128 // res\.headers[\'Content\-Type\'] is now "image/png"1129.1130.fi1131.1132.IP "" 01133.1134.SS "res\.attachment([filename])"1135Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.1136.1137.IP "" 41138.1139.nf11401141 res\.attachment(\'path/to/my/image\.png\');1142.1143.fi1144.1145.IP "" 01146.1147.SS "res\.sendfile(path)"1148Used by \fBres\.download()\fR to transfer an arbitrary file\.1149.1150.IP "" 41151.1152.nf11531154res\.sendfile(\'path/to/my\.file\');1155.1156.fi1157.1158.IP "" 01159.1160.P1161This 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\.1162.1163.IP "" 41164.1165.nf11661167res\.sendfile(path, function(err, path){1168 if (err) {1169 // handle the error1170 } else {1171 console\.log(\'transferred %s\', path);1172 }1173});1174.1175.fi1176.1177.IP "" 01178.1179.P1180When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.1181.1182.SS "res\.download(file[, filename])"1183Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1184.1185.IP "" 41186.1187.nf11881189res\.download(\'path/to/image\.png\');1190res\.download(\'path/to/image\.png\', \'foo\.png\');1191.1192.fi1193.1194.IP "" 01195.1196.P1197This is equivalent to:1198.1199.IP "" 41200.1201.nf12021203res\.attachment(file);1204res\.sendfile(file);1205.1206.fi1207.1208.IP "" 01209.1210.SS "res\.send(body|status[, headers|status[, status]])"1211The \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:1212.1213.IP "" 41214.1215.nf12161217 res\.send(); // 2041218 res\.send(new Buffer(\'wahoo\'));1219 res\.send({ some: \'json\' });1220 res\.send(\'<p>some html</p>\');1221 res\.send(\'Sorry, cant find that\', 404);1222 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);1223 res\.send(404);1224.1225.fi1226.1227.IP "" 01228.1229.P1230By 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\.1231.1232.SS "res\.redirect(url[, status])"1233Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1234.1235.IP "" 41236.1237.nf12381239res\.redirect(\'/\', 301);1240res\.redirect(\'/account\');1241res\.redirect(\'http://google\.com\');1242res\.redirect(\'home\');1243res\.redirect(\'back\');1244.1245.fi1246.1247.IP "" 01248.1249.P1250Express 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 "/"\.1251.1252.SS "res\.cookie(name, val[, options])"1253Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1254.1255.IP "" 41256.1257.nf12581259// "Remember me" for 15 minutes1260res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });1261.1262.fi1263.1264.IP "" 01265.1266.P1267To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:1268.1269.IP "" 41270.1271.nf12721273app\.use(express\.cookieDecoder());12741275app\.get(\'/\', function(req, res){1276 // use req\.cookies\.rememberme1277});1278.1279.fi1280.1281.IP "" 01282.1283.SS "res\.clearCookie(name)"1284Clear cookie \fIname\fR by setting "expires" far in the past\.1285.1286.IP "" 41287.1288.nf12891290res\.clearCookie(\'rememberme\');1291.1292.fi1293.1294.IP "" 01295.1296.SS "res\.render(view[, options[, fn]])"1297Render \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\.1298.1299.P1300Most 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:1301.1302.IP "\(bu" 41303\fIscope\fR Template evaluation context (value of \fIthis\fR)1304.1305.IP "\(bu" 41306\fIlocals\fR Object containing local variables1307.1308.IP "\(bu" 41309\fIdebug\fR Output debugging information1310.1311.IP "\(bu" 41312\fIstatus\fR Response status code, defaults to 2001313.1314.IP "\(bu" 41315\fIheaders\fR Response headers object1316.1317.IP "" 01318.1319.SS "res\.partial(view[, options])"1320Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.1321.1322.IP "\(bu" 41323\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.1324.1325.IP "\(bu" 41326as: \'something\' will add the \fIsomething\fR local variable1327.1328.IP "\(bu" 41329as: this will use the collection value as the template context1330.1331.IP "\(bu" 41332as: global will merge the collection value\'s properties with \fIlocals\fR1333.1334.IP "" 013351336.1337.IP "\(bu" 41338\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\.1339.1340.IP "" 01341.1342.P1343The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.1344.1345.IP "" 41346.1347.nf13481349partial(\'movie\.jade\', { collection: movies });1350partial(\'movie\.jade\', movies);1351partial(\'movie\', movies);1352// In view: movie\.director1353.1354.fi1355.1356.IP "" 01357.1358.P1359To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:1360.1361.IP "" 41362.1363.nf13641365partial(\'movie\', { collection: movies, as: \'video\' });1366// In view: video\.director1367.1368.fi1369.1370.IP "" 01371.1372.P1373Also 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\.1374.1375.IP "" 41376.1377.nf13781379partial(\'movie\', { collection: movies, as: this });1380// In view: this\.director1381.1382.fi1383.1384.IP "" 01385.1386.P1387Another 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:1388.1389.IP "" 41390.1391.nf13921393partials(\'movie\', { collection: movies, as: global });1394// In view: director1395.1396.fi1397.1398.IP "" 01399.1400.SS "app\.set(name[, val])"1401Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1402.1403.IP "" 41404.1405.nf14061407app\.set(\'views\', __dirname + \'/views\');1408app\.set(\'views\');1409// => \.\.\.path\.\.\.1410.1411.fi1412.1413.IP "" 01414.1415.SS "app\.enable(name)"1416Enable the given setting \fIname\fR:1417.1418.IP "" 41419.1420.nf14211422app\.enable(\'some arbitrary setting\');1423app\.set(\'some arbitrary setting\');1424// => true1425.1426.fi1427.1428.IP "" 01429.1430.SS "app\.disable(name)"1431Disable the given setting \fIname\fR:1432.1433.IP "" 41434.1435.nf14361437app\.disable(\'some setting\');1438app\.set(\'some setting\');1439// => false1440.1441.fi1442.1443.IP "" 01444.1445.SS "app\.configure(env|function[, function])"1446Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1447.1448.IP "" 41449.1450.nf14511452app\.configure(function(){1453 // executed for each env1454});14551456app\.configure(\'development\', function(){1457 // executed for \'development\' only1458});1459.1460.fi1461.1462.IP "" 01463.1464.SS "app\.redirect(name, val)"1465For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1466.1467.IP "" 41468.1469.nf14701471app\.redirect(\'google\', \'http://google\.com\');1472.1473.fi1474.1475.IP "" 01476.1477.P1478Now in a route we may call:1479.1480.P1481res\.redirect(\'google\');1482.1483.P1484We may also map dynamic redirects:1485.1486.IP "" 41487.1488.nf14891490app\.redirect(\'comments\', function(req, res){1491 return \'/post/\' + req\.params\.id + \'/comments\';1492});1493.1494.fi1495.1496.IP "" 01497.1498.P1499So 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\.1500.1501.IP "" 41502.1503.nf15041505app\.get(\'/post/:id\', function(req, res){1506 res\.redirect(\'comments\');1507});1508.1509.fi1510.1511.IP "" 01512.1513.SS "app\.error(function)"1514Adds 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:1515.1516.IP "" 41517.1518.nf15191520app\.error(function(err, req, res, next){1521 res\.send(err\.message, 500);1522});1523.1524.fi1525.1526.IP "" 01527.1528.SS "app\.helpers(obj)"1529Registers static view helpers\.1530.1531.IP "" 41532.1533.nf15341535app\.helpers({1536 name: function(first, last){ return first + \', \' + last },1537 firstName: \'tj\',1538 lastName: \'holowaychuk\'1539});1540.1541.fi1542.1543.IP "" 01544.1545.P1546Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1547.1548.IP "" 41549.1550.nf15511552<%= name(firstName, lastName) %>1553.1554.fi1555.1556.IP "" 01557.1558.SS "app\.dynamicHelpers(obj)"1559Registers 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\.1560.1561.IP "" 41562.1563.nf15641565app\.dynamicHelpers({1566 session: function(req, res){1567 return req\.session;1568 }1569});1570.1571.fi1572.1573.IP "" 01574.1575.P1576All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1577.1578.IP "" 41579.1580.nf15811582<%= session\.name %>1583.1584.fi1585.1586.IP "" 01587.1588.SS "app\.mounted(fn)"1589Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1590.1591.IP "" 41592.1593.nf15941595var app = express\.createServer(),1596 blog = express\.createServer();15971598blog\.mounted(function(parent){1599 // parent is app1600 // "this" is blog1601});16021603app\.use(blog);1604.1605.fi1606.1607.IP "" 01608.1609.SS "app\.register(ext, exports)"1610Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:1611.1612.IP "" 41613.1614.nf16151616 app\.register(\'\.html\', require(\'jade\'));1617.1618.fi1619.1620.IP "" 01621.1622.P1623This 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":1624.1625.IP "" 41626.1627.nf16281629 app\.register(\'\.haml\', require(\'haml\-js\'));1630.1631.fi1632.1633.IP "" 01634.1635.P1636For engines that do not comply with the Express specification, we can also wrap their api this way\.1637.1638.IP "" 41639.1640.nf16411642 app\.register(\'\.foo\', {1643 render: function(str, options) {1644 // perhaps their api is1645 // foo\.toHTML(str, options);1646 }1647 });1648.1649.fi1650.1651.IP "" 01652.1653.SS "app\.listen([port[, host]])"1654Bind 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\.1655.1656.IP "" 41657.1658.nf16591660app\.listen();1661app\.listen(3000);1662app\.listen(3000, \'n\.n\.n\.n\');1663.1664.fi1665.1666.IP "" 01667.1668.P1669The \fIport\fR argument may also be a string representing the path to a unix domain socket:1670.1671.IP "" 41672.1673.nf16741675app\.listen(\'/tmp/express\.sock\');1676.1677.fi1678.1679.IP "" 01680.1681.P1682Then try it out:1683.1684.IP "" 41685.1686.nf16871688$ telnet /tmp/express\.sock1689GET / HTTP/1\.116901691HTTP/1\.1 200 OK1692Content\-Type: text/plain1693Content\-Length: 1116941695Hello World1696.1697.fi1698.1699.IP "" 01700