Skip to content
Myr

guide.1

This file

Path

docs/guide.1

883 lines · 17.7 KiB

Last changed by

More view docsTj Holowaychukbefore adoption1c8ff48

History of this file

Take 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.SS "View Partials"400The 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:401.402.IP "" 4403.404.nf405406partial(\'comment\.haml\', { collection: comments });407.408.fi409.410.IP "" 0411.412.P413To 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\.414.415.IP "" 4416.417.nf418419partial(\'comment\', { collection: comments });420.421.fi422.423.IP "" 0424.425.P426And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:427.428.IP "" 4429.430.nf431432partial(\'comments\', comments);433.434.fi435.436.IP "" 0437.438.SS "Template Engines"439Below are a few template engines commonly used with Express:440.441.IP "\(bu" 4442Jade \fIhttp://github\.com/visionmedia/jade\fR haml\.js successor443.444.IP "\(bu" 4445Haml \fIhttp://github\.com/visionmedia/haml\.js\fR indented templates446.447.IP "\(bu" 4448EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript449.450.IP "" 0451.452.SS "req\.header(key[, defaultValue])"453Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:454.455.IP "" 4456.457.nf458459req\.header(\'Host\');460req\.header(\'host\');461req\.header(\'Accept\', \'*/*\');462.463.fi464.465.IP "" 0466.467.SS "req\.accepts(type)"468Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.469.470.P471When 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\.472.473.IP "" 4474.475.nf476477// Accept: text/html478req\.accepts(\'html\');479// => true480481// Accept: text/*; application/json482req\.accepts(\'html\');483req\.accepts(\'text/html\');484req\.accepts(\'text/plain\');485req\.accepts(\'application/json\');486// => true487488req\.accepts(\'image/png\');489req\.accepts(\'png\');490// => false491.492.fi493.494.IP "" 0495.496.SS "req\.param(name)"497Return the value of param \fIname\fR when present\.498.499.IP "\(bu" 4500Checks route placeholders, ex: /user/:id501.502.IP "\(bu" 4503Checks query string params, ex: ?id=12504.505.IP "\(bu" 4506Checks urlencoded body params, ex: id=12507.508.IP "" 0509.510.P511To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIconnect\.bodyDecoder\fR middleware\.512.513.SS "req\.flash(type[, msg])"514Queue flash \fImsg\fR of the given \fItype\fR\.515.516.IP "" 4517.518.nf519520req\.flash(\'info\', \'email sent\');521req\.flash(\'error\', \'email delivery failed\');522req\.flash(\'info\', \'email re\-sent\');523// => 2524525req\.flash(\'info\');526// => [\'email sent\', \'email re\-sent\']527528req\.flash(\'info\');529// => []530531req\.flash();532// => { error: [\'email delivery failed\'], info: [] }533.534.fi535.536.IP "" 0537.538.SS "req\.isXMLHttpRequest"539Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:540.541.IP "" 4542.543.nf544545req\.xhr546req\.isXMLHttpRequest547.548.fi549.550.IP "" 0551.552.SS "res\.header(key[, val])"553Get or set the response header \fIkey\fR\.554.555.IP "" 4556.557.nf558559res\.header(\'Content\-Length\');560// => undefined561562res\.header(\'Content\-Length\', 123);563// => 123564565res\.header(\'Content\-Length\');566// => 123567.568.fi569.570.IP "" 0571.572.SS "res\.contentType(type)"573Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.574.575.IP "" 4576.577.nf578579  var filename = \'path/to/image\.png\';580  res\.contentType(filename);581  // res\.headers[\'Content\-Type\'] is now \"image/png\"582.583.fi584.585.IP "" 0586.587.SS "res\.attachment([filename])"588Sets the \fIContent\-Disposition\fR response header to \"attachment\", with optional \fIfilename\fR\.589.590.IP "" 4591.592.nf593594  res\.attachment(\'path/to/my/image\.png\');595.596.fi597.598.IP "" 0599.600.SS "res\.sendfile(path)"601Used by \fBres\.download()\fR to transfer an arbitrary file\.602.603.IP "" 4604.605.nf606607res\.sendfile(\'path/to/my\.file\');608.609.fi610.611.IP "" 0612.613.P614\fBNOTE\fR: this is \fInot\fR a replacement for Connect\'s \fIstaticProvider\fR middleware, nor does it perform any security checks, use with caution when using in a dynamic manner\.615.616.SS "res\.download(file[, filename])"617Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.618.619.IP "" 4620.621.nf622623res\.download(\'path/to/image\.png\');624res\.download(\'path/to/image\.png\', \'foo\.png\');625.626.fi627.628.IP "" 0629.630.P631This is equivalent to:632.633.IP "" 4634.635.nf636637res\.attachment(file);638res\.sendfile(file);639.640.fi641.642.IP "" 0643.644.SS "res\.send(body|status[, headers|status[, status]])"645The \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:646.647.IP "" 4648.649.nf650651 res\.send(new Buffer(\'wahoo\'));652 res\.send({ some: \'json\' });653 res\.send(\'<p>some html</p>\');654 res\.send(\'Sorry, cant find that\', 404);655 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);656 res\.send(404);657.658.fi659.660.IP "" 0661.662.P663By 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\.664.665.SS "res\.redirect(url[, status])"666Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.667.668.IP "" 4669.670.nf671672res\.redirect(\'/\', 301);673res\.redirect(\'/account\');674res\.redirect(\'http://google\.com\');675res\.redirect(\'home\');676res\.redirect(\'back\');677.678.fi679.680.IP "" 0681.682.P683Express 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 \"/\"\.684.685.SS "res\.render(view[, options[, fn]])"686Render \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\.687.688.P689Most 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:690.691.IP "\(bu" 4692\fIcontext|scope\fR Template evaluation context (\fIthis\fR)693.694.IP "\(bu" 4695\fIlocals\fR Object containing local variables696.697.IP "\(bu" 4698\fIfilename\fR Filename used for the \fIcache\fR option699.700.IP "\(bu" 4701\fIcache\fR Cache intermediate JavaScript in memory702.703.IP "\(bu" 4704\fIdebug\fR Output debugging information705.706.IP "" 0707.708.SS "app\.set(name[, val])"709Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:710.711.IP "" 4712.713.nf714715app\.set(\'reload views\', 200);716app\.set(\'reload views\');717// => 200718.719.fi720.721.IP "" 0722.723.SS "app\.enable(name)"724Enable the given setting \fIname\fR:725.726.IP "" 4727.728.nf729730app\.enable(\'some arbitrary setting\');731app\.set(\'some arbitrary setting\');732// => true733.734.fi735.736.IP "" 0737.738.SS "app\.disable(name)"739Disable the given setting \fIname\fR:740.741.IP "" 4742.743.nf744745app\.disable(\'some setting\');746app\.set(\'some setting\');747// => false748.749.fi750.751.IP "" 0752.753.SS "app\.configure(env|function[, function])"754Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:755.756.IP "" 4757.758.nf759760app\.configure(function(){761    // executed for each env762});763764app\.configure(\'development\', function(){765    // executed for \'development\' only766});767.768.fi769.770.IP "" 0771.772.SS "app\.redirect(name, val)"773For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:774.775.IP "" 4776.777.nf778779app\.redirect(\'google\', \'http://google\.com\');780.781.fi782.783.IP "" 0784.785.P786Now in a route we may call:787.788.P789res\.redirect(\'google\');790.791.P792We may also map dynamic redirects:793.794.IP "" 4795.796.nf797798app\.redirect(\'comments\', function(req, res, params){799    return \'/post/\' + params\.id + \'/comments\';800});801.802.fi803.804.IP "" 0805.806.P807So 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\.808.809.IP "" 4810.811.nf812813app\.get(\'/post/:id\', function(req, res){814    res\.redirect(\'comments\');815});816.817.fi818.819.IP "" 0820.821.SS "app\.error(function)"822Adds 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:823.824.IP "" 4825.826.nf827828app\.error(function(err, req, res, next){829    res\.send(err\.message, 500);830});831.832.fi833.834.IP "" 0835.836.SS "app\.listen([port[, host]])"837Bind 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\.838.839.IP "" 4840.841.nf842843app\.listen();844app\.listen(3000);845app\.listen(3000, \'n\.n\.n\.n\');846.847.fi848.849.IP "" 0850.851.P852The \fIport\fR argument may also be a string representing the path to a unix domain socket:853.854.IP "" 4855.856.nf857858app\.listen(\'/tmp/express\.sock\');859.860.fi861.862.IP "" 0863.864.P865Then try it out:866.867.IP "" 4868.869.nf870871$ telnet /tmp/express\.sock872GET / HTTP/1\.1873874HTTP/1\.1 200 OK875Content\-Type: text/plain876Content\-Length: 11877878Hello World879.880.fi881.882.IP "" 0883