guide.1
This file
Path
docs/guide.1
1,132 lines · 22.5 KiB
Last changed by
Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
History of this fileTake it
Started guideTj Holowaychukbefore adoption9e3a0c6
lines 1–5why, one step back1.\" generated with Ronn/v0.6.62.\" http://github.com/rtomayko/ronn/3.4.TH "GUIDE" "" "July 2010" "" ""5.Install docsTj Holowaychukbefore adoption63d02f1
line 6why, one step back6.SS "Installation"No "or similar" for curl installTj Holowaychukbefore adoption56a1dd9
line 7why, one step back7curl:Install docsTj Holowaychukbefore adoption63d02f1
lines 8–12why, one step back8.9.IP "" 410.11.nf12Updated curl install docsTj Holowaychukbefore adoption3ceb0de
line 13why, one step back13$ curl \-# http://expressjs\.com/install\.sh | shInstall docsTj Holowaychukbefore adoption63d02f1
lines 14–19why, one step back14.15.fi16.17.IP "" 018.19.PUpdated curl install docsTj Holowaychukbefore adoption3ceb0de
line 20why, one step back20npm:Install docsTj Holowaychukbefore adoption63d02f1
lines 21–25why, one step back21.22.IP "" 423.24.nf25Updated curl install docsTj Holowaychukbefore adoption3ceb0de
lines 26–27why, one step back26$ npm install connect27$ npm install expressInstall docsTj Holowaychukbefore adoption63d02f1
lines 28–33why, one step back28.29.fi30.31.IP "" 032.33.PUpdated install docsTj Holowaychukbefore adoption193c4a9
line 34why, one step back34git clone, first update the submodules:Install docsTj Holowaychukbefore adoption63d02f1
lines 35–39why, one step back35.36.IP "" 437.38.nf39Updated install docsTj Holowaychukbefore adoption193c4a9
line 40why, one step back40$ git submodule update \-\-initInstall docsTj Holowaychukbefore adoption63d02f1
line 41why, one step back41$ make installUpdated install docsTj Holowaychukbefore adoption193c4a9
line 42why, one step back42$ make install\-supportInstall docsTj Holowaychukbefore adoption63d02f1
lines 43–47why, one step back43.44.fi45.46.IP "" 047.Removed annoying padding transitionTj Holowaychukbefore adoption346b2a2
line 48why, one step back48.SS "Creating An Application"Moved config docs upTj Holowaychukbefore adoption6e8413f
line 49why, one step back49The \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\.Added configuration sectionTj Holowaychukbefore adoption83d2555
lines 50–66why, one step back50.51.IP "" 452.53.nf5455var app = require(\'express\')\.createServer();5657app\.get(\'/\', function(req, res){58 res\.send(\'hello world\');59});6061app\.listen(3000);62.63.fi64.65.IP "" 066.Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 67–70why, one step back67.SS "Configuration"68Express 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\.69.70.PUpdated configuration docsTj Holowaychukbefore adoptionf8ccaa3
line 71why, one step back71In 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\.Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 72–77why, one step back72.73.IP "" 474.75.nf7677app\.configure(function(){Updated docsTj Holowaychukbefore adoptioncacada8
lines 78–79why, one step back78 app\.use(connect\.methodOverride());79 app\.use(connect\.bodyDecoder());Updated configuration docsTj Holowaychukbefore adoptionf8ccaa3
lines 80–81why, one step back80 app\.use(app\.router);81 app\.use(connect\.staticProvider(__dirname + \'/public\'));Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 82–84why, one step back82});8384app\.configure(\'development\', function(){Updated docsTj Holowaychukbefore adoptioncacada8
line 85why, one step back85 app\.use(connect\.errorHandler({ dumpExceptions: true, showStack: true }));Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 86–88why, one step back86});8788app\.configure(\'production\', function(){Updated docsTj Holowaychukbefore adoptioncacada8
line 89why, one step back89 app\.use(connect\.errorHandler());Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 90–118why, one step back90});91.92.fi93.94.IP "" 095.96.P97For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:98.99.IP "" 4100.101.nf102103app\.configure(function(){104 app\.set(\'views\', __dirname + \'/views\');105 app\.set(\'views\');106 // => \"\.\.\. views directory \.\.\.\"107108 app\.enable(\'some feature\');109 // same as app\.set(\'some feature\', true);110111 app\.disable(\'some feature\');112 // same as app\.set(\'some feature\', false);113});114.115.fi116.117.IP "" 0118.More docsTj Holowaychukbefore adoptionde81ee7
lines 119–131why, one step back119.P120To alter the environment we can set the \fICONNECT_ENV\fR environment variable, or more specifically \fIEXPRESS_ENV\fR, for example:121.122.IP "" 4123.124.nf125126$ EXPRESS_ENV=production node app\.js127.128.fi129.130.IP "" 0131.Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 132–135why, one step back132.SS "Settings"133Express supports the following settings out of the box:134.135.IP "\(bu" 4Updated docsTj Holowaychukbefore adoption4d32762
line 136why, one step back136\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fRMore docsTj Holowaychukbefore adoptionde81ee7
lines 137–138why, one step back137.138.IP "\(bu" 4New "home" docsTj Holowaychukbefore adoption1e7a12f
line 139why, one step back139\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.More docsTj Holowaychukbefore adoptionbedff32
lines 140–141why, one step back140.141.IP "\(bu" 4Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 142–146why, one step back142\fIviews\fR Root views directory defaulting to \fBCWD/views\fR143.144.IP "\(bu" 4145\fIview engine\fR Default view engine name for views rendered without extensions146.Added more setting docsTj Holowaychukbefore adoption38281e6
line 147why, one step back147.IP "\(bu" 4Fixed reload views exampleTj Holowaychukbefore adoption5fcf971
line 148why, one step back148\fIreload views\fR Reloads altered views, by default watches for \fImtime\fR changes with with a 5 minute interval\. Example: \fIapp\.set(\'reload views\', 60000);\fRAdded more setting docsTj Holowaychukbefore adoption38281e6
line 149why, one step back149.Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 150–151why, one step back150.IP "" 0151.Started guideTj Holowaychukbefore adoption9e3a0c6
line 152why, one step back152.SS "Routing"Route passing docsTj Holowaychukbefore adoption0ace97c
line 153why, one step back153Express 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 passed as the \fIthird\fR argument, which here we name \fIparams\fR\.Started guideTj Holowaychukbefore adoption9e3a0c6
lines 154–180why, one step back154.155.IP "" 4156.157.nf158159app\.get(\'/user/:id\', function(req, res, params){160 res\.send(\'user \' + params\.id);161});162.163.fi164.165.IP "" 0166.167.P168A 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:169.170.IP "" 4171.172.nf173174\\/user\\/([^\\/]+)\\/?175.176.fi177.178.IP "" 0179.180.PUpdated docsTj Holowaychukbefore adoption0111582
line 181why, one step back181Regular expression literals may also be passed for complex uses\. Since capture groups with literal \fIRegExp\fR\'s are anonymous we can access them directly from the \fIparams\fR array\.Started guideTj Holowaychukbefore adoption9e3a0c6
lines 182–186why, one step back182.183.IP "" 4184.185.nf186Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
line 187why, one step back187app\.get(/^\\/users?(?:\\/(\\d+)(?:\\\.\\\.(\\d+))?)?/, function(req, res, params){Updated docsTj Holowaychukbefore adoption0111582
line 188why, one step back188 res\.send(params);Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
lines 189–209why, one step back189});190.191.fi192.193.IP "" 0194.195.P196Curl requests against the previously defined route:197.198.IP "" 4199.200.nf201202 $ curl http://dev:3000/user203 [null,null]204 $ curl http://dev:3000/users205 [null,null]206 $ curl http://dev:3000/users/1207 [\"1\",null]208 $ curl http://dev:3000/users/1\.\.15209 [\"1\",\"15\"]Started guideTj Holowaychukbefore adoption9e3a0c6
lines 210–248why, one step back210.211.fi212.213.IP "" 0214.215.P216Below are some route examples, and the associated paths that they may consume:217.218.IP "" 4219.220.nf221222 \"/user/:id\"223 /user/12224225 \"/users/:id?\"226 /users/5227 /users228229 \"/files/*\"230 /files/jquery\.js231 /files/javascripts/jquery\.js232233 \"/file/*\.*\"234 /files/jquery\.js235 /files/javascripts/jquery\.js236237 \"/user/:id/:operation?\"238 /user/1239 /user/1/edit240241 \"/products\.:format\"242 /products\.json243 /products\.xml244245 \"/products\.:format?\"246 /products\.json247 /products\.xml248 /productsRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 249–270why, one step back249.250.fi251.252.IP "" 0253.254.SS "Passing Route Control"255We may pass control to the next \fImatching\fR route, by calling the \fIfourth\fR parameter, the \fInext()\fR function\. When a match cannot be made, control is passed back to Connect\.256.257.IP "" 4258.259.nf260261app\.get(\'/users/:id?\', function(req, res, params){262 if (params\.id) {263 // do something264 } else {265 next();266 }267});268269app\.get(\'/users\', function(req, res, params){270 // do something elseAdded configuration sectionTj Holowaychukbefore adoption83d2555
lines 271–290why, one step back271});272.273.fi274.275.IP "" 0276.277.SS "Middleware"278The Express \fIPlugin\fR is no more! middleware via Connect \fIhttp://github\.com/extjs/Connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:279.280.IP "" 4281.282.nf283284var connect = require(\'connect\'),285 express = require(\'express\');286287var app = express\.createServer(288 connect\.logger(),289 connect\.bodyDecoder()290);More docsTj Holowaychukbefore adoptionbedff32
lines 291–295why, one step back291.292.fi293.294.IP "" 0295.Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 296–302why, one step back296.P297Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:298.299.IP "" 4300.301.nf302Updated docsTj Holowaychukbefore adoptioncacada8
line 303why, one step back303app\.use(connect\.logger({ format: \':method :uri\' }));Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 304–373why, one step back304.305.fi306.307.IP "" 0308.309.SS "Error Handling"310Express 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:311.312.IP "" 4313.314.nf315316function NotFound(msg){317 this\.name = \'NotFound\';318 Error\.call(this, msg);319 Error\.captureStackTrace(this, arguments\.callee);320}321322sys\.inherits(NotFound, Error);323324app\.get(\'/404\', function(req, res){325 throw new NotFound;326});327328app\.get(\'/500\', function(req, res){329 throw new Error(\'keyboard cat!\');330});331.332.fi333.334.IP "" 0335.336.P337We 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\.338.339.IP "" 4340.341.nf342343app\.error(function(err, req, res, next){344 if (err instanceof NotFound) {345 res\.render(\'404\.jade\');346 } else {347 next(err);348 }349});350.351.fi352.353.IP "" 0354.355.P356Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like357.358.IP "" 4359.360.nf361362app\.error(function(err, req, res){363 res\.render(\'500\.jade\', {364 locals: {365 error: err366 }367 });368});369.370.fi371.372.IP "" 0373.More error handling docsTj Holowaychukbefore adoptioncea401c
lines 374–380why, one step back374.P375Our 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:376.377.IP "" 4378.379.nf380Updated docsTj Holowaychukbefore adoptioncacada8
line 381why, one step back381app\.use(connect\.errorHandler({ dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 382–393why, one step back382.383.fi384.385.IP "" 0386.387.P388Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:389.390.IP "" 4391.392.nf393Updated docsTj Holowaychukbefore adoptioncacada8
line 394why, one step back394app\.use(connect\.errorHandler({ showStack: true, dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 395–402why, one step back395.396.fi397.398.IP "" 0399.400.P401The \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\.402.Added more view docsTj Holowaychukbefore adoption2f96506
lines 403–422why, one step back403.SS "View Rendering"404View 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 (currently) export the method \fIexports\.render(str, options)\fR to comply with Express, however with will likely be extensible in the future\.405.406.P407Below 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\.408.409.IP "" 4410.411.nf412413app\.get(\'/\', function(req, res){414 res\.render(\'index\.haml\', {415 locals: { title: \'My Site\' }416 });417});418.419.fi420.421.IP "" 0422.Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
lines 423–474why, one step back423.P424The 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:425.426.IP "" 4427.428.nf429430app\.set(\'view engine\', \'jade\');431.432.fi433.434.IP "" 0435.436.P437Allowing us to render with:438.439.IP "" 4440.441.nf442443res\.render(\'index\');444.445.fi446.447.IP "" 0448.449.P450vs:451.452.IP "" 4453.454.nf455456res\.render(\'index\.jade\');457.458.fi459.460.IP "" 0461.462.P463When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:464.465.IP "" 4466.467.nf468469res\.render(\'another\-page\.ejs\');470.471.fi472.473.IP "" 0474.Added more view docsTj Holowaychukbefore adoption2f96506
lines 475–513why, one step back475.SS "View Partials"476The 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:477.478.IP "" 4479.480.nf481482partial(\'comment\.haml\', { collection: comments });483.484.fi485.486.IP "" 0487.488.P489To 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\.490.491.IP "" 4492.493.nf494495partial(\'comment\', { collection: comments });496.497.fi498.499.IP "" 0500.501.P502And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:503.504.IP "" 4505.506.nf507508partial(\'comments\', comments);509.510.fi511.512.IP "" 0513.Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701
lines 514–527why, one step back514.P515When using the partial collection support a few \"magic\" variables are provided for free:516.517.IP "\(bu" 4518\fIfirstInCollection\fR True if this is the first object519.520.IP "\(bu" 4521\fIindexInCollection\fR Index of the object in the collection522.523.IP "\(bu" 4524_lastInCollection _ True if this is the last object525.526.IP "" 0527.Added more view docsTj Holowaychukbefore adoption2f96506
lines 528–541why, one step back528.SS "Template Engines"529Below are a few template engines commonly used with Express:530.531.IP "\(bu" 4532Jade \fIhttp://github\.com/visionmedia/jade\fR haml\.js successor533.534.IP "\(bu" 4535Haml \fIhttp://github\.com/visionmedia/haml\.js\fR indented templates536.537.IP "\(bu" 4538EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript539.540.IP "" 0541.More docsTj Holowaychukbefore adoptionde81ee7
line 542why, one step back542.SS "req\.header(key[, defaultValue])"More docsTj Holowaychukbefore adoptiondfecbe5
lines 543–556why, one step back543Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:544.545.IP "" 4546.547.nf548549req\.header(\'Host\');550req\.header(\'host\');551req\.header(\'Accept\', \'*/*\');552.553.fi554.555.IP "" 0556.More docsTj Holowaychukbefore adoptionde81ee7
line 557why, one step back557.SS "req\.accepts(type)"More docsTj Holowaychukbefore adoptiondfecbe5
lines 558–585why, one step back558Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.559.560.P561When 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\.562.563.IP "" 4564.565.nf566567// Accept: text/html568req\.accepts(\'html\');569// => true570571// Accept: text/*; application/json572req\.accepts(\'html\');573req\.accepts(\'text/html\');574req\.accepts(\'text/plain\');575req\.accepts(\'application/json\');576// => true577578req\.accepts(\'image/png\');579req\.accepts(\'png\');580// => false581.582.fi583.584.IP "" 0585.More docsTj Holowaychukbefore adoptionde81ee7
line 586why, one step back586.SS "req\.param(name)"More docsTj Holowaychukbefore adoptiondfecbe5
lines 587–602why, one step back587Return the value of param \fIname\fR when present\.588.589.IP "\(bu" 4590Checks route placeholders, ex: /user/:id591.592.IP "\(bu" 4593Checks query string params, ex: ?id=12594.595.IP "\(bu" 4596Checks urlencoded body params, ex: id=12597.598.IP "" 0599.600.P601To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIconnect\.bodyDecoder\fR middleware\.602.More docsTj Holowaychukbefore adoptionde81ee7
line 603why, one step back603.SS "req\.flash(type[, msg])"More docsTj Holowaychukbefore adoptiondfecbe5
lines 604–627why, one step back604Queue flash \fImsg\fR of the given \fItype\fR\.605.606.IP "" 4607.608.nf609610req\.flash(\'info\', \'email sent\');611req\.flash(\'error\', \'email delivery failed\');612req\.flash(\'info\', \'email re\-sent\');613// => 2614615req\.flash(\'info\');616// => [\'email sent\', \'email re\-sent\']617618req\.flash(\'info\');619// => []620621req\.flash();622// => { error: [\'email delivery failed\'], info: [] }623.624.fi625.626.IP "" 0627.More docsTj Holowaychukbefore adoptionde81ee7
line 628why, one step back628.SS "req\.isXMLHttpRequest"More docsTj Holowaychukbefore adoptiondfecbe5
lines 629–641why, one step back629Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:630.631.IP "" 4632.633.nf634635req\.xhr636req\.isXMLHttpRequest637.638.fi639.640.IP "" 0641.More docsTj Holowaychukbefore adoptionde81ee7
line 642why, one step back642.SS "res\.header(key[, val])"More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 643–661why, one step back643Get or set the response header \fIkey\fR\.644.645.IP "" 4646.647.nf648649res\.header(\'Content\-Length\');650// => undefined651652res\.header(\'Content\-Length\', 123);653// => 123654655res\.header(\'Content\-Length\');656// => 123657.658.fi659.660.IP "" 0661.More docsTj Holowaychukbefore adoptionde81ee7
line 662why, one step back662.SS "res\.contentType(type)"More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 663–676why, one step back663Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.664.665.IP "" 4666.667.nf668669 var filename = \'path/to/image\.png\';670 res\.contentType(filename);671 // res\.headers[\'Content\-Type\'] is now \"image/png\"672.673.fi674.675.IP "" 0676.More docsTj Holowaychukbefore adoptionde81ee7
line 677why, one step back677.SS "res\.attachment([filename])"Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
lines 678–689why, one step back678Sets the \fIContent\-Disposition\fR response header to \"attachment\", with optional \fIfilename\fR\.679.680.IP "" 4681.682.nf683684 res\.attachment(\'path/to/my/image\.png\');685.686.fi687.688.IP "" 0689.More docsTj Holowaychukbefore adoptionde81ee7
line 690why, one step back690.SS "res\.sendfile(path)"Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 691–703why, one step back691Used by \fBres\.download()\fR to transfer an arbitrary file\.692.693.IP "" 4694.695.nf696697res\.sendfile(\'path/to/my\.file\');698.699.fi700.701.IP "" 0702.703.PBetter docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1
line 704why, one step back704This is \fInot\fR a substitution for Connect\'s \fIstaticProvider\fR middleware, it does not support HTTP caching, and does not perform any security checks\. This method is utilized by \fIres\.download()\fR to transfer static files, and allows you do to so from outside of the public directory, so suitable security checks should be applied\.Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
line 705why, one step back705.More docsTj Holowaychukbefore adoptionde81ee7
line 706why, one step back706.SS "res\.download(file[, filename])"Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 707–733why, one step back707Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.708.709.IP "" 4710.711.nf712713res\.download(\'path/to/image\.png\');714res\.download(\'path/to/image\.png\', \'foo\.png\');715.716.fi717.718.IP "" 0719.720.P721This is equivalent to:722.723.IP "" 4724.725.nf726727res\.attachment(file);728res\.sendfile(file);729.730.fi731.732.IP "" 0733.More docsTj Holowaychukbefore adoptionde81ee7
line 734why, one step back734.SS "res\.send(body|status[, headers|status[, status]])"Docs for res.send()Tj Holowaychukbefore adoption5a48248
lines 735–754why, one step back735The \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:736.737.IP "" 4738.739.nf740741 res\.send(new Buffer(\'wahoo\'));742 res\.send({ some: \'json\' });743 res\.send(\'<p>some html</p>\');744 res\.send(\'Sorry, cant find that\', 404);745 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);746 res\.send(404);747.748.fi749.750.IP "" 0751.752.P753By 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\.754.More docsTj Holowaychukbefore adoptionde81ee7
line 755why, one step back755.SS "res\.redirect(url[, status])"More docsTj Holowaychukbefore adoptionbedff32
lines 756–774why, one step back756Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.757.758.IP "" 4759.760.nf761762res\.redirect(\'/\', 301);763res\.redirect(\'/account\');764res\.redirect(\'http://google\.com\');765res\.redirect(\'home\');766res\.redirect(\'back\');767.768.fi769.770.IP "" 0771.772.P773Express 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 \"/\"\.774.More view docsTj Holowaychukbefore adoption1c8ff48
lines 775–787why, one step back775.SS "res\.render(view[, options[, fn]])"776Render \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\.777.778.P779Most 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:780.781.IP "\(bu" 4782\fIcontext|scope\fR Template evaluation context (\fIthis\fR)783.784.IP "\(bu" 4785\fIlocals\fR Object containing local variables786.787.IP "\(bu" 4Cleaning up view docsTj Holowaychukbefore adoption25c8883
line 788why, one step back788\fIcache\fR Cache intermediate JavaScript in memory (the default in \fIproduction\fR mode)More view docsTj Holowaychukbefore adoption1c8ff48
lines 789–794why, one step back789.790.IP "\(bu" 4791\fIdebug\fR Output debugging information792.793.IP "" 0794.In depth partial docsTj Holowaychukbefore adoption793943f
lines 795–875why, one step back795.SS "res\.partial(view[, options])"796Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.797.798.IP "\(bu" 4799\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.800.801.IP "\(bu" 4802as: \'something\' will add the \fIsomething\fR local variable803.804.IP "\(bu" 4805as: this will use the collection value as the template context806.807.IP "\(bu" 4808as: global will merge the collection value\'s properties with \fIlocals\fR809.810.IP "" 0811812.813.IP "\(bu" 4814\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\.815.816.IP "" 0817.818.P819The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.820.821.IP "" 4822.823.nf824825partial(\'movie\.jade\', { collection: movies });826partial(\'movie\.jade\', movies);827partial(\'movie\', movies);828// In view: movie\.director829.830.fi831.832.IP "" 0833.834.P835To change the local from \fImovie\fR to \fIvideo\fR we can use the \"as\" option:836.837.IP "" 4838.839.nf840841partial(\'movie\', { collection: movies, as: \'video\' });842// In view: video\.director843.844.fi845.846.IP "" 0847.848.P849Also 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\.850.851.IP "" 4852.853.nf854855partial(\'movie\', { collection: movies, as: this });856// In view: this\.director857.858.fi859.860.IP "" 0861.862.P863Another 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:864.865.IP "" 4866.867.nf868869partials(\'movie\', { collection: movies, as: global });870// In view: director871.872.fi873.874.IP "" 0875.More docsTj Holowaychukbefore adoptionde81ee7
lines 876–940why, one step back876.SS "app\.set(name[, val])"877Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:878.879.IP "" 4880.881.nf882883app\.set(\'reload views\', 200);884app\.set(\'reload views\');885// => 200886.887.fi888.889.IP "" 0890.891.SS "app\.enable(name)"892Enable the given setting \fIname\fR:893.894.IP "" 4895.896.nf897898app\.enable(\'some arbitrary setting\');899app\.set(\'some arbitrary setting\');900// => true901.902.fi903.904.IP "" 0905.906.SS "app\.disable(name)"907Disable the given setting \fIname\fR:908.909.IP "" 4910.911.nf912913app\.disable(\'some setting\');914app\.set(\'some setting\');915// => false916.917.fi918.919.IP "" 0920.921.SS "app\.configure(env|function[, function])"922Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:923.924.IP "" 4925.926.nf927928app\.configure(function(){929 // executed for each env930});931932app\.configure(\'development\', function(){933 // executed for \'development\' only934});935.936.fi937.938.IP "" 0939.940.SS "app\.redirect(name, val)"More docsTj Holowaychukbefore adoptionbedff32
lines 941–982why, one step back941For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:942.943.IP "" 4944.945.nf946947app\.redirect(\'google\', \'http://google\.com\');948.949.fi950.951.IP "" 0952.953.P954Now in a route we may call:955.956.P957res\.redirect(\'google\');958.959.P960We may also map dynamic redirects:961.962.IP "" 4963.964.nf965966app\.redirect(\'comments\', function(req, res, params){967 return \'/post/\' + params\.id + \'/comments\';968});969.970.fi971.972.IP "" 0973.974.P975So 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\.976.977.IP "" 4978.979.nf980981app\.get(\'/post/:id\', function(req, res){982 res\.redirect(\'comments\');Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 983–989why, one step back983});984.985.fi986.987.IP "" 0988.989.SS "app\.error(function)"More error docsTj Holowaychukbefore adoption6227f5c
line 990why, one step back990Adds 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:Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 991–997why, one step back991.992.IP "" 4993.994.nf995996app\.error(function(err, req, res, next){997 res\.send(err\.message, 500);More docsTj Holowaychukbefore adoptionbedff32
line 998why, one step back998});Added configuration sectionTj Holowaychukbefore adoption83d2555
lines 999–1000why, one step back999.1000.fiConfiguration docsTj Holowaychukbefore adoptioncb04364
lines 1001–1002why, one step back1001.1002.IP "" 0Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 1003–1004why, one step back1003.1004.SS "app\.helpers(obj)"Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 1005why, one step back1005Registers static view helpers\.Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 1006–1011why, one step back1006.1007.IP "" 41008.1009.nf10101011app\.helpers({Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 1012–1041why, one step back1012 name: function(first, last){ return first + \', \' + last },1013 firstName: \'tj\',1014 lastName: \'holowaychuk\'1015});1016.1017.fi1018.1019.IP "" 01020.1021.P1022Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1023.1024.IP "" 41025.1026.nf10271028<%= name(firstName, lastName) %>1029.1030.fi1031.1032.IP "" 01033.1034.SS "app\.dynamicHelpers(obj)"1035Registers dynamic view helpers\. Dynamic view helpers are simply functions which accept \fIreq\fR, \fIres\fR, and \fIparams\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\.1036.1037.IP "" 41038.1039.nf10401041app\.dynamicHelpers({Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 1042–1051why, one step back1042 session: function(req, res, params){1043 return req\.session;1044 }1045});1046.1047.fi1048.1049.IP "" 01050.1051.PDocs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 1052–1058why, one step back1052All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1053.1054.IP "" 41055.1056.nf10571058<%= session\.name %>Rebuilt docsTj Holowaychukbefore adoptionba88e48
lines 1059–1079why, one step back1059.1060.fi1061.1062.IP "" 01063.1064.SS "app\.mounted(fn)"1065Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1066.1067.IP "" 41068.1069.nf10701071var app = express\.createServer(),1072 blog = express\.createServer();10731074blog\.mounted(function(parent){1075 // parent is app1076 // \"this\" is blog1077});10781079app\.use(blog);Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 1080–1083why, one step back1080.1081.fi1082.1083.IP "" 0Server#listen() docsTj Holowaychukbefore adoptionf3803c4
lines 1084–1098why, one step back1084.1085.SS "app\.listen([port[, host]])"1086Bind 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\.1087.1088.IP "" 41089.1090.nf10911092app\.listen();1093app\.listen(3000);1094app\.listen(3000, \'n\.n\.n\.n\');1095.1096.fi1097.1098.IP "" 0Unix domain socket docsTj Holowaychukbefore adoption2fa7907
lines 1099–1131why, one step back1099.1100.P1101The \fIport\fR argument may also be a string representing the path to a unix domain socket:1102.1103.IP "" 41104.1105.nf11061107app\.listen(\'/tmp/express\.sock\');1108.1109.fi1110.1111.IP "" 01112.1113.P1114Then try it out:1115.1116.IP "" 41117.1118.nf11191120$ telnet /tmp/express\.sock1121GET / HTTP/1\.111221123HTTP/1\.1 200 OK1124Content\-Type: text/plain1125Content\-Length: 1111261127Hello World1128.1129.fi1130.1131.IP "" 0Started guideTj Holowaychukbefore adoption9e3a0c6
line 1132why, one step back1132