Skip to content
Myr

docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent 9d1b3f5 · Browse files · 3 files+197 added−134 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+197 added−134 removed

  • other:+197 added−134 removed

3 files+197 added−134 removed

modified:docs/guide.1+80 added-47 removed
922 unmodified lines
923.924.IP "" 0925.926.SS "View Partials"927The 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:927The Express view system has built\-in support for partials and collections, which are "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:928.929.IP "" 4930.931.nf932933partial(\'comment\.haml\', { collection: comments });934.935.fi936.937.IP "" 0938.939.P940To 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\.941.942.IP "" 4943.944.nf945933partial(\'comment\', { collection: comments });934.935.fi936.937.IP "" 0938.939.P953And once again even further, when rendering a collection we can simply pass an array, if no other options are desired:940If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:941.942.IP "" 4943.944.nf
7 unmodified lines
952.P953When using the partial collection support a few "magic" variables are provided for free:954.955.IP "\(bu" 4969\fIfirstInCollection\fR True if this is the first object956\fIfirstInCollection\fR true if this is the first object957.958.IP "\(bu" 4972\fIindexInCollection\fR Index of the object in the collection959\fIindexInCollection\fR index of the object in the collection960.961.IP "\(bu" 4975\fIlastInCollection\fR True if this is the last object962\fIlastInCollection\fR true if this is the last object963.964.IP "\(bu" 4978\fIcollectionLength\fR Length of the collection965\fIcollectionLength\fR length of the collection966.967.IP "" 0968.969.P970For documentation on altering the object name view res\.partial() \fIhttp://expressjs\.com/guide\.html#res\-partial\-view\-options\-\fR\.971.972.P986NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead\. For example do \fInot\fR implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates\.973NOTE: be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views\. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead\.974.975.SS "Template Engines"976Below are a few template engines commonly used with Express:977.978.IP "\(bu" 4979Jade \fIhttp://jade\-lang\.com\fR haml\.js successor980.981.IP "\(bu" 4995Haml \fIhttp://github\.com/visionmedia/haml\.js\fR pythonic indented templates996.997.IP "\(bu" 4982EJS \fIhttp://github\.com/visionmedia/ejs\fR Embedded JavaScript983.984.IP "\(bu" 4985CoffeeKup \fIhttp://github\.com/mauricemach/coffeekup\fR CoffeeScript based templating
3 unmodified lines
989.990.IP "" 0991.992.SS "Session Support"1009Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieDecoder\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.993Sessions support can be added by using Connect\'s \fIsession\fR middleware\. To do so we also need the \fIcookieParser\fR middleware place above it, which will parse and populate cookie data to \fIreq\.cookies\fR\.994.995.IP "" 4996.997.nf9981015app\.use(express\.cookieDecoder());1016app\.use(express\.session());999app\.use(express\.cookieParser());1000app\.use(express\.session({ secret: "keyboard cat" }));1001.1002.fi1003.1004.IP "" 0
5 unmodified lines
1010.1011.nf10121013var RedisStore = require(\'connect\-redis\');1030app\.use(express\.cookieDecoder());1031app\.use(express\.session({ store: new RedisStore }));1014app\.use(express\.cookieParser());1015app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));1016.1017.fi1018.1019.IP "" 0
5 unmodified lines
1025.1026.nf10271028var RedisStore = require(\'connect\-redis\');1045app\.use(express\.bodyDecoder());1046app\.use(express\.cookieDecoder());1047app\.use(express\.session({ store: new RedisStore }));1029app\.use(express\.bodyParser());1030app\.use(express\.cookieParser());1031app\.use(express\.session({ secret: "keyboard cat", store: new RedisStore }));10321033app\.post(\'/add\-to\-cart\', function(req, res){1034 // Perhaps we posted several items with a form1051 // (use the bodyDecoder() middleware for this)1035 // (use the bodyParser() middleware for this)1036 var items = req\.body\.items;1037 req\.session\.items = items;1038 res\.redirect(\'back\');1039});
12 unmodified lines
1052.1053.IP "" 01054.1055.P1072The \fIreq\.session\fR object also has methods such as \fISession#touch()\fR, \fISession#destroy()\fR, \fISession#regenerate()\fR among others to maintain and manipulate sessions\. For more information view the Connect Session \fIhttp://senchalabs\.github\.com/connect/session\.html\fR documentation\.1056The \fIreq\.session\fR object also has methods such as \fISession#touch()\fR, \fISession#destroy()\fR, \fISession#regenerate()\fR among others to maintain and manipulate sessions\. For more information view the Connect Session \fIhttp://senchalabs\.github\.com/connect/middleware\-session\.html\fR documentation\.1057.1058.SS "Migration Guide"1075Pre\-beta Express developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.1059Express 1\.x developers may reference the Migration Guide \fImigrate\.html\fR to get up to speed on how to upgrade your application\.1060.1061.SS "req\.header(key[, defaultValue])"1062Get the case\-insensitive request header \fIkey\fR, with optional \fIdefaultValue\fR:1063.
8 unmodified lines
1072.fi1073.1074.IP "" 01075.1076.P1077The \fIReferrer\fR and \fIReferer\fR header fields are special\-cased, either will work:1078.1079.IP "" 41080.1081.nf10821083// sent Referrer: http://google\.com10841085req\.header(\'Referer\');1086// => "http://google\.com"10871088req\.header(\'Referrer\');1089// => "http://google\.com"1090.1091.fi1092.1093.IP "" 01094.1095.SS "req\.accepts(type)"1096Check if the \fIAccept\fR header is present, and includes the given \fItype\fR\.1097.1098.P
112 unmodified lines
1211.SS "req\.param(name[, default])"1212Return the value of param \fIname\fR when present or \fIdefault\fR\.1213.1214.IP "\(bu" 41212Checks route placeholders (\fIreq\.params\fR), ex: /user/:id1215Checks route params (\fIreq\.params\fR), ex: /user/:id1216.1217.IP "\(bu" 41218Checks query string params (\fIreq\.query\fR), ex: ?id=121219.
2 unmodified lines
1222.1223.IP "" 01224.1225.P1223To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the \fIexpress\.bodyDecoder\fR middleware\.1226To utilize urlencoded request bodies, \fIreq\.body\fR should be an object\. This can be done by using the _express\.bodyParser middleware\.1227.1228.SS "req\.flash(type[, msg])"1229Queue flash \fImsg\fR of the given \fItype\fR\.1230.
74 unmodified lines
1305.nf13061307 var filename = \'path/to/image\.png\';1308 res\.contentType(filename);1306 // res\.headers[\'Content\-Type\'] is now "image/png"1309 // Content\-Type is now "image/png"1310.1311.fi1312.1313.IP "" 0
10 unmodified lines
1324.fi1325.1326.IP "" 01327.1325.SS "res\.sendfile(path)"1328.SS "res\.sendfile(path[, options[, callback]])"1329Used by \fBres\.download()\fR to transfer an arbitrary file\.1330.1331.IP "" 41332.
5 unmodified lines
1338.1339.IP "" 01340.1341.P1339This 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\.1342This method accepts an optional callback which is called when an error occurs, or when the transfer is complete\. By default failures call \fBnext(err)\fR, however when a callback is supplied you must do this explicitly, or act on the error\.1343.1344.IP "" 41345.1346.nf13471345res\.sendfile(path, function(err, path){1348res\.sendfile(path, function(err){1349 if (err) {1347 // handle the error1350 next(err);1351 } else {1352 console\.log(\'transferred %s\', path);1353 }1354});
1 unmodified line
1356.fi1357.1358.IP "" 01359.1360.P1361Options may also be passed to the internal \fIfs\.createReadStream()\fR call, for example altering the \fIbufferSize\fR:1362.1363.IP "" 41364.1365.nf13661367res\.sendfile(path, { bufferSize: 1024 }, function(err){1368 // handle1369});1370.1371.fi1372.1373.IP "" 01374.1357.SS "res\.download(file[, filename])"1375.SS "res\.download(file[, filename[, callback]])"1376Transfer the given \fIfile\fR as an attachment with optional alternative \fIfilename\fR\.1377.1378.IP "" 41379.
19 unmodified lines
1399.fi1400.1401.IP "" 01402.1403.P1404An optional callback may be supplied as either the second or third argument, which is passed to \fIres\.sendfile()\fR:1405.1406.IP "" 41407.1408.nf14091410res\.download(path, \'expenses\.doc\', function(err){1411 // handle1412});1413.1414.fi1415.1416.IP "" 01417.1418.SS "res\.send(body|status[, headers|status[, status]])"1386The \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:1419The \fIres\.send()\fR method is a high level response utility allowing you to pass objects to respond with json, strings for html, Buffer instances, or numbers representing the status code\. The following are all valid uses:1420.1421.IP "" 41422.1423.nf
13 unmodified lines
1437.P1438By 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\.1439.1440.P1408Note that this method \fIend()\fR the response, so you will want to use node\'s \fIres\.writeHead()\fR / \fIres\.write()\fR for multiple writes or streaming\.1441Note that this method \fIend()\fRs the response, so you will want to use node\'s \fIres\.write()\fR for multiple writes or streaming\.1442.1443.SS "res\.redirect(url[, status])"1444Redirect to the given \fIurl\fR with a default response \fIstatus\fR of 302\.1445.
14 unmodified lines
1460.P1461Express 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 "/"\.1462.1463.SS "res\.cookie(name, val[, options])"1431Sets the given cookie \fIname\fR to \fIval\fR, with \fIoptions\fR such as "httpOnly: true", "expires", "secure" etc\.1464Sets the given cookie \fIname\fR to \fIval\fR, with options \fIhttpOnly\fR, \fIsecure\fR, \fIexpires\fR etc\.1465.1466.IP "" 41467.1468.nf
11 unmodified lines
1480.IP "" 41481.1482.nf14831451app\.use(express\.cookieDecoder());1484app\.use(express\.cookieParser());14851486app\.get(\'/\', function(req, res){1454 // use req\.cookies\.rememberme1487 // use req\.cookies\.rememberme1488});1489.1490.fi1491.
506 unmodified lines
modified:docs/guide.html+60 added-44 removed
206 unmodified lines
207<li><a href="#" class="toggle">+</a> <a class="section-title" href="#">Response</a><ul class="section" id="section-Response">208<li><a href="#res-header-key-val-">header()</a></li>209<li><a href="#res-contentType-type-">contentType()</a></li>210<li><a href="#res-attachment-filename-">attachment()</a></li>211<li><a href="#res-sendfile-path-">sendfile()</a></li>212<li><a href="#res-download-file-filename-">download()</a></li>211<li><a href="#res-sendfile-path-options-callback-">sendfile()</a></li>212<li><a href="#res-download-file-filename-callback-">download()</a></li>213<li><a href="#res-send-body-status-headers-status-status-">send()</a></li>214<li><a href="#res-redirect-url-status-">redirect()</a></li>215<li><a href="#res-cookie-name-val-options-">cookie()</a></li>216<li><a href="#res-clearCookie-name-">clearCookie()</a></li>
605 unmodified lines
822</code></pre>823824<h3 id="View-Partials">View Partials</h3>825826<p>The Express view system has built-in support for partials and collections, which are827sort of "mini" views representing a document fragment. For example rather than iterating826<p>The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating827in a view to display comments, we would use a partial with collection support:</p>828830<pre><code>partial('comment.haml', { collection: comments });831</code></pre>832833<p>To make things even less verbose we can assume the extension as <em>.haml</em> when omitted,834however if we wished we could use an ejs partial, within a haml view for example.</p>835829<pre><code>partial('comment', { collection: comments });830</code></pre>831839<p>And once again even further, when rendering a collection we can simply pass840an array, if no other options are desired:</p>832<p>If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:</p>833834<pre><code>partial('comment', comments);835</code></pre>836837<p>When using the partial collection support a few "magic" variables are provided838for free:</p>839840<ul>849<li><em>firstInCollection</em> True if this is the first object</li>850<li><em>indexInCollection</em> Index of the object in the collection</li>851<li><em>lastInCollection</em> True if this is the last object</li>852<li><em>collectionLength</em> Length of the collection</li>841<li><em>firstInCollection</em> true if this is the first object</li>842<li><em>indexInCollection</em> index of the object in the collection</li>843<li><em>lastInCollection</em> true if this is the last object</li>844<li><em>collectionLength</em> length of the collection</li>845</ul>846847848<p>For documentation on altering the object name view <a href="http://expressjs.com/guide.html#res-partial-view-options-">res.partial()</a>.</p>849858<p>NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead. For example do <em>not</em> implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates.</p>850<p>NOTE: be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead.</p>851852<h3 id="Template-Engines">Template Engines</h3>853854<p>Below are a few template engines commonly used with Express:</p>855856<ul>857<li><a href="http://jade-lang.com">Jade</a> haml.js successor</li>866<li><a href="http://github.com/visionmedia/haml.js">Haml</a> pythonic indented templates</li>858<li><a href="http://github.com/visionmedia/ejs">EJS</a> Embedded JavaScript</li>859<li><a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a> CoffeeScript based templating</li>860<li><a href="https://github.com/kof/node-jqtpl">jQuery Templates</a> for node</li>861</ul>862863864<h3 id="Session-Support">Session Support</h3>865875<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieDecoder</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>866<p>Sessions support can be added by using Connect's <em>session</em> middleware. To do so we also need the <em>cookieParser</em> middleware place above it, which will parse and populate cookie data to <em>req.cookies</em>.</p>867877<pre><code>app.use(express.cookieDecoder());878app.use(express.session());868<pre><code>app.use(express.cookieParser());869app.use(express.session({ secret: "keyboard cat" }));870</code></pre>871872<p>By default the <em>session</em> middleware uses the memory store bundled with Connect, however many implementations exist. For example <a href="http://github.com/visionmedia/connect-redis">connect-redis</a> supplies a <a href="http://code.google.com/p/redis/">Redis</a> session store and can be used as shown below:</p>873874<pre><code>var RedisStore = require('connect-redis');884app.use(express.cookieDecoder());885app.use(express.session({ store: new RedisStore }));875app.use(express.cookieParser());876app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));877</code></pre>878879<p>Now the <em>req.session</em> and <em>req.sessionStore</em> properties will be accessible to all routes and subsequent middleware. Properties on <em>req.session</em> are automatically saved on a response, so for example if we wish to shopping cart data:</p>880881<pre><code>var RedisStore = require('connect-redis');891app.use(express.bodyDecoder());892app.use(express.cookieDecoder());893app.use(express.session({ store: new RedisStore }));882app.use(express.bodyParser());883app.use(express.cookieParser());884app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));885886app.post('/add-to-cart', function(req, res){887 // Perhaps we posted several items with a form897 // (use the bodyDecoder() middleware for this)888 // (use the bodyParser() middleware for this)889 var items = req.body.items;890 req.session.items = items;891 res.redirect('back');892});
8 unmodified lines
901 res.render('shopping-cart');902});903</code></pre>904914<p>The <em>req.session</em> object also has methods such as <em>Session#touch()</em>, <em>Session#destroy()</em>, <em>Session#regenerate()</em> among others to maintain and manipulate sessions. For more information view the <a href="http://senchalabs.github.com/connect/session.html">Connect Session</a> documentation.</p>905<p>The <em>req.session</em> object also has methods such as <em>Session#touch()</em>, <em>Session#destroy()</em>, <em>Session#regenerate()</em> among others to maintain and manipulate sessions. For more information view the <a href="http://senchalabs.github.com/connect/middleware-session.html">Connect Session</a> documentation.</p>906907<h3 id="Migration-Guide">Migration Guide</h3>908918<p> Pre-beta Express developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application.</p>909<p> Express 1.x developers may reference the <a href="migrate.html">Migration Guide</a> to get up to speed on how to upgrade your application.</p>910911<h3 id="req-header-key-defaultValue-">req.header(key[, defaultValue])</h3>912913<p>Get the case-insensitive request header <em>key</em>, with optional <em>defaultValue</em>:</p>
2 unmodified lines
916req.header('host');917req.header('Accept', '*/*');918</code></pre>919920<p>The <em>Referrer</em> and <em>Referer</em> header fields are special-cased, either will work:</p>921922<pre><code>// sent Referrer: http://google.com923924req.header('Referer');925// =&gt; "http://google.com"926927req.header('Referrer');928// =&gt; "http://google.com"929</code></pre>930931<h3 id="req-accepts-type-">req.accepts(type)</h3>932933<p>Check if the <em>Accept</em> header is present, and includes the given <em>type</em>.</p>934
76 unmodified lines
10111012<p>Return the value of param <em>name</em> when present or <em>default</em>.</p>10131014<ul>1013<li>Checks route placeholders (<em>req.params</em>), ex: /user/:id</li>1015<li>Checks route params (<em>req.params</em>), ex: /user/:id</li>1016<li>Checks query string params (<em>req.query</em>), ex: ?id=12</li>1017<li>Checks urlencoded body params (<em>req.body</em>), ex: id=12</li>1018</ul>101910201021<p>To utilize urlencoded request bodies, <em>req.body</em>1022should be an object. This can be done by using1021the <em>express.bodyDecoder</em> middleware.</p>1023the _express.bodyParser middleware.</p>10241025<h3 id="req-flash-type-msg-">req.flash(type[, msg])</h3>10261027<p>Queue flash <em>msg</em> of the given <em>type</em>.</p>
46 unmodified lines
1074<p>Sets the <em>Content-Type</em> response header to the given <em>type</em>.</p>10751076<pre><code> var filename = 'path/to/image.png';1077 res.contentType(filename);1076 // res.headers['Content-Type'] is now "image/png"1078 // Content-Type is now "image/png"1079</code></pre>10801081<h3 id="res-attachment-filename-">res.attachment([filename])</h3>1082
1 unmodified line
10841085<pre><code> res.attachment('path/to/my/image.png');1086</code></pre>10871086<h3 id="res-sendfile-path-">res.sendfile(path)</h3>1088<h3 id="res-sendfile-path-options-callback-">res.sendfile(path[, options[, callback]])</h3>10891090<p>Used by <code>res.download()</code> to transfer an arbitrary file.</p>10911092<pre><code>res.sendfile('path/to/my.file');1093</code></pre>10941093<p>This 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 <strong>not</strong> been streamed, <em>next(err)</em> will be called on an exception.</p>1095<p>This method accepts an optional callback which is called when1096an error occurs, or when the transfer is complete. By default failures call <code>next(err)</code>, however when a callback is supplied you must do this explicitly, or act on the error.</p>10971095<pre><code>res.sendfile(path, function(err, path){1098<pre><code>res.sendfile(path, function(err){1099 if (err) {1097 // handle the error1100 next(err);1101 } else {1102 console.log('transferred %s', path);1103 }1104});1105</code></pre>11061104<h3 id="res-download-file-filename-">res.download(file[, filename])</h3>1107<p>Options may also be passed to the internal <em>fs.createReadStream()</em> call, for example altering the <em>bufferSize</em>:</p>11081109<pre><code>res.sendfile(path, { bufferSize: 1024 }, function(err){1110 // handle1111});1112</code></pre>11131114<h3 id="res-download-file-filename-callback-">res.download(file[, filename[, callback]])</h3>11151116<p>Transfer the given <em>file</em> as an attachment with optional alternative <em>filename</em>.</p>11171118<pre><code>res.download('path/to/image.png');1119res.download('path/to/image.png', 'foo.png');
4 unmodified lines
1124<pre><code>res.attachment(file);1125res.sendfile(file);1126</code></pre>11271128<p>An optional callback may be supplied as either the second or third argument, which is passed to <em>res.sendfile()</em>:</p>11291130<pre><code>res.download(path, 'expenses.doc', function(err){1131 // handle1132});1133</code></pre>11341135<h3 id="res-send-body-status-headers-status-status-">res.send(body|status[, headers|status[, status]])</h3>11361120<p>The <code>res.send()</code> method is a high level response utility allowing you to pass1121objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status1122code based responses. The following are all valid uses:</p>1137<p>The <em>res.send()</em> method is a high level response utility allowing you to pass1138objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:</p>11391140<pre><code> res.send(); // 2041141 res.send(new Buffer('wahoo'));1142 res.send({ some: 'json' });
6 unmodified lines
1149<p>By default the <em>Content-Type</em> response header is set, however if explicitly1150assigned through <code>res.send()</code> or previously with <code>res.header()</code> or <code>res.contentType()</code>1151it will not be set again.</p>11521137<p>Note that this method <em>end()</em> the response, so you will want to use node's <em>res.writeHead()</em> / <em>res.write()</em> for multiple writes or streaming.</p>1153<p>Note that this method <em>end()</em>s the response, so you will want to use node's <em>res.write()</em> for multiple writes or streaming.</p>11541155<h3 id="res-redirect-url-status-">res.redirect(url[, status])</h3>11561157<p>Redirect to the given <em>url</em> with a default response <em>status</em> of 302.</p>
10 unmodified lines
1168the "home" setting and defaults to "/".</p>11691170<h3 id="res-cookie-name-val-options-">res.cookie(name, val[, options])</h3>11711156<p>Sets the given cookie <em>name</em> to <em>val</em>, with <em>options</em> such as "httpOnly: true", "expires", "secure" etc.</p>1172<p>Sets the given cookie <em>name</em> to <em>val</em>, with options <em>httpOnly</em>, <em>secure</em>, <em>expires</em> etc.</p>11731174<pre><code>// "Remember me" for 15 minutes 1175res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });1176</code></pre>11771178<p>To parse incoming <em>Cookie</em> headers, use the <em>cookieDecoder</em> middleware, which provides the <em>req.cookies</em> object:</p>11791164<pre><code>app.use(express.cookieDecoder());1180<pre><code>app.use(express.cookieParser());11811182app.get('/', function(req, res){1167 // use req.cookies.rememberme1183 // use req.cookies.rememberme1184});1185</code></pre>11861187<h3 id="res-clearCookie-name-">res.clearCookie(name)</h3>
316 unmodified lines
modified:docs/guide.md+57 added-43 removed
520 unmodified lines
521 });522523### View Partials524525The Express view system has built-in support for partials and collections, which are526sort of "mini" views representing a document fragment. For example rather than iterating525The Express view system has built-in support for partials and collections, which are "mini" views representing a document fragment. For example rather than iterating526in a view to display comments, we would use a partial with collection support:527529 partial('comment.haml', { collection: comments });530531To make things even less verbose we can assume the extension as _.haml_ when omitted,532however if we wished we could use an ejs partial, within a haml view for example.533528 partial('comment', { collection: comments });529536And once again even further, when rendering a collection we can simply pass537an array, if no other options are desired:530If no other options are desired, we can omit the object and simply pass our array, which is equivalent to above:531532 partial('comment', comments);533534When using the partial collection support a few "magic" variables are provided535for free:536544 * _firstInCollection_ True if this is the first object545 * _indexInCollection_ Index of the object in the collection546 * _lastInCollection_ True if this is the last object547 * _collectionLength_ Length of the collection537 * _firstInCollection_ true if this is the first object538 * _indexInCollection_ index of the object in the collection539 * _lastInCollection_ true if this is the last object540 * _collectionLength_ length of the collection541542For documentation on altering the object name view [res.partial()](http://expressjs.com/guide.html#res-partial-view-options-).543551NOTE: partials are not recommended for large collections (150+) because the view system adds to the overhead. For example do _not_ implement a simple ul list with partial collection support, simply create a partial and iterate within that single partial, as this is far more efficient than rendering 150+ templates.544NOTE: be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead.545546### Template Engines547548Below are a few template engines commonly used with Express:549550 * [Jade](http://jade-lang.com) haml.js successor558 * [Haml](http://github.com/visionmedia/haml.js) pythonic indented templates551 * [EJS](http://github.com/visionmedia/ejs) Embedded JavaScript552 * [CoffeeKup](http://github.com/mauricemach/coffeekup) CoffeeScript based templating553 * [jQuery Templates](https://github.com/kof/node-jqtpl) for node554555### Session Support556565Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieDecoder_ middleware place above it, which will parse and populate cookie data to _req.cookies_.557Sessions support can be added by using Connect's _session_ middleware. To do so we also need the _cookieParser_ middleware place above it, which will parse and populate cookie data to _req.cookies_.558567 app.use(express.cookieDecoder());568 app.use(express.session());559 app.use(express.cookieParser());560 app.use(express.session({ secret: "keyboard cat" }));561562By default the _session_ middleware uses the memory store bundled with Connect, however many implementations exist. For example [connect-redis](http://github.com/visionmedia/connect-redis) supplies a [Redis](http://code.google.com/p/redis/) session store and can be used as shown below:563564 var RedisStore = require('connect-redis');573 app.use(express.cookieDecoder());574 app.use(express.session({ store: new RedisStore }));565 app.use(express.cookieParser());566 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));567568Now the _req.session_ and _req.sessionStore_ properties will be accessible to all routes and subsequent middleware. Properties on _req.session_ are automatically saved on a response, so for example if we wish to shopping cart data:569570 var RedisStore = require('connect-redis');579 app.use(express.bodyDecoder());580 app.use(express.cookieDecoder());581 app.use(express.session({ store: new RedisStore }));571 app.use(express.bodyParser());572 app.use(express.cookieParser());573 app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));574575 app.post('/add-to-cart', function(req, res){576 // Perhaps we posted several items with a form585 // (use the bodyDecoder() middleware for this)577 // (use the bodyParser() middleware for this)578 var items = req.body.items;579 req.session.items = items;580 res.redirect('back');581 });
7 unmodified lines
589 }590 res.render('shopping-cart');591 });592601The _req.session_ object also has methods such as _Session#touch()_, _Session#destroy()_, _Session#regenerate()_ among others to maintain and manipulate sessions. For more information view the [Connect Session](http://senchalabs.github.com/connect/session.html) documentation.593The _req.session_ object also has methods such as _Session#touch()_, _Session#destroy()_, _Session#regenerate()_ among others to maintain and manipulate sessions. For more information view the [Connect Session](http://senchalabs.github.com/connect/middleware-session.html) documentation.594595### Migration Guide596605 Pre-beta Express developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.597 Express 1.x developers may reference the [Migration Guide](migrate.html) to get up to speed on how to upgrade your application.598599### req.header(key[, defaultValue])600601Get the case-insensitive request header _key_, with optional _defaultValue_:
1 unmodified line
603 req.header('Host');604 req.header('host');605 req.header('Accept', '*/*');606607The _Referrer_ and _Referer_ header fields are special-cased, either will work:608609 // sent Referrer: http://google.com610611 req.header('Referer');612 // => "http://google.com"613614 req.header('Referrer');615 // => "http://google.com"616617### req.accepts(type)618619Check if the _Accept_ header is present, and includes the given _type_.620
69 unmodified lines
690### req.param(name[, default])691692Return the value of param _name_ when present or _default_.693692 - Checks route placeholders (_req.params_), ex: /user/:id694 - Checks route params (_req.params_), ex: /user/:id695 - Checks query string params (_req.query_), ex: ?id=12696 - Checks urlencoded body params (_req.body_), ex: id=12697698To utilize urlencoded request bodies, _req.body_699should be an object. This can be done by using698the _express.bodyDecoder_ middleware.700the _express.bodyParser middleware.701702### req.flash(type[, msg])703704Queue flash _msg_ of the given _type_.
30 unmodified lines
735736 res.header('Content-Length');737 // => undefined738737 res.header('Content-Length', 123);739 res.header('Content-Length', 123);740 // => 123739741 742 res.header('Content-Length');743 // => 123744745### res.contentType(type)
1 unmodified line
747Sets the _Content-Type_ response header to the given _type_.748749 var filename = 'path/to/image.png';750 res.contentType(filename);749 // res.headers['Content-Type'] is now "image/png"751 // Content-Type is now "image/png"752753### res.attachment([filename])754755Sets the _Content-Disposition_ response header to "attachment", with optional _filename_.756757 res.attachment('path/to/my/image.png');758757### res.sendfile(path)759### res.sendfile(path[, options[, callback]])760761Used by `res.download()` to transfer an arbitrary file. 762763 res.sendfile('path/to/my.file');764763This 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 __not__ been streamed, _next(err)_ will be called on an exception.765This method accepts an optional callback which is called when766an error occurs, or when the transfer is complete. By default failures call `next(err)`, however when a callback is supplied you must do this explicitly, or act on the error.767765 res.sendfile(path, function(err, path){768 res.sendfile(path, function(err){769 if (err) {767 // handle the error770 next(err);771 } else {772 console.log('transferred %s', path);773 }774 });775773### res.download(file[, filename])776Options may also be passed to the internal _fs.createReadStream()_ call, for example altering the _bufferSize_:777778 res.sendfile(path, { bufferSize: 1024 }, function(err){779 // handle780 });781782### res.download(file[, filename[, callback]])783784Transfer the given _file_ as an attachment with optional alternative _filename_.785786 res.download('path/to/image.png');787 res.download('path/to/image.png', 'foo.png');
2 unmodified lines
790791 res.attachment(file);792 res.sendfile(file);793794An optional callback may be supplied as either the second or third argument, which is passed to _res.sendfile()_:795796 res.download(path, 'expenses.doc', function(err){797 // handle798 });799800### res.send(body|status[, headers|status[, status]])801787The `res.send()` method is a high level response utility allowing you to pass788objects to respond with json, strings for html, arbitrary _Buffer_s or numbers for status789code based responses. The following are all valid uses:802The _res.send()_ method is a high level response utility allowing you to pass803objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:804805 res.send(); // 204806 res.send(new Buffer('wahoo'));807 res.send({ some: 'json' });
5 unmodified lines
813By default the _Content-Type_ response header is set, however if explicitly814assigned through `res.send()` or previously with `res.header()` or `res.contentType()`815it will not be set again.816803Note that this method _end()_ the response, so you will want to use node's _res.writeHead()_ / _res.write()_ for multiple writes or streaming.817Note that this method _end()_s the response, so you will want to use node's _res.write()_ for multiple writes or streaming.818819### res.redirect(url[, status])820821Redirect to the given _url_ with a default response _status_ of 302.
9 unmodified lines
831the "home" setting and defaults to "/".832833### res.cookie(name, val[, options])834821Sets the given cookie _name_ to _val_, with _options_ such as "httpOnly: true", "expires", "secure" etc.835Sets the given cookie _name_ to _val_, with options _httpOnly_, _secure_, _expires_ etc.836837 // "Remember me" for 15 minutes 838 res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });839840To parse incoming _Cookie_ headers, use the _cookieDecoder_ middleware, which provides the _req.cookies_ object:841828 app.use(express.cookieDecoder());842 app.use(express.cookieParser());843 844 app.get('/', function(req, res){831 // use req.cookies.rememberme845 // use req.cookies.rememberme846 });847848### res.clearCookie(name)849
272 unmodified lines