guide.1
This file
Path
docs/guide.1
1,109 lines · 22.0 KiB
Last changed by
Updated docsTj Holowaychukbefore adoption0111582
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"Updated curl install docsTj Holowaychukbefore adoption3ceb0de
line 7why, one step back7curl (or similar):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–77why, 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.P71In 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\.72.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());Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 80–82why, one step back80});8182app\.configure(\'development\', function(){Updated docsTj Holowaychukbefore adoptioncacada8
line 83why, one step back83 app\.use(connect\.errorHandler({ dumpExceptions: true, showStack: true }));Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 84–86why, one step back84});8586app\.configure(\'production\', function(){Updated docsTj Holowaychukbefore adoptioncacada8
line 87why, one step back87 app\.use(connect\.errorHandler());Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 88–116why, one step back88});89.90.fi91.92.IP "" 093.94.P95For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:96.97.IP "" 498.99.nf100101app\.configure(function(){102 app\.set(\'views\', __dirname + \'/views\');103 app\.set(\'views\');104 // => \"\.\.\. views directory \.\.\.\"105106 app\.enable(\'some feature\');107 // same as app\.set(\'some feature\', true);108109 app\.disable(\'some feature\');110 // same as app\.set(\'some feature\', false);111});112.113.fi114.115.IP "" 0116.More docsTj Holowaychukbefore adoptionde81ee7
lines 117–129why, one step back117.P118To alter the environment we can set the \fICONNECT_ENV\fR environment variable, or more specifically \fIEXPRESS_ENV\fR, for example:119.120.IP "" 4121.122.nf123124$ EXPRESS_ENV=production node app\.js125.126.fi127.128.IP "" 0129.Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 130–133why, one step back130.SS "Settings"131Express supports the following settings out of the box:132.133.IP "\(bu" 4Updated docsTj Holowaychukbefore adoption4d32762
line 134why, one step back134\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fRMore docsTj Holowaychukbefore adoptionde81ee7
lines 135–136why, one step back135.136.IP "\(bu" 4Updated docsTj Holowaychukbefore adoption4d32762
line 137why, one step back137\fIhome\fR Application base path used with \fIres\.redirect()\fR, when mounted defaults to \fIServer#route\fR, otherwise \"/\"\. Assigned on \fIServer#listen()\fR\.More docsTj Holowaychukbefore adoptionbedff32
lines 138–139why, one step back138.139.IP "\(bu" 4Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 140–144why, one step back140\fIviews\fR Root views directory defaulting to \fBCWD/views\fR141.142.IP "\(bu" 4143\fIview engine\fR Default view engine name for views rendered without extensions144.Added more setting docsTj Holowaychukbefore adoption38281e6
line 145why, one step back145.IP "\(bu" 4Fixed reload views exampleTj Holowaychukbefore adoption5fcf971
line 146why, one step back146\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 147why, one step back147.Moved config docs upTj Holowaychukbefore adoption6e8413f
lines 148–149why, one step back148.IP "" 0149.Started guideTj Holowaychukbefore adoption9e3a0c6
line 150why, one step back150.SS "Routing"Route passing docsTj Holowaychukbefore adoption0ace97c
line 151why, one step back151Express 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 152–178why, one step back152.153.IP "" 4154.155.nf156157app\.get(\'/user/:id\', function(req, res, params){158 res\.send(\'user \' + params\.id);159});160.161.fi162.163.IP "" 0164.165.P166A 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:167.168.IP "" 4169.170.nf171172\\/user\\/([^\\/]+)\\/?173.174.fi175.176.IP "" 0177.178.PUpdated docsTj Holowaychukbefore adoption0111582
line 179why, one step back179Regular 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 180–184why, one step back180.181.IP "" 4182.183.nf184Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
line 185why, one step back185app\.get(/^\\/users?(?:\\/(\\d+)(?:\\\.\\\.(\\d+))?)?/, function(req, res, params){Updated docsTj Holowaychukbefore adoption0111582
line 186why, one step back186 res\.send(params);Docs for params.captures. Closes #358Tj Holowaychukbefore adoptiond03821b
lines 187–207why, one step back187});188.189.fi190.191.IP "" 0192.193.P194Curl requests against the previously defined route:195.196.IP "" 4197.198.nf199200 $ curl http://dev:3000/user201 [null,null]202 $ curl http://dev:3000/users203 [null,null]204 $ curl http://dev:3000/users/1205 [\"1\",null]206 $ curl http://dev:3000/users/1\.\.15207 [\"1\",\"15\"]Started guideTj Holowaychukbefore adoption9e3a0c6
lines 208–246why, one step back208.209.fi210.211.IP "" 0212.213.P214Below are some route examples, and the associated paths that they may consume:215.216.IP "" 4217.218.nf219220 \"/user/:id\"221 /user/12222223 \"/users/:id?\"224 /users/5225 /users226227 \"/files/*\"228 /files/jquery\.js229 /files/javascripts/jquery\.js230231 \"/file/*\.*\"232 /files/jquery\.js233 /files/javascripts/jquery\.js234235 \"/user/:id/:operation?\"236 /user/1237 /user/1/edit238239 \"/products\.:format\"240 /products\.json241 /products\.xml242243 \"/products\.:format?\"244 /products\.json245 /products\.xml246 /productsRoute passing docsTj Holowaychukbefore adoption0ace97c
lines 247–268why, one step back247.248.fi249.250.IP "" 0251.252.SS "Passing Route Control"253We 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\.254.255.IP "" 4256.257.nf258259app\.get(\'/users/:id?\', function(req, res, params){260 if (params\.id) {261 // do something262 } else {263 next();264 }265});266267app\.get(\'/users\', function(req, res, params){268 // do something elseAdded configuration sectionTj Holowaychukbefore adoption83d2555
lines 269–288why, one step back269});270.271.fi272.273.IP "" 0274.275.SS "Middleware"276The 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:277.278.IP "" 4279.280.nf281282var connect = require(\'connect\'),283 express = require(\'express\');284285var app = express\.createServer(286 connect\.logger(),287 connect\.bodyDecoder()288);More docsTj Holowaychukbefore adoptionbedff32
lines 289–293why, one step back289.290.fi291.292.IP "" 0293.Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 294–300why, one step back294.P295Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:296.297.IP "" 4298.299.nf300Updated docsTj Holowaychukbefore adoptioncacada8
line 301why, one step back301app\.use(connect\.logger({ format: \':method :uri\' }));Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 302–371why, one step back302.303.fi304.305.IP "" 0306.307.SS "Error Handling"308Express 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:309.310.IP "" 4311.312.nf313314function NotFound(msg){315 this\.name = \'NotFound\';316 Error\.call(this, msg);317 Error\.captureStackTrace(this, arguments\.callee);318}319320sys\.inherits(NotFound, Error);321322app\.get(\'/404\', function(req, res){323 throw new NotFound;324});325326app\.get(\'/500\', function(req, res){327 throw new Error(\'keyboard cat!\');328});329.330.fi331.332.IP "" 0333.334.P335We 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\.336.337.IP "" 4338.339.nf340341app\.error(function(err, req, res, next){342 if (err instanceof NotFound) {343 res\.render(\'404\.jade\');344 } else {345 next(err);346 }347});348.349.fi350.351.IP "" 0352.353.P354Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like355.356.IP "" 4357.358.nf359360app\.error(function(err, req, res){361 res\.render(\'500\.jade\', {362 locals: {363 error: err364 }365 });366});367.368.fi369.370.IP "" 0371.More error handling docsTj Holowaychukbefore adoptioncea401c
lines 372–378why, one step back372.P373Our 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:374.375.IP "" 4376.377.nf378Updated docsTj Holowaychukbefore adoptioncacada8
line 379why, one step back379app\.use(connect\.errorHandler({ dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 380–391why, one step back380.381.fi382.383.IP "" 0384.385.P386Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:387.388.IP "" 4389.390.nf391Updated docsTj Holowaychukbefore adoptioncacada8
line 392why, one step back392app\.use(connect\.errorHandler({ showStack: true, dumpExceptions: true }));More error handling docsTj Holowaychukbefore adoptioncea401c
lines 393–400why, one step back393.394.fi395.396.IP "" 0397.398.P399The \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\.400.Added more view docsTj Holowaychukbefore adoption2f96506
lines 401–420why, one step back401.SS "View Rendering"402View 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\.403.404.P405Below 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\.406.407.IP "" 4408.409.nf410411app\.get(\'/\', function(req, res){412 res\.render(\'index\.haml\', {413 locals: { title: \'My Site\' }414 });415});416.417.fi418.419.IP "" 0420.Docs for "view engine" settingTj Holowaychukbefore adoption1810c9b
lines 421–472why, one step back421.P422The 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:423.424.IP "" 4425.426.nf427428app\.set(\'view engine\', \'jade\');429.430.fi431.432.IP "" 0433.434.P435Allowing us to render with:436.437.IP "" 4438.439.nf440441res\.render(\'index\');442.443.fi444.445.IP "" 0446.447.P448vs:449.450.IP "" 4451.452.nf453454res\.render(\'index\.jade\');455.456.fi457.458.IP "" 0459.460.P461When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:462.463.IP "" 4464.465.nf466467res\.render(\'another\-page\.ejs\');468.469.fi470.471.IP "" 0472.Added more view docsTj Holowaychukbefore adoption2f96506
lines 473–511why, one step back473.SS "View Partials"474The 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:475.476.IP "" 4477.478.nf479480partial(\'comment\.haml\', { collection: comments });481.482.fi483.484.IP "" 0485.486.P487To 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\.488.489.IP "" 4490.491.nf492493partial(\'comment\', { collection: comments });494.495.fi496.497.IP "" 0498.499.P500And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:501.502.IP "" 4503.504.nf505506partial(\'comments\', comments);507.508.fi509.510.IP "" 0511.Added partial magic var docs. Closes #342Tj Holowaychukbefore adoptionbe85701
lines 512–525why, one step back512.P513When using the partial collection support a few \"magic\" variables are provided for free:514.515.IP "\(bu" 4516\fIfirstInCollection\fR True if this is the first object517.518.IP "\(bu" 4519\fIindexInCollection\fR Index of the object in the collection520.521.IP "\(bu" 4522_lastInCollection _ True if this is the last object523.524.IP "" 0525.Added more view docsTj Holowaychukbefore adoption2f96506
lines 526–539why, one step back526.SS "Template Engines"527Below are a few template engines commonly used with Express:528.529.IP "\(bu" 4530Jade \fIhttp://github\.com/visionmedia/jade\fR haml\.js successor531.532.IP "\(bu" 4533Haml \fIhttp://github\.com/visionmedia/haml\.js\fR indented templates534.535.IP "\(bu" 4536EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript537.538.IP "" 0539.More docsTj Holowaychukbefore adoptionde81ee7
line 540why, one step back540.SS "req\.header(key[, defaultValue])"More docsTj Holowaychukbefore adoptiondfecbe5
lines 541–554why, one step back541Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:542.543.IP "" 4544.545.nf546547req\.header(\'Host\');548req\.header(\'host\');549req\.header(\'Accept\', \'*/*\');550.551.fi552.553.IP "" 0554.More docsTj Holowaychukbefore adoptionde81ee7
line 555why, one step back555.SS "req\.accepts(type)"More docsTj Holowaychukbefore adoptiondfecbe5
lines 556–583why, one step back556Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.557.558.P559When 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\.560.561.IP "" 4562.563.nf564565// Accept: text/html566req\.accepts(\'html\');567// => true568569// Accept: text/*; application/json570req\.accepts(\'html\');571req\.accepts(\'text/html\');572req\.accepts(\'text/plain\');573req\.accepts(\'application/json\');574// => true575576req\.accepts(\'image/png\');577req\.accepts(\'png\');578// => false579.580.fi581.582.IP "" 0583.More docsTj Holowaychukbefore adoptionde81ee7
line 584why, one step back584.SS "req\.param(name)"More docsTj Holowaychukbefore adoptiondfecbe5
lines 585–600why, one step back585Return the value of param \fIname\fR when present\.586.587.IP "\(bu" 4588Checks route placeholders, ex: /user/:id589.590.IP "\(bu" 4591Checks query string params, ex: ?id=12592.593.IP "\(bu" 4594Checks urlencoded body params, ex: id=12595.596.IP "" 0597.598.P599To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIconnect\.bodyDecoder\fR middleware\.600.More docsTj Holowaychukbefore adoptionde81ee7
line 601why, one step back601.SS "req\.flash(type[, msg])"More docsTj Holowaychukbefore adoptiondfecbe5
lines 602–625why, one step back602Queue flash \fImsg\fR of the given \fItype\fR\.603.604.IP "" 4605.606.nf607608req\.flash(\'info\', \'email sent\');609req\.flash(\'error\', \'email delivery failed\');610req\.flash(\'info\', \'email re\-sent\');611// => 2612613req\.flash(\'info\');614// => [\'email sent\', \'email re\-sent\']615616req\.flash(\'info\');617// => []618619req\.flash();620// => { error: [\'email delivery failed\'], info: [] }621.622.fi623.624.IP "" 0625.More docsTj Holowaychukbefore adoptionde81ee7
line 626why, one step back626.SS "req\.isXMLHttpRequest"More docsTj Holowaychukbefore adoptiondfecbe5
lines 627–639why, one step back627Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:628.629.IP "" 4630.631.nf632633req\.xhr634req\.isXMLHttpRequest635.636.fi637.638.IP "" 0639.More docsTj Holowaychukbefore adoptionde81ee7
line 640why, one step back640.SS "res\.header(key[, val])"More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 641–659why, one step back641Get or set the response header \fIkey\fR\.642.643.IP "" 4644.645.nf646647res\.header(\'Content\-Length\');648// => undefined649650res\.header(\'Content\-Length\', 123);651// => 123652653res\.header(\'Content\-Length\');654// => 123655.656.fi657.658.IP "" 0659.More docsTj Holowaychukbefore adoptionde81ee7
line 660why, one step back660.SS "res\.contentType(type)"More docs :)Tj Holowaychukbefore adoption0c5fe61
lines 661–674why, one step back661Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.662.663.IP "" 4664.665.nf666667 var filename = \'path/to/image\.png\';668 res\.contentType(filename);669 // res\.headers[\'Content\-Type\'] is now \"image/png\"670.671.fi672.673.IP "" 0674.More docsTj Holowaychukbefore adoptionde81ee7
line 675why, one step back675.SS "res\.attachment([filename])"Docs for res.attachment()Tj Holowaychukbefore adoptioneb235e1
lines 676–687why, one step back676Sets the \fIContent\-Disposition\fR response header to \"attachment\", with optional \fIfilename\fR\.677.678.IP "" 4679.680.nf681682 res\.attachment(\'path/to/my/image\.png\');683.684.fi685.686.IP "" 0687.More docsTj Holowaychukbefore adoptionde81ee7
line 688why, one step back688.SS "res\.sendfile(path)"Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 689–701why, one step back689Used by \fBres\.download()\fR to transfer an arbitrary file\.690.691.IP "" 4692.693.nf694695res\.sendfile(\'path/to/my\.file\');696.697.fi698.699.IP "" 0700.701.PBetter docs for res.sendfile()Tj Holowaychukbefore adoption8a337f1
line 702why, one step back702This 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 703why, one step back703.More docsTj Holowaychukbefore adoptionde81ee7
line 704why, one step back704.SS "res\.download(file[, filename])"Docs for new res methodsTj Holowaychukbefore adoptionb08dab9
lines 705–731why, one step back705Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.706.707.IP "" 4708.709.nf710711res\.download(\'path/to/image\.png\');712res\.download(\'path/to/image\.png\', \'foo\.png\');713.714.fi715.716.IP "" 0717.718.P719This is equivalent to:720.721.IP "" 4722.723.nf724725res\.attachment(file);726res\.sendfile(file);727.728.fi729.730.IP "" 0731.More docsTj Holowaychukbefore adoptionde81ee7
line 732why, one step back732.SS "res\.send(body|status[, headers|status[, status]])"Docs for res.send()Tj Holowaychukbefore adoption5a48248
lines 733–752why, one step back733The \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:734.735.IP "" 4736.737.nf738739 res\.send(new Buffer(\'wahoo\'));740 res\.send({ some: \'json\' });741 res\.send(\'<p>some html</p>\');742 res\.send(\'Sorry, cant find that\', 404);743 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);744 res\.send(404);745.746.fi747.748.IP "" 0749.750.P751By 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\.752.More docsTj Holowaychukbefore adoptionde81ee7
line 753why, one step back753.SS "res\.redirect(url[, status])"More docsTj Holowaychukbefore adoptionbedff32
lines 754–772why, one step back754Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.755.756.IP "" 4757.758.nf759760res\.redirect(\'/\', 301);761res\.redirect(\'/account\');762res\.redirect(\'http://google\.com\');763res\.redirect(\'home\');764res\.redirect(\'back\');765.766.fi767.768.IP "" 0769.770.P771Express 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 \"/\"\.772.More view docsTj Holowaychukbefore adoption1c8ff48
lines 773–785why, one step back773.SS "res\.render(view[, options[, fn]])"774Render \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\.775.776.P777Most 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:778.779.IP "\(bu" 4780\fIcontext|scope\fR Template evaluation context (\fIthis\fR)781.782.IP "\(bu" 4783\fIlocals\fR Object containing local variables784.785.IP "\(bu" 4Cleaning up view docsTj Holowaychukbefore adoption25c8883
line 786why, one step back786\fIcache\fR Cache intermediate JavaScript in memory (the default in \fIproduction\fR mode)More view docsTj Holowaychukbefore adoption1c8ff48
lines 787–792why, one step back787.788.IP "\(bu" 4789\fIdebug\fR Output debugging information790.791.IP "" 0792.In depth partial docsTj Holowaychukbefore adoption793943f
lines 793–873why, one step back793.SS "res\.partial(view[, options])"794Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.795.796.IP "\(bu" 4797\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.798.799.IP "\(bu" 4800as: \'something\' will add the \fIsomething\fR local variable801.802.IP "\(bu" 4803as: this will use the collection value as the template context804.805.IP "\(bu" 4806as: global will merge the collection value\'s properties with \fIlocals\fR807.808.IP "" 0809810.811.IP "\(bu" 4812\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\.813.814.IP "" 0815.816.P817The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.818.819.IP "" 4820.821.nf822823partial(\'movie\.jade\', { collection: movies });824partial(\'movie\.jade\', movies);825partial(\'movie\', movies);826// In view: movie\.director827.828.fi829.830.IP "" 0831.832.P833To change the local from \fImovie\fR to \fIvideo\fR we can use the \"as\" option:834.835.IP "" 4836.837.nf838839partial(\'movie\', { collection: movies, as: \'video\' });840// In view: video\.director841.842.fi843.844.IP "" 0845.846.P847Also 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\.848.849.IP "" 4850.851.nf852853partial(\'movie\', { collection: movies, as: this });854// In view: this\.director855.856.fi857.858.IP "" 0859.860.P861Another 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:862.863.IP "" 4864.865.nf866867partials(\'movie\', { collection: movies, as: global });868// In view: director869.870.fi871.872.IP "" 0873.More docsTj Holowaychukbefore adoptionde81ee7
lines 874–938why, one step back874.SS "app\.set(name[, val])"875Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:876.877.IP "" 4878.879.nf880881app\.set(\'reload views\', 200);882app\.set(\'reload views\');883// => 200884.885.fi886.887.IP "" 0888.889.SS "app\.enable(name)"890Enable the given setting \fIname\fR:891.892.IP "" 4893.894.nf895896app\.enable(\'some arbitrary setting\');897app\.set(\'some arbitrary setting\');898// => true899.900.fi901.902.IP "" 0903.904.SS "app\.disable(name)"905Disable the given setting \fIname\fR:906.907.IP "" 4908.909.nf910911app\.disable(\'some setting\');912app\.set(\'some setting\');913// => false914.915.fi916.917.IP "" 0918.919.SS "app\.configure(env|function[, function])"920Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:921.922.IP "" 4923.924.nf925926app\.configure(function(){927 // executed for each env928});929930app\.configure(\'development\', function(){931 // executed for \'development\' only932});933.934.fi935.936.IP "" 0937.938.SS "app\.redirect(name, val)"More docsTj Holowaychukbefore adoptionbedff32
lines 939–980why, one step back939For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:940.941.IP "" 4942.943.nf944945app\.redirect(\'google\', \'http://google\.com\');946.947.fi948.949.IP "" 0950.951.P952Now in a route we may call:953.954.P955res\.redirect(\'google\');956.957.P958We may also map dynamic redirects:959.960.IP "" 4961.962.nf963964app\.redirect(\'comments\', function(req, res, params){965 return \'/post/\' + params\.id + \'/comments\';966});967.968.fi969.970.IP "" 0971.972.P973So 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\.974.975.IP "" 4976.977.nf978979app\.get(\'/post/:id\', function(req, res){980 res\.redirect(\'comments\');Error handling docsTj Holowaychukbefore adoption9fbb9fa
lines 981–987why, one step back981});982.983.fi984.985.IP "" 0986.987.SS "app\.error(function)"More error docsTj Holowaychukbefore adoption6227f5c
line 988why, one step back988Adds 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 989–995why, one step back989.990.IP "" 4991.992.nf993994app\.error(function(err, req, res, next){995 res\.send(err\.message, 500);More docsTj Holowaychukbefore adoptionbedff32
line 996why, one step back996});Added configuration sectionTj Holowaychukbefore adoption83d2555
lines 997–998why, one step back997.998.fiConfiguration docsTj Holowaychukbefore adoptioncb04364
lines 999–1000why, one step back999.1000.IP "" 0Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 1001–1002why, one step back1001.1002.SS "app\.helpers(obj)"Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
line 1003why, one step back1003Registers static view helpers\.Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 1004–1009why, one step back1004.1005.IP "" 41006.1007.nf10081009app\.helpers({Docs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 1010–1039why, one step back1010 name: function(first, last){ return first + \', \' + last },1011 firstName: \'tj\',1012 lastName: \'holowaychuk\'1013});1014.1015.fi1016.1017.IP "" 01018.1019.P1020Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1021.1022.IP "" 41023.1024.nf10251026<%= name(firstName, lastName) %>1027.1028.fi1029.1030.IP "" 01031.1032.SS "app\.dynamicHelpers(obj)"1033Registers 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\.1034.1035.IP "" 41036.1037.nf10381039app\.dynamicHelpers({Added app.helpers() docsTj Holowaychukbefore adoption7eb088b
lines 1040–1049why, one step back1040 session: function(req, res, params){1041 return req\.session;1042 }1043});1044.1045.fi1046.1047.IP "" 01048.1049.PDocs for Server#{helpers,dynamicHelpers}()Tj Holowaychukbefore adoption78008d1
lines 1050–1060why, one step back1050All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1051.1052.IP "" 41053.1054.nf10551056<%= session\.name %>1057.1058.fi1059.1060.IP "" 0Server#listen() docsTj Holowaychukbefore adoptionf3803c4
lines 1061–1075why, one step back1061.1062.SS "app\.listen([port[, host]])"1063Bind 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\.1064.1065.IP "" 41066.1067.nf10681069app\.listen();1070app\.listen(3000);1071app\.listen(3000, \'n\.n\.n\.n\');1072.1073.fi1074.1075.IP "" 0Unix domain socket docsTj Holowaychukbefore adoption2fa7907
lines 1076–1108why, one step back1076.1077.P1078The \fIport\fR argument may also be a string representing the path to a unix domain socket:1079.1080.IP "" 41081.1082.nf10831084app\.listen(\'/tmp/express\.sock\');1085.1086.fi1087.1088.IP "" 01089.1090.P1091Then try it out:1092.1093.IP "" 41094.1095.nf10961097$ telnet /tmp/express\.sock1098GET / HTTP/1\.110991100HTTP/1\.1 200 OK1101Content\-Type: text/plain1102Content\-Length: 1111031104Hello World1105.1106.fi1107.1108.IP "" 0Started guideTj Holowaychukbefore adoption9e3a0c6
line 1109why, one step back1109