Skip to content
Myr

guide.1

This file

Path

docs/guide.1

1,338 lines · 26.0 KiB

Last changed by

Updated docsTj Holowaychukbefore adoptionf0eab06

History of this file

Take it

1.\" generated with Ronn/v0.7.32.\" http://github.com/rtomayko/ronn/tree/0.7.33.4.TH "GUIDE" "" "September 2010" "" ""5.6.SH "NAME"7\fBguide\fR8.9.SS "Installation"10curl:11.12.IP "" 413.14.nf1516$ curl \-# http://expressjs\.com/install\.sh | sh17.18.fi19.20.IP "" 021.22.P23npm:24.25.IP "" 426.27.nf2829$ npm install express30.31.fi32.33.IP "" 034.35.P36git clone, first update the submodules:37.38.IP "" 439.40.nf4142$ git submodule update \-\-init43$ make install44$ make install\-support45.46.fi47.48.IP "" 049.50.SS "Creating An Application"51The \fIexpress\.Server\fR now inherits from \fIhttp\.Server\fR, however follows the same idiom by providing \fIexpress\.createServer()\fR as shown below\. This means that you can utilize Express server\'s transparently with other libraries\.52.53.IP "" 454.55.nf5657var app = require(\'express\')\.createServer();5859app\.get(\'/\', function(req, res){60    res\.send(\'hello world\');61});6263app\.listen(3000);64.65.fi66.67.IP "" 068.69.SS "Configuration"70Express supports arbitrary environments, such as \fIproduction\fR and \fIdevelopment\fR\. Developers can use the \fIconfigure()\fR method to setup needs required by the current environment\. When \fIconfigure()\fR is called without an environment name it will be run in \fIevery\fR environment prior to the environment specific callback\.71.72.P73In the example below we only \fIdumpExceptions\fR, and respond with exception stack traces in \fIdevelopment\fR mode, however for both environments we utilize \fImethodOverride\fR and \fIbodyDecoder\fR\. Note the use of \fIapp\.router\fR, which can (optionally) be used to mount the application routes, otherwise the first call to \fIapp\.{get,put,del,post}()\fR will mount the routes\.74.75.IP "" 476.77.nf7879app\.configure(function(){80    app\.use(express\.methodOverride());81    app\.use(express\.bodyDecoder());82    app\.use(app\.router);83    app\.use(express\.staticProvider(__dirname + \'/public\'));84});8586app\.configure(\'development\', function(){87    app\.use(express\.errorHandler({ dumpExceptions: true, showStack: true }));88});8990app\.configure(\'production\', function(){91    app\.use(express\.errorHandler());92});93.94.fi95.96.IP "" 097.98.P99For internal and arbitrary settings Express provides the \fIset(key[, val])\fR, \fIenable(key)\fR, \fIdisable(key)\fR methods:100.101.IP "" 4102.103.nf104105app\.configure(function(){106    app\.set(\'views\', __dirname + \'/views\');107    app\.set(\'views\');108    // => "\.\.\. views directory \.\.\."109110    app\.enable(\'some feature\');111    // same as app\.set(\'some feature\', true);112113    app\.disable(\'some feature\');114    // same as app\.set(\'some feature\', false);115});116.117.fi118.119.IP "" 0120.121.P122To alter the environment we can set the \fICONNECT_ENV\fR environment variable, or more specifically \fIEXPRESS_ENV\fR, for example:123.124.IP "" 4125.126.nf127128$ EXPRESS_ENV=production node app\.js129.130.fi131.132.IP "" 0133.134.SS "Settings"135Express supports the following settings out of the box:136.137.IP "\(bu" 4138\fIenv\fR Application environment set internally, use \fIapp\.set(\'env\')\fR on \fIServer#listen()\fR139.140.IP "\(bu" 4141\fIhome\fR Application base path used for \fIres\.redirect()\fR and transparently handling mounted apps\.142.143.IP "\(bu" 4144\fIviews\fR Root views directory defaulting to \fBCWD/views\fR145.146.IP "\(bu" 4147\fIview engine\fR Default view engine name for views rendered without extensions148.149.IP "\(bu" 4150\fIview options\fR An object specifying global view options151.152.IP "\(bu" 4153\fIpartials\fR Root view partials directory defaulting to \fIviews\fR/partials\.154.155.IP "\(bu" 4156\fIstream threshold\fR Bytesize indicating when a file should be streamed for \fIres\.sendfile()\fR using \fIfs\.ReadStream()\fR and \fIsys\.pump()\fR\.157.158.IP "" 0159.160.SS "Routing"161Express utilizes the HTTP verbs to provide a meaningful, expressive routing API\. For example we may want to render a user\'s account for the path \fI/user/12\fR, this can be done by defining the route below\. The values associated to the named placeholders are available as \fBreq\.params\fR\.162.163.IP "" 4164.165.nf166167app\.get(\'/user/:id\', function(req, res){168    res\.send(\'user \' + req\.params\.id);169});170.171.fi172.173.IP "" 0174.175.P176A route is simple a string which is compiled to a \fIRegExp\fR internally\. For example when \fI/user/:id\fR is compiled, a simplified version of the regexp may look similar to:177.178.IP "" 4179.180.nf181182\e/user\e/([^\e/]+)\e/?183.184.fi185.186.IP "" 0187.188.P189Regular expression literals may also be passed for complex uses\. Since capture groups with literal \fIRegExp\fR\'s are anonymous we can access them directly \fBreq\.params\fR\.190.191.IP "" 4192.193.nf194195app\.get(/^\e/users?(?:\e/(\ed+)(?:\e\.\e\.(\ed+))?)?/, function(req, res){196    res\.send(req\.params);197});198.199.fi200.201.IP "" 0202.203.P204Curl requests against the previously defined route:205.206.IP "" 4207.208.nf209210   $ curl http://dev:3000/user211   [null,null]212   $ curl http://dev:3000/users213   [null,null]214   $ curl http://dev:3000/users/1215   ["1",null]216   $ curl http://dev:3000/users/1\.\.15217   ["1","15"]218.219.fi220.221.IP "" 0222.223.P224Below are some route examples, and the associated paths that they may consume:225.226.IP "" 4227.228.nf229230 "/user/:id"231 /user/12232233 "/users/:id?"234 /users/5235 /users236237 "/files/*"238 /files/jquery\.js239 /files/javascripts/jquery\.js240241 "/file/*\.*"242 /files/jquery\.js243 /files/javascripts/jquery\.js244245 "/user/:id/:operation?"246 /user/1247 /user/1/edit248249 "/products\.:format"250 /products\.json251 /products\.xml252253 "/products\.:format?"254 /products\.json255 /products\.xml256 /products257.258.fi259.260.IP "" 0261.262.SS "Passing Route Control"263We may pass control to the next \fImatching\fR route, by calling the \fIthird\fR argument, the \fInext()\fR function\. When a match cannot be made, control is passed back to Connect, and middleware continue to be invoked\.264.265.IP "" 4266.267.nf268269app\.get(\'/users/:id?\', function(req, res, next){270    var id = req\.params\.id;271    if (id) {272        // do something273    } else {274        next();275    }276});277278app\.get(\'/users\', function(req, res){279    // do something else280});281.282.fi283.284.IP "" 0285.286.SS "Middleware"287The Express \fIPlugin\fR is no more! middleware via Connect \fIhttp://github\.com/senchalabs/connect\fR can be passed to \fIexpress\.createServer()\fR as you would with a regular Connect server\. For example:288.289.IP "" 4290.291.nf292293var express = require(\'express\');294295var app = express\.createServer(296    express\.logger(),297    express\.bodyDecoder()298);299.300.fi301.302.IP "" 0303.304.P305Alternatively we can \fIuse()\fR them which is useful when adding middleware within \fIconfigure()\fR blocks:306.307.IP "" 4308.309.nf310311app\.use(express\.logger({ format: \':method :uri\' }));312.313.fi314.315.IP "" 0316.317.P318Typically with connect middleware you would \fIrequire(\'connect\')\fR like so:319.320.IP "" 4321.322.nf323324var connect = require(\'connect\');325app\.use(connect\.logger());326.327.fi328.329.IP "" 0330.331.P332This is somewhat annoying, so express re\-exports these middleware properties, however they are \fIidentical\fR:333.334.IP "" 4335.336.nf337338app\.use(express\.logger());339.340.fi341.342.IP "" 0343.344.SS "Error Handling"345Express 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:346.347.IP "" 4348.349.nf350351function NotFound(msg){352    this\.name = \'NotFound\';353    Error\.call(this, msg);354    Error\.captureStackTrace(this, arguments\.callee);355}356357sys\.inherits(NotFound, Error);358359app\.get(\'/404\', function(req, res){360    throw new NotFound;361});362363app\.get(\'/500\', function(req, res){364    throw new Error(\'keyboard cat!\');365});366.367.fi368.369.IP "" 0370.371.P372We 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\.373.374.P375Note that these handlers can be defined anywhere, as they will be placed below the route handlers on \fIlisten()\fR\. This allows for definition within \fIconfigure()\fR blocks so we can handle exceptions in different ways based on the environment\.376.377.IP "" 4378.379.nf380381app\.error(function(err, req, res, next){382    if (err instanceof NotFound) {383        res\.render(\'404\.jade\');384    } else {385        next(err);386    }387});388.389.fi390.391.IP "" 0392.393.P394Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like395.396.IP "" 4397.398.nf399400app\.error(function(err, req, res){401    res\.render(\'500\.jade\', {402       locals: {403           error: err404       }405    });406});407.408.fi409.410.IP "" 0411.412.P413Our 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:414.415.IP "" 4416.417.nf418419app\.use(express\.errorHandler({ dumpExceptions: true }));420.421.fi422.423.IP "" 0424.425.P426Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set \fIshowStack\fR to true:427.428.IP "" 4429.430.nf431432app\.use(express\.errorHandler({ showStack: true, dumpExceptions: true }));433.434.fi435.436.IP "" 0437.438.P439The \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\.440.441.SS "View Rendering"442View filenames take the form \fINAME\fR\.\fIENGINE\fR, where \fIENGINE\fR is the name of the module that will be required\. For example the view \fIlayout\.ejs\fR will tell the view system to \fIrequire(\'ejs\')\fR, the module being loaded must export the method \fIexports\.render(str, options)\fR to comply with Express, however \fIapp\.register()\fR can be used to map engines to file extensions, so that for example "foo\.html" can be rendered by jade\.443.444.P445Below 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\.446.447.IP "" 4448.449.nf450451app\.get(\'/\', function(req, res){452    res\.render(\'index\.haml\', {453        locals: { title: \'My Site\' }454    });455});456.457.fi458.459.IP "" 0460.461.P462The 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:463.464.IP "" 4465.466.nf467468app\.set(\'view engine\', \'jade\');469.470.fi471.472.IP "" 0473.474.P475Allowing us to render with:476.477.IP "" 4478.479.nf480481res\.render(\'index\');482.483.fi484.485.IP "" 0486.487.P488vs:489.490.IP "" 4491.492.nf493494res\.render(\'index\.jade\');495.496.fi497.498.IP "" 0499.500.P501When \fIview engine\fR is set, extensions are entirely optional, however we can still mix and match template engines:502.503.IP "" 4504.505.nf506507res\.render(\'another\-page\.ejs\');508.509.fi510.511.IP "" 0512.513.P514Express also provides the \fIview options\fR setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:515.516.IP "" 4517.518.nf519520app\.set(\'view options\', {521    layout: false522});523.524.fi525.526.IP "" 0527.528.P529Which can then be overridden within the \fBres\.render()\fR call if need be:530.531.IP "" 4532.533.nf534535res\.render(\'myview\.ejs\', { layout: true });536.537.fi538.539.IP "" 0540.541.P542A good example of this is specifying custom \fIejs\fR opening and closing tags:543.544.IP "" 4545.546.nf547548app\.set(\'view options\', {549    open: \'{{\',550    close: \'}}\'551});552.553.fi554.555.IP "" 0556.557.SS "View Partials"558The 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:559.560.IP "" 4561.562.nf563564partial(\'comment\.haml\', { collection: comments });565.566.fi567.568.IP "" 0569.570.P571To 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\.572.573.IP "" 4574.575.nf576577partial(\'comment\', { collection: comments });578.579.fi580.581.IP "" 0582.583.P584And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:585.586.IP "" 4587.588.nf589590partial(\'comments\', comments);591.592.fi593.594.IP "" 0595.596.P597When using the partial collection support a few "magic" variables are provided for free:598.599.IP "\(bu" 4600\fIfirstInCollection\fR True if this is the first object601.602.IP "\(bu" 4603\fIindexInCollection\fR Index of the object in the collection604.605.IP "\(bu" 4606\fIlastInCollection\fR True if this is the last object607.608.IP "" 0609.610.SS "Template Engines"611Below are a few template engines commonly used with Express:612.613.IP "\(bu" 4614Jade \fIhttp://jade\-lang\.com\fR haml\.js successor615.616.IP "\(bu" 4617Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates618.619.IP "\(bu" 4620EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript621.622.IP "" 0623.624.SS "req\.header(key[, defaultValue])"625Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:626.627.IP "" 4628.629.nf630631req\.header(\'Host\');632req\.header(\'host\');633req\.header(\'Accept\', \'*/*\');634.635.fi636.637.IP "" 0638.639.SS "req\.accepts(type)"640Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.641.642.P643When 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\.644.645.IP "" 4646.647.nf648649// Accept: text/html650req\.accepts(\'html\');651// => true652653// Accept: text/*; application/json654req\.accepts(\'html\');655req\.accepts(\'text/html\');656req\.accepts(\'text/plain\');657req\.accepts(\'application/json\');658// => true659660req\.accepts(\'image/png\');661req\.accepts(\'png\');662// => false663.664.fi665.666.IP "" 0667.668.SS "req\.param(name)"669Return the value of param \fIname\fR when present\.670.671.IP "\(bu" 4672Checks route placeholders (\fIreq\.params\fR), ex: /user/:id673.674.IP "\(bu" 4675Checks query string params (\fIreq\.query\fR), ex: ?id=12676.677.IP "\(bu" 4678Checks urlencoded body params (\fIreq\.body\fR), ex: id=12679.680.IP "" 0681.682.P683To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.684.685.SS "req\.flash(type[, msg])"686Queue flash \fImsg\fR of the given \fItype\fR\.687.688.IP "" 4689.690.nf691692req\.flash(\'info\', \'email sent\');693req\.flash(\'error\', \'email delivery failed\');694req\.flash(\'info\', \'email re\-sent\');695// => 2696697req\.flash(\'info\');698// => [\'email sent\', \'email re\-sent\']699700req\.flash(\'info\');701// => []702703req\.flash();704// => { error: [\'email delivery failed\'], info: [] }705.706.fi707.708.IP "" 0709.710.P711Flash notification message may also utilize formatters, by default only the %s string formatter is available:712.713.IP "" 4714.715.nf716717req\.flash(\'info\', \'email delivery to _%s_ from _%s_ failed\.\', toUser, fromUser);718.719.fi720.721.IP "" 0722.723.SS "req\.isXMLHttpRequest"724Also aliased as \fIreq\.xhr\fR, this getter checks the \fIX\-Requested\-With\fR header to see if it was issued by an \fIXMLHttpRequest\fR:725.726.IP "" 4727.728.nf729730req\.xhr731req\.isXMLHttpRequest732.733.fi734.735.IP "" 0736.737.SS "res\.header(key[, val])"738Get or set the response header \fIkey\fR\.739.740.IP "" 4741.742.nf743744res\.header(\'Content\-Length\');745// => undefined746747res\.header(\'Content\-Length\', 123);748// => 123749750res\.header(\'Content\-Length\');751// => 123752.753.fi754.755.IP "" 0756.757.SS "res\.contentType(type)"758Sets the \fIContent\-Type\fR response header to the given \fItype\fR\.759.760.IP "" 4761.762.nf763764  var filename = \'path/to/image\.png\';765  res\.contentType(filename);766  // res\.headers[\'Content\-Type\'] is now "image/png"767.768.fi769.770.IP "" 0771.772.SS "res\.attachment([filename])"773Sets the \fIContent\-Disposition\fR response header to "attachment", with optional \fIfilename\fR\.774.775.IP "" 4776.777.nf778779  res\.attachment(\'path/to/my/image\.png\');780.781.fi782.783.IP "" 0784.785.SS "res\.sendfile(path)"786Used by \fBres\.download()\fR to transfer an arbitrary file\.787.788.IP "" 4789.790.nf791792res\.sendfile(\'path/to/my\.file\');793.794.fi795.796.IP "" 0797.798.P799This method accepts a callback which when given will be called on an exception, as well as when the transfer has completed\. When a callback is not given, and the file has \fBnot\fR been streamed, \fInext(err)\fR will be called on an exception\.800.801.IP "" 4802.803.nf804805res\.sendfile(path, function(err, path){806  if (err) {807    // handle the error808  } else {809    console\.log(\'transferred %s\', path);810  }811});812.813.fi814.815.IP "" 0816.817.P818When the filesize exceeds the \fIstream threshold\fR (defaulting to 32k), the file will be streamed using \fIfs\.ReadStream\fR and \fIsys\.pump()\fR\.819.820.SS "res\.download(file[, filename])"821Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.822.823.IP "" 4824.825.nf826827res\.download(\'path/to/image\.png\');828res\.download(\'path/to/image\.png\', \'foo\.png\');829.830.fi831.832.IP "" 0833.834.P835This is equivalent to:836.837.IP "" 4838.839.nf840841res\.attachment(file);842res\.sendfile(file);843.844.fi845.846.IP "" 0847.848.SS "res\.send(body|status[, headers|status[, status]])"849The \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:850.851.IP "" 4852.853.nf854855 res\.send(); // 204856 res\.send(new Buffer(\'wahoo\'));857 res\.send({ some: \'json\' });858 res\.send(\'<p>some html</p>\');859 res\.send(\'Sorry, cant find that\', 404);860 res\.send(\'text\', { \'Content\-Type\': \'text/plain\' }, 201);861 res\.send(404);862.863.fi864.865.IP "" 0866.867.P868By 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\.869.870.SS "res\.redirect(url[, status])"871Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.872.873.IP "" 4874.875.nf876877res\.redirect(\'/\', 301);878res\.redirect(\'/account\');879res\.redirect(\'http://google\.com\');880res\.redirect(\'home\');881res\.redirect(\'back\');882.883.fi884.885.IP "" 0886.887.P888Express 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 "/"\.889.890.SS "res\.cookie(name, val[, options])"891Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.892.893.IP "" 4894.895.nf896897// "Remember me" for 15 minutes898res\.cookie(\'rememberme\', \'yes\', { expires: new Date(Date\.now() + 900000), httpOnly: true });899.900.fi901.902.IP "" 0903.904.P905To parse incoming \fICookie\fR headers, use the \fIcookieDecoder\fR middleware, which provides the \fIreq\.cookies\fR object:906.907.IP "" 4908.909.nf910911app\.use(express\.cookieDecoder());912913app\.get(\'/\', function(req, res){914    // use req\.cookies\.rememberme915});916.917.fi918.919.IP "" 0920.921.SS "res\.clearCookie(name)"922Clear cookie \fIname\fR by setting "expires" far in the past\.923.924.IP "" 4925.926.nf927928res\.clearCookie(\'rememberme\');929.930.fi931.932.IP "" 0933.934.SS "res\.render(view[, options[, fn]])"935Render \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\.936.937.P938Most 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:939.940.IP "\(bu" 4941\fIcontext|scope\fR Template evaluation context (\fIthis\fR)942.943.IP "\(bu" 4944\fIlocals\fR Object containing local variables945.946.IP "\(bu" 4947\fIdebug\fR Output debugging information948.949.IP "\(bu" 4950\fIstatus\fR Response status code, defaults to 200951.952.IP "\(bu" 4953\fIheaders\fR Response headers object954.955.IP "" 0956.957.SS "res\.partial(view[, options])"958Render \fIview\fR partial with the given \fIoptions\fR\. This method is always available to the view as a local variable\.959.960.IP "\(bu" 4961\fIas\fR Variable name for each \fIcollection\fR value, defaults to the view name\.962.963.IP "\(bu" 4964as: \'something\' will add the \fIsomething\fR local variable965.966.IP "\(bu" 4967as: this will use the collection value as the template context968.969.IP "\(bu" 4970as: global will merge the collection value\'s properties with \fIlocals\fR971.972.IP "" 0973974.975.IP "\(bu" 4976\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\.977.978.IP "" 0979.980.P981The following are equivalent, and the name of collection value when passed to the partial will be \fImovie\fR as derived from the name\.982.983.IP "" 4984.985.nf986987partial(\'movie\.jade\', { collection: movies });988partial(\'movie\.jade\', movies);989partial(\'movie\', movies);990// In view: movie\.director991.992.fi993.994.IP "" 0995.996.P997To change the local from \fImovie\fR to \fIvideo\fR we can use the "as" option:998.999.IP "" 41000.1001.nf10021003partial(\'movie\', { collection: movies, as: \'video\' });1004// In view: video\.director1005.1006.fi1007.1008.IP "" 01009.1010.P1011Also 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\.1012.1013.IP "" 41014.1015.nf10161017partial(\'movie\', { collection: movies, as: this });1018// In view: this\.director1019.1020.fi1021.1022.IP "" 01023.1024.P1025Another 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:1026.1027.IP "" 41028.1029.nf10301031partials(\'movie\', { collection: movies, as: global });1032// In view: director1033.1034.fi1035.1036.IP "" 01037.1038.SS "app\.set(name[, val])"1039Apply an application level setting \fIname\fR to \fIval\fR, or get the value of \fIname\fR when \fIval\fR is not present:1040.1041.IP "" 41042.1043.nf10441045app\.set(\'views\', __dirname + \'/views\');1046app\.set(\'views\');1047// => \.\.\.path\.\.\.1048.1049.fi1050.1051.IP "" 01052.1053.SS "app\.enable(name)"1054Enable the given setting \fIname\fR:1055.1056.IP "" 41057.1058.nf10591060app\.enable(\'some arbitrary setting\');1061app\.set(\'some arbitrary setting\');1062// => true1063.1064.fi1065.1066.IP "" 01067.1068.SS "app\.disable(name)"1069Disable the given setting \fIname\fR:1070.1071.IP "" 41072.1073.nf10741075app\.disable(\'some setting\');1076app\.set(\'some setting\');1077// => false1078.1079.fi1080.1081.IP "" 01082.1083.SS "app\.configure(env|function[, function])"1084Define a callback function for the given \fIenv\fR (or all environments) with callback \fIfunction\fR:1085.1086.IP "" 41087.1088.nf10891090app\.configure(function(){1091    // executed for each env1092});10931094app\.configure(\'development\', function(){1095    // executed for \'development\' only1096});1097.1098.fi1099.1100.IP "" 01101.1102.SS "app\.redirect(name, val)"1103For use with \fBres\.redirect()\fR we can map redirects at the application level as shown below:1104.1105.IP "" 41106.1107.nf11081109app\.redirect(\'google\', \'http://google\.com\');1110.1111.fi1112.1113.IP "" 01114.1115.P1116Now in a route we may call:1117.1118.P1119res\.redirect(\'google\');1120.1121.P1122We may also map dynamic redirects:1123.1124.IP "" 41125.1126.nf11271128app\.redirect(\'comments\', function(req, res){1129    return \'/post/\' + req\.params\.id + \'/comments\';1130});1131.1132.fi1133.1134.IP "" 01135.1136.P1137So 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\.1138.1139.IP "" 41140.1141.nf11421143app\.get(\'/post/:id\', function(req, res){1144    res\.redirect(\'comments\');1145});1146.1147.fi1148.1149.IP "" 01150.1151.SS "app\.error(function)"1152Adds 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:1153.1154.IP "" 41155.1156.nf11571158app\.error(function(err, req, res, next){1159    res\.send(err\.message, 500);1160});1161.1162.fi1163.1164.IP "" 01165.1166.SS "app\.helpers(obj)"1167Registers static view helpers\.1168.1169.IP "" 41170.1171.nf11721173app\.helpers({1174    name: function(first, last){ return first + \', \' + last },1175    firstName: \'tj\',1176    lastName: \'holowaychuk\'1177});1178.1179.fi1180.1181.IP "" 01182.1183.P1184Our view could now utilize the \fIfirstName\fR and \fIlastName\fR variables, as well as the \fIname()\fR function exposed\.1185.1186.IP "" 41187.1188.nf11891190<%= name(firstName, lastName) %>1191.1192.fi1193.1194.IP "" 01195.1196.SS "app\.dynamicHelpers(obj)"1197Registers dynamic view helpers\. Dynamic view helpers are simply functions which accept \fIreq\fR, \fIres\fR, and are evaluated against the \fIServer\fR instance before a view is rendered\. The \fIreturn value\fR of this function becomes the local variable it is associated with\.1198.1199.IP "" 41200.1201.nf12021203app\.dynamicHelpers({1204    session: function(req, res){1205        return req\.session;1206    }1207});1208.1209.fi1210.1211.IP "" 01212.1213.P1214All views would now have \fIsession\fR available so that session data can be accessed via \fIsession\.name\fR etc:1215.1216.IP "" 41217.1218.nf12191220<%= session\.name %>1221.1222.fi1223.1224.IP "" 01225.1226.SS "app\.mounted(fn)"1227Assign a callback \fIfn\fR which is called when this \fIServer\fR is passed to \fIServer#use()\fR\.1228.1229.IP "" 41230.1231.nf12321233var app = express\.createServer(),1234    blog = express\.createServer();12351236blog\.mounted(function(parent){1237    // parent is app1238    // "this" is blog1239});12401241app\.use(blog);1242.1243.fi1244.1245.IP "" 01246.1247.SS "app\.register(ext, exports)"1248Register the given template engine \fIexports\fR as \fIext\fR\. For example we may wish to map "\.html" files to jade:1249.1250.IP "" 41251.1252.nf12531254 app\.register(\'\.html\', require(\'jade\'));1255.1256.fi1257.1258.IP "" 01259.1260.P1261This is also useful for libraries that may not match extensions correctly\. For example my haml\.js library is installed from npm as "hamljs" so instead of layout\.hamljs, we can register the engine as "\.haml":1262.1263.IP "" 41264.1265.nf12661267 app\.register(\'\.haml\', require(\'haml\-js\'));1268.1269.fi1270.1271.IP "" 01272.1273.P1274For engines that do not comply with the Express specification, we can also wrap their api this way\.1275.1276.IP "" 41277.1278.nf12791280 app\.register(\'\.foo\', {1281     render: function(str, options) {1282         // perhaps their api is1283         // foo\.toHTML(str, options);1284     }1285 });1286.1287.fi1288.1289.IP "" 01290.1291.SS "app\.listen([port[, host]])"1292Bind 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\.1293.1294.IP "" 41295.1296.nf12971298app\.listen();1299app\.listen(3000);1300app\.listen(3000, \'n\.n\.n\.n\');1301.1302.fi1303.1304.IP "" 01305.1306.P1307The \fIport\fR argument may also be a string representing the path to a unix domain socket:1308.1309.IP "" 41310.1311.nf13121313app\.listen(\'/tmp/express\.sock\');1314.1315.fi1316.1317.IP "" 01318.1319.P1320Then try it out:1321.1322.IP "" 41323.1324.nf13251326$ telnet /tmp/express\.sock1327GET / HTTP/1\.113281329HTTP/1\.1 200 OK1330Content\-Type: text/plain1331Content\-Length: 1113321333Hello World1334.1335.fi1336.1337.IP "" 01338