guide.1
This file
Path
docs/guide.1
1,013 lines · 20.1 KiB
Last changed by
Updated docsTj Holowaychukbefore adoptioncacada8
History of this fileTake it
1.\" generated with Ronn/v0.6.62.\" http://github.com/rtomayko/ronn/3.4.TH "GUIDE" "" "July 2010" "" ""5.6.SS "Installation"7npm:8.9.IP "" 410.11.nf1213$ npm install connect14$ npm install express15.16.fi17.18.IP "" 019.20.P21curl (or similar):22.23.IP "" 424.25.nf2627$ curl \-# http://github\.com/visionmedia/express/raw/master/install\.sh | sh28.29.fi30.31.IP "" 032.33.P34git clone, first update the submodules:35.36.IP "" 437.38.nf3940$ git submodule update \-\-init41$ make install42$ make install\-support43.44.fi45.46.IP "" 047.48.SS "Creating An Application"49The \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\.50.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.67.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(){78 app\.use(connect\.methodOverride());79 app\.use(connect\.bodyDecoder());80});8182app\.configure(\'development\', function(){83 app\.use(connect\.errorHandler({ dumpExceptions: true, showStack: true }));84});8586app\.configure(\'production\', function(){87 app\.use(connect\.errorHandler());88});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.117.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.130.SS "Settings"131Express supports the following settings out of the box:132.133.IP "\(bu" 4134\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR to utilize135.136.IP "\(bu" 4137\fIhome\fR Application base path used with \fIres\.redirect()\fR138.139.IP "\(bu" 4140\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.145.IP "\(bu" 4146\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);\fR147.148.IP "" 0149.150.SS "Routing"151Express 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\.152.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.P179Literal regular expressions may also be passed for complex uses:180.181.IP "" 4182.183.nf184185app\.get(/^\\/foo(bar)?$/, function(){});186.187.fi188.189.IP "" 0190.191.P192Below are some route examples, and the associated paths that they may consume:193.194.IP "" 4195.196.nf197198 \"/user/:id\"199 /user/12200201 \"/users/:id?\"202 /users/5203 /users204205 \"/files/*\"206 /files/jquery\.js207 /files/javascripts/jquery\.js208209 \"/file/*\.*\"210 /files/jquery\.js211 /files/javascripts/jquery\.js212213 \"/user/:id/:operation?\"214 /user/1215 /user/1/edit216217 \"/products\.:format\"218 /products\.json219 /products\.xml220221 \"/products\.:format?\"222 /products\.json223 /products\.xml224 /products225.226.fi227.228.IP "" 0229.230.SS "Passing Route Control"231We 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\.232.233.IP "" 4234.235.nf236237app\.get(\'/users/:id?\', function(req, res, params){238 if (params\.id) {239 // do something240 } else {241 next();242 }243});244245app\.get(\'/users\', function(req, res, params){246 // do something else247});248.249.fi250.251.IP "" 0252.253.SS "Middleware"254The 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:255.256.IP "" 4257.258.nf259260var connect = require(\'connect\'),261 express = require(\'express\');262263var app = express\.createServer(264 connect\.logger(),265 connect\.bodyDecoder()266);267.268.fi269.270.IP "" 0271.272.P273Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:274.275.IP "" 4276.277.nf278279app\.use(connect\.logger({ format: \':method :uri\' }));280.281.fi282.283.IP "" 0284.285.SS "Error Handling"286Express 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:287.288.IP "" 4289.290.nf291292function NotFound(msg){293 this\.name = \'NotFound\';294 Error\.call(this, msg);295 Error\.captureStackTrace(this, arguments\.callee);296}297298sys\.inherits(NotFound, Error);299300app\.get(\'/404\', function(req, res){301 throw new NotFound;302});303304app\.get(\'/500\', function(req, res){305 throw new Error(\'keyboard cat!\');306});307.308.fi309.310.IP "" 0311.312.P313We 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\.314.315.IP "" 4316.317.nf318319app\.error(function(err, req, res, next){320 if (err instanceof NotFound) {321 res\.render(\'404\.jade\');322 } else {323 next(err);324 }325});326.327.fi328.329.IP "" 0330.331.P332Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like333.334.IP "" 4335.336.nf337338app\.error(function(err, req, res){339 res\.render(\'500\.jade\', {340 locals: {341 error: err342 }343 });344});345.346.fi347.348.IP "" 0349.350.P351Our 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:352.353.IP "" 4354.355.nf356357app\.use(connect\.errorHandler({ dumpExceptions: true }));358.359.fi360.361.IP "" 0362.363.P364Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:365.366.IP "" 4367.368.nf369370app\.use(connect\.errorHandler({ showStack: true, dumpExceptions: true }));371.372.fi373.374.IP "" 0375.376.P377The \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\.378.379.SS "View Rendering"380View 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\.381.382.P383Below 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\.384.385.IP "" 4386.387.nf388389app\.get(\'/\', function(req, res){390 res\.render(\'index\.haml\', {391 locals: { title: \'My Site\' }392 });393});394.395.fi396.397.IP "" 0398.399.P400The 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:401.402.IP "" 4403.404.nf405406app\.set(\'view engine\', \'jade\');407.408.fi409.410.IP "" 0411.412.P413Allowing us to render with:414.415.IP "" 4416.417.nf418419res\.render(\'index\');420.421.fi422.423.IP "" 0424.425.P426vs:427.428.IP "" 4429.430.nf431432res\.render(\'index\.jade\');433.434.fi435.436.IP "" 0437.438.P439When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:440.441.IP "" 4442.443.nf444445res\.render(\'another\-page\.ejs\');446.447.fi448.449.IP "" 0450.451.SS "View Partials"452The 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:453.454.IP "" 4455.456.nf457458partial(\'comment\.haml\', { collection: comments });459.460.fi461.462.IP "" 0463.464.P465To 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\.466.467.IP "" 4468.469.nf470471partial(\'comment\', { collection: comments });472.473.fi474.475.IP "" 0476.477.P478And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:479.480.IP "" 4481.482.nf483484partial(\'comments\', comments);485.486.fi487.488.IP "" 0489.490.SS "Template Engines"491Below are a few template engines commonly used with Express:492.493.IP "\(bu" 4494Jade \fIhttp://github\.com/visionmedia/jade\fR haml\.js successor495.496.IP "\(bu" 4497Haml \fIhttp://github\.com/visionmedia/haml\.js\fR indented templates498.499.IP "\(bu" 4500EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript501.502.IP "" 0503.504.SS "req\.header(key[, defaultValue])"505Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:506.507.IP "" 4508.509.nf510511req\.header(\'Host\');512req\.header(\'host\');513req\.header(\'Accept\', \'*/*\');514.515.fi516.517.IP "" 0518.519.SS "req\.accepts(type)"520Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.521.522.P523When 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\.524.525.IP "" 4526.527.nf528529// Accept: text/html530req\.accepts(\'html\');531// => true532533// Accept: text/*; application/json534req\.accepts(\'html\');535req\.accepts(\'text/html\');536req\.accepts(\'text/plain\');537req\.accepts(\'application/json\');538// => true539540req\.accepts(\'image/png\');541req\.accepts(\'png\');542// => false543.544.fi545.546.IP "" 0547.548.SS "req\.param(name)"549Return the value of param \fIname\fR when present\.550.551.IP "\(bu" 4552Checks route placeholders, ex: /user/:id553.554.IP "\(bu" 4555Checks query string params, ex: ?id=12556.557.IP "\(bu" 4558Checks urlencoded body params, ex: id=12559.560.IP "" 0561.562.P563To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIconnect\.bodyDecoder\fR middleware\.564.565.SS "req\.flash(type[, msg])"566Queue flash \fImsg\fR of the given \fItype\fR\.567.568.IP "" 4569.570.nf571572req\.flash(\'info\', \'email sent\');573req\.flash(\'error\', \'email delivery failed\');574req\.flash(\'info\', \'email re\-sent\');575// => 2576577req\.flash(\'info\');578// => [\'email sent\', \'email re\-sent\']579580req\.flash(\'info\');581// => []582583req\.flash();584// => { error: [\'email delivery failed\'], info: [] }585.586.fi587.588.IP "" 0589.590.SS "req\.isXMLHttpRequest"591Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:592.593.IP "" 4594.595.nf596597req\.xhr598req\.isXMLHttpRequest599.600.fi601.602.IP "" 0603.604.SS "res\.header(key[, val])"605Get or set the response header \fIkey\fR\.606.607.IP "" 4608.609.nf610611res\.header(\'Content\-Length\');612// => undefined613614res\.header(\'Content\-Length\', 123);615// => 123616617res\.header(\'Content\-Length\');618// => 123619.620.fi621.622.IP "" 0623.624.SS "res\.contentType(type)"625Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.626.627.IP "" 4628.629.nf630631 var filename = \'path/to/image\.png\';632 res\.contentType(filename);633 // res\.headers[\'Content\-Type\'] is now \"image/png\"634.635.fi636.637.IP "" 0638.639.SS "res\.attachment([filename])"640Sets the \fIContent\-Disposition\fR response header to \"attachment\", with optional \fIfilename\fR\.641.642.IP "" 4643.644.nf645646 res\.attachment(\'path/to/my/image\.png\');647.648.fi649.650.IP "" 0651.652.SS "res\.sendfile(path)"653Used by \fBres\.download()\fR to transfer an arbitrary file\.654.655.IP "" 4656.657.nf658659res\.sendfile(\'path/to/my\.file\');660.661.fi662.663.IP "" 0664.665.P666This 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\.667.668.SS "res\.download(file[, filename])"669Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.670.671.IP "" 4672.673.nf674675res\.download(\'path/to/image\.png\');676res\.download(\'path/to/image\.png\', \'foo\.png\');677.678.fi679.680.IP "" 0681.682.P683This is equivalent to:684.685.IP "" 4686.687.nf688689res\.attachment(file);690res\.sendfile(file);691.692.fi693.694.IP "" 0695.696.SS "res\.send(body|status[, headers|status[, status]])"697The \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:698.699.IP "" 4700.701.nf702703 res\.send(new Buffer(\'wahoo\'));704 res\.send({ some: \'json\' });705 res\.send(\'<p>some html</p>\');706 res\.send(\'Sorry, cant find that\', 404);707 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);708 res\.send(404);709.710.fi711.712.IP "" 0713.714.P715By 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\.716.717.SS "res\.redirect(url[, status])"718Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.719.720.IP "" 4721.722.nf723724res\.redirect(\'/\', 301);725res\.redirect(\'/account\');726res\.redirect(\'http://google\.com\');727res\.redirect(\'home\');728res\.redirect(\'back\');729.730.fi731.732.IP "" 0733.734.P735Express 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 \"/\"\.736.737.SS "res\.render(view[, options[, fn]])"738Render \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\.739.740.P741Most 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:742.743.IP "\(bu" 4744\fIcontext|scope\fR Template evaluation context (\fIthis\fR)745.746.IP "\(bu" 4747\fIlocals\fR Object containing local variables748.749.IP "\(bu" 4750\fIcache\fR Cache intermediate JavaScript in memory (the default in \fIproduction\fR mode)751.752.IP "\(bu" 4753\fIdebug\fR Output debugging information754.755.IP "" 0756.757.SS "res\.partial(view[, options])"758Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.759.760.IP "\(bu" 4761\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.762.763.IP "\(bu" 4764as: \'something\' will add the \fIsomething\fR local variable765.766.IP "\(bu" 4767as: this will use the collection value as the template context768.769.IP "\(bu" 4770as: global will merge the collection value\'s properties with \fIlocals\fR771.772.IP "" 0773774.775.IP "\(bu" 4776\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\.777.778.IP "" 0779.780.P781The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.782.783.IP "" 4784.785.nf786787partial(\'movie\.jade\', { collection: movies });788partial(\'movie\.jade\', movies);789partial(\'movie\', movies);790// In view: movie\.director791.792.fi793.794.IP "" 0795.796.P797To change the local from \fImovie\fR to \fIvideo\fR we can use the \"as\" option:798.799.IP "" 4800.801.nf802803partial(\'movie\', { collection: movies, as: \'video\' });804// In view: video\.director805.806.fi807.808.IP "" 0809.810.P811Also 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\.812.813.IP "" 4814.815.nf816817partial(\'movie\', { collection: movies, as: this });818// In view: this\.director819.820.fi821.822.IP "" 0823.824.P825Another 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:826.827.IP "" 4828.829.nf830831partials(\'movie\', { collection: movies, as: global });832// In view: director833.834.fi835.836.IP "" 0837.838.SS "app\.set(name[, val])"839Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:840.841.IP "" 4842.843.nf844845app\.set(\'reload views\', 200);846app\.set(\'reload views\');847// => 200848.849.fi850.851.IP "" 0852.853.SS "app\.enable(name)"854Enable the given setting \fIname\fR:855.856.IP "" 4857.858.nf859860app\.enable(\'some arbitrary setting\');861app\.set(\'some arbitrary setting\');862// => true863.864.fi865.866.IP "" 0867.868.SS "app\.disable(name)"869Disable the given setting \fIname\fR:870.871.IP "" 4872.873.nf874875app\.disable(\'some setting\');876app\.set(\'some setting\');877// => false878.879.fi880.881.IP "" 0882.883.SS "app\.configure(env|function[, function])"884Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:885.886.IP "" 4887.888.nf889890app\.configure(function(){891 // executed for each env892});893894app\.configure(\'development\', function(){895 // executed for \'development\' only896});897.898.fi899.900.IP "" 0901.902.SS "app\.redirect(name, val)"903For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:904.905.IP "" 4906.907.nf908909app\.redirect(\'google\', \'http://google\.com\');910.911.fi912.913.IP "" 0914.915.P916Now in a route we may call:917.918.P919res\.redirect(\'google\');920.921.P922We may also map dynamic redirects:923.924.IP "" 4925.926.nf927928app\.redirect(\'comments\', function(req, res, params){929 return \'/post/\' + params\.id + \'/comments\';930});931.932.fi933.934.IP "" 0935.936.P937So 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\.938.939.IP "" 4940.941.nf942943app\.get(\'/post/:id\', function(req, res){944 res\.redirect(\'comments\');945});946.947.fi948.949.IP "" 0950.951.SS "app\.error(function)"952Adds 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:953.954.IP "" 4955.956.nf957958app\.error(function(err, req, res, next){959 res\.send(err\.message, 500);960});961.962.fi963.964.IP "" 0965.966.SS "app\.listen([port[, host]])"967Bind 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\.968.969.IP "" 4970.971.nf972973app\.listen();974app\.listen(3000);975app\.listen(3000, \'n\.n\.n\.n\');976.977.fi978.979.IP "" 0980.981.P982The \fIport\fR argument may also be a string representing the path to a unix domain socket:983.984.IP "" 4985.986.nf987988app\.listen(\'/tmp/express\.sock\');989.990.fi991.992.IP "" 0993.994.P995Then try it out:996.997.IP "" 4998.999.nf10001001$ telnet /tmp/express\.sock1002GET / HTTP/1\.110031004HTTP/1\.1 200 OK1005Content\-Type: text/plain1006Content\-Length: 1110071008Hello World1009.1010.fi1011.1012.IP "" 01013