response.js
This file
Path
lib/response.js
780 lines · 17.8 KiB · JavaScript
Last changed by
Include ETag in HEAD requestsTiago Relvaobefore adoption3c7310e
History of this fileTake it
The walk stopped after 200 commits: lines older than 26802a6 point at it.
fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 1–4why, one step back1/**2 * Module dependencies.3 */4move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 5–11why, one step back5var http = require('http');6var path = require('path');7var mixin = require('utils-merge');8var escapeHtml = require('escape-html');9var sign = require('cookie-signature').sign;10var normalizeType = require('./utils').normalizeType;11var normalizeTypes = require('./utils').normalizeTypes;Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9
line 12why, one step back12var contentDisposition = require('./utils').contentDisposition;move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 13–19why, one step back13var etag = require('./utils').etag;14var statusCodes = http.STATUS_CODES;15var cookie = require('cookie');16var send = require('send');17var basename = path.basename;18var extname = path.extname;19var mime = send.mime;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 20–57why, one step back2021/**22 * Response prototype.23 */2425var res = module.exports = {26 __proto__: http.ServerResponse.prototype27};2829/**30 * Set status `code`.31 *32 * @param {Number} code33 * @return {ServerResponse}34 * @api public35 */3637res.status = function(code){38 this.statusCode = code;39 return this;40};4142/**43 * Set Link header field with the given `links`.44 *45 * Examples:46 *47 * res.links({48 * next: 'http://api.example.com/users?page=2',49 * last: 'http://api.example.com/users?page=5'50 * });51 *52 * @param {Object} links53 * @return {ServerResponse}54 * @api public55 */5657res.links = function(links){refactor res.links()TJ Holowaychukbefore adoption8e2f538
lines 58–60why, one step back58 var link = this.get('Link') || '';59 if (link) link += ', ';60 return this.set('Link', link + Object.keys(links).map(function(rel){fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 61–86why, one step back61 return '<' + links[rel] + '>; rel="' + rel + '"';62 }).join(', '));63};6465/**66 * Send a response.67 *68 * Examples:69 *70 * res.send(new Buffer('wahoo'));71 * res.send({ some: 'json' });72 * res.send('<p>some html</p>');73 * res.send(404, 'Sorry, cant find that');74 * res.send(404);75 *76 * @param {Mixed} body or status77 * @param {Mixed} body78 * @return {ServerResponse}79 * @api public80 */8182res.send = function(body){83 var req = this.req;84 var head = 'HEAD' == req.method;85 var len;86Merge pull request #1694 from kavu/add_disable_etagTJ Holowaychukbefore adoption610e172
lines 87–89why, one step back87 // settings88 var app = this.app;89fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 90–109why, one step back90 // allow status / body91 if (2 == arguments.length) {92 // res.send(body, status) backwards compat93 if ('number' != typeof body && 'number' == typeof arguments[1]) {94 this.statusCode = arguments[1];95 } else {96 this.statusCode = body;97 body = arguments[1];98 }99 }100101 switch (typeof body) {102 // response status103 case 'number':104 this.get('Content-Type') || this.type('txt');105 this.statusCode = body;106 body = http.STATUS_CODES[body];107 break;108 // string defaulting to html109 case 'string':remove res.charset usageJonathan Ongbefore adoption2064f41
line 110why, one step back110 if (!this.get('Content-Type')) this.type('html');fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 111–132why, one step back111 break;112 case 'boolean':113 case 'object':114 if (null == body) {115 body = '';116 } else if (Buffer.isBuffer(body)) {117 this.get('Content-Type') || this.type('bin');118 } else {119 return this.json(body);120 }121 break;122 }123124 // populate Content-Length125 if (undefined !== body && !this.get('Content-Length')) {126 this.set('Content-Length', len = Buffer.isBuffer(body)127 ? body.length128 : Buffer.byteLength(body));129 }130131 // ETag support132 // TODO: W/ supportInclude ETag in HEAD requestsTiago Relvaobefore adoption3c7310e
line 133why, one step back133 if (app.settings.etag && len && ('GET' == req.method || 'HEAD' == req.method)) {fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 134–236why, one step back134 if (!this.get('ETag')) {135 this.set('ETag', etag(body));136 }137 }138139 // freshness140 if (req.fresh) this.statusCode = 304;141142 // strip irrelevant headers143 if (204 == this.statusCode || 304 == this.statusCode) {144 this.removeHeader('Content-Type');145 this.removeHeader('Content-Length');146 this.removeHeader('Transfer-Encoding');147 body = '';148 }149150 // respond151 this.end(head ? null : body);152 return this;153};154155/**156 * Send JSON response.157 *158 * Examples:159 *160 * res.json(null);161 * res.json({ user: 'tj' });162 * res.json(500, 'oh noes!');163 * res.json(404, 'I dont have that');164 *165 * @param {Mixed} obj or status166 * @param {Mixed} obj167 * @return {ServerResponse}168 * @api public169 */170171res.json = function(obj){172 // allow status / body173 if (2 == arguments.length) {174 // res.json(body, status) backwards compat175 if ('number' == typeof arguments[1]) {176 this.statusCode = arguments[1];177 } else {178 this.statusCode = obj;179 obj = arguments[1];180 }181 }182183 // settings184 var app = this.app;185 var replacer = app.get('json replacer');186 var spaces = app.get('json spaces');187 var body = JSON.stringify(obj, replacer, spaces);188189 // content-type190 this.get('Content-Type') || this.set('Content-Type', 'application/json');191192 return this.send(body);193};194195/**196 * Send JSON response with JSONP callback support.197 *198 * Examples:199 *200 * res.jsonp(null);201 * res.jsonp({ user: 'tj' });202 * res.jsonp(500, 'oh noes!');203 * res.jsonp(404, 'I dont have that');204 *205 * @param {Mixed} obj or status206 * @param {Mixed} obj207 * @return {ServerResponse}208 * @api public209 */210211res.jsonp = function(obj){212 // allow status / body213 if (2 == arguments.length) {214 // res.json(body, status) backwards compat215 if ('number' == typeof arguments[1]) {216 this.statusCode = arguments[1];217 } else {218 this.statusCode = obj;219 obj = arguments[1];220 }221 }222223 // settings224 var app = this.app;225 var replacer = app.get('json replacer');226 var spaces = app.get('json spaces');227 var body = JSON.stringify(obj, replacer, spaces)228 .replace(/\u2028/g, '\\u2028')229 .replace(/\u2029/g, '\\u2029');230 var callback = this.req.query[app.get('jsonp callback name')];231232 // content-type233 this.set('Content-Type', 'application/json');234235 // jsonp236 if (callback) {Merge pull request #1711 from jonjenkins/masterTJ Holowaychukbefore adoption3ea7381
line 237why, one step back237 if (Array.isArray(callback)) callback = callback[0];fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 238–239why, one step back238 this.set('Content-Type', 'text/javascript');239 var cb = callback.replace(/[^\[\]\w$.]/g, '');Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionbd8b9f5
line 240why, one step back240 body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 241–258why, one step back241 }242243 return this.send(body);244};245246/**247 * Transfer the file at the given `path`.248 *249 * Automatically sets the _Content-Type_ response header field.250 * The callback `fn(err)` is invoked when the transfer is complete251 * or when an error occurs. Be sure to check `res.sentHeader`252 * if you wish to attempt responding, as the header and some data253 * may have already been transferred.254 *255 * Options:256 *257 * - `maxAge` defaulting to 0258 * - `root` root directory for relative filenamesPass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
line 259why, one step back259 * - `hidden` serve hidden files, defaulting to falsefix package.json conflictTJ Holowaychukbefore adoption26802a6
line 260why, one step back260 *Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
lines 261–262why, one step back261 * Other options are passed along to `send`.262 *fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 263–289why, one step back263 * Examples:264 *265 * The following example illustrates how `res.sendfile()` may266 * be used as an alternative for the `static()` middleware for267 * dynamic situations. The code backing `res.sendfile()` is actually268 * the same code, so HTTP cache support etc is identical.269 *270 * app.get('/user/:uid/photos/:file', function(req, res){271 * var uid = req.params.uid272 * , file = req.params.file;273 *274 * req.user.mayViewFilesFrom(uid, function(yes){275 * if (yes) {276 * res.sendfile('/uploads/' + uid + '/' + file);277 * } else {278 * res.send(403, 'Sorry! you cant see that.');279 * }280 * });281 * });282 *283 * @param {String} path284 * @param {Object|Function} options or fn285 * @param {Function} fn286 * @api public287 */288289res.sendfile = function(path, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 290–294why, one step back290 options = options || {};291 var self = this;292 var req = self.req;293 var next = this.req.next;294 var done;fix package.json conflictTJ Holowaychukbefore adoption26802a6
line 295why, one step back295Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
line 296why, one step back296fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 297–312why, one step back297 // support function as second arg298 if ('function' == typeof options) {299 fn = options;300 options = {};301 }302303 // socket errors304 req.socket.on('error', error);305306 // errors307 function error(err) {308 if (done) return;309 done = true;310311 // clean up312 cleanup();remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289
line 313why, one step back313 if (!self.headersSent) self.removeHeader('Content-Disposition');fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 314–318why, one step back314315 // callback available316 if (fn) return fn(err);317318 // list in limbo if there's no callbackremove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289
line 319why, one step back319 if (self.headersSent) return;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 320–325why, one step back320321 // delegate322 next(err);323 }324325 // streamingMerge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption0b88208
line 326why, one step back326 function stream(stream) {fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 327–328why, one step back327 if (done) return;328 cleanup();Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption0b88208
line 329why, one step back329 if (fn) stream.on('end', fn);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 330–336why, one step back330 }331332 // cleanup333 function cleanup() {334 req.socket.removeListener('error', error);335 }336Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
lines 337–339why, one step back337 // Back-compat338 options.maxage = options.maxage || options.maxAge || 0;339fix package.json conflictTJ Holowaychukbefore adoption26802a6
line 340why, one step back340 // transferPass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
line 341why, one step back341 var file = send(req, path, options);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 342–354why, one step back342 file.on('error', error);343 file.on('directory', next);344 file.on('stream', stream);345 file.pipe(this);346 this.on('finish', cleanup);347};348349/**350 * Transfer the file at the given `path` as an attachment.351 *352 * Optionally providing an alternate attachment `filename`,353 * and optional callback `fn(err)`. The callback is invoked354 * when the data transfer is complete, or when an error hasremove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289
line 355why, one step back355 * ocurred. Be sure to check `res.headersSent` if you plan to respond.fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 356–372why, one step back356 *357 * This method uses `res.sendfile()`.358 *359 * @param {String} path360 * @param {String|Function} filename or fn361 * @param {Function} fn362 * @api public363 */364365res.download = function(path, filename, fn){366 // support function as second arg367 if ('function' == typeof filename) {368 fn = filename;369 filename = null;370 }371372 filename = filename || path;Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9
line 373why, one step back373 this.set('Content-Disposition', contentDisposition(filename));fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 374–458why, one step back374 return this.sendfile(path, fn);375};376377/**378 * Set _Content-Type_ response header with `type` through `mime.lookup()`379 * when it does not contain "/", or set the Content-Type to `type` otherwise.380 *381 * Examples:382 *383 * res.type('.html');384 * res.type('html');385 * res.type('json');386 * res.type('application/json');387 * res.type('png');388 *389 * @param {String} type390 * @return {ServerResponse} for chaining391 * @api public392 */393394res.contentType =395res.type = function(type){396 return this.set('Content-Type', ~type.indexOf('/')397 ? type398 : mime.lookup(type));399};400401/**402 * Respond to the Acceptable formats using an `obj`403 * of mime-type callbacks.404 *405 * This method uses `req.accepted`, an array of406 * acceptable types ordered by their quality values.407 * When "Accept" is not present the _first_ callback408 * is invoked, otherwise the first match is used. When409 * no match is performed the server responds with410 * 406 "Not Acceptable".411 *412 * Content-Type is set for you, however if you choose413 * you may alter this within the callback using `res.type()`414 * or `res.set('Content-Type', ...)`.415 *416 * res.format({417 * 'text/plain': function(){418 * res.send('hey');419 * },420 *421 * 'text/html': function(){422 * res.send('<p>hey</p>');423 * },424 *425 * 'appliation/json': function(){426 * res.send({ message: 'hey' });427 * }428 * });429 *430 * In addition to canonicalized MIME types you may431 * also use extnames mapped to these types:432 *433 * res.format({434 * text: function(){435 * res.send('hey');436 * },437 *438 * html: function(){439 * res.send('<p>hey</p>');440 * },441 *442 * json: function(){443 * res.send({ message: 'hey' });444 * }445 * });446 *447 * By default Express passes an `Error`448 * with a `.status` of 406 to `next(err)`449 * if a match is not made. If you provide450 * a `.default` callback it will be invoked451 * instead.452 *453 * @param {Object} obj454 * @return {ServerResponse} for chaining455 * @api public456 */457458res.format = function(obj){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 459–460why, one step back459 var req = this.req;460 var next = req.next;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 461–467why, one step back461462 var fn = obj.default;463 if (fn) delete obj.default;464 var keys = Object.keys(obj);465466 var key = req.accepts(keys);467add res.vary(). Closes #1682cjihrigbefore adoptione5de08f
line 468why, one step back468 this.vary("Accept");fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 469–470why, one step back469470 if (key) {remove res.charset usageJonathan Ongbefore adoption2064f41
line 471why, one step back471 this.set('Content-Type', normalizeType(key).value);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 472–494why, one step back472 obj[key](req, this, next);473 } else if (fn) {474 fn();475 } else {476 var err = new Error('Not Acceptable');477 err.status = 406;478 err.types = normalizeTypes(keys).map(function(o){ return o.value });479 next(err);480 }481482 return this;483};484485/**486 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.487 *488 * @param {String} filename489 * @return {ServerResponse}490 * @api public491 */492493res.attachment = function(filename){494 if (filename) this.type(extname(filename));Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9
line 495why, one step back495 this.set('Content-Disposition', contentDisposition(filename));fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 496–521why, one step back496 return this;497};498499/**500 * Set header `field` to `val`, or pass501 * an object of header fields.502 *503 * Examples:504 *505 * res.set('Foo', ['bar', 'baz']);506 * res.set('Accept', 'application/json');507 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });508 *509 * Aliased as `res.header()`.510 *511 * @param {String|Object|Array} field512 * @param {String} val513 * @return {ServerResponse} for chaining514 * @api public515 */516517res.set =518res.header = function(field, val){519 if (2 == arguments.length) {520 if (Array.isArray(val)) val = val.map(String);521 else val = String(val);preserve casing of headers in res.header and res.setDouglas Christopher Wilsonbefore adoption1536a21
line 522why, one step back522 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 523–525why, one step back523 var charset = mime.charsets.lookup(val.split(';')[0]);524 if (charset) val += '; charset=' + charset.toLowerCase();525 }fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 526–558why, one step back526 this.setHeader(field, val);527 } else {528 for (var key in field) {529 this.set(key, field[key]);530 }531 }532 return this;533};534535/**536 * Get value for header `field`.537 *538 * @param {String} field539 * @return {String}540 * @api public541 */542543res.get = function(field){544 return this.getHeader(field);545};546547/**548 * Clear cookie `name`.549 *550 * @param {String} name551 * @param {Object} options552 * @param {ServerResponse} for chaining553 * @api public554 */555556res.clearCookie = function(name, options){557 var opts = { expires: new Date(1), path: '/' };558 return this.cookie(name, '', optionsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 559why, one step back559 ? mixin(opts, options)fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 560–586why, one step back560 : opts);561};562563/**564 * Set cookie `name` to `val`, with the given `options`.565 *566 * Options:567 *568 * - `maxAge` max-age in milliseconds, converted to `expires`569 * - `signed` sign the cookie570 * - `path` defaults to "/"571 *572 * Examples:573 *574 * // "Remember Me" for 15 minutes575 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });576 *577 * // save as above578 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })579 *580 * @param {String} name581 * @param {String|Object} val582 * @param {Options} options583 * @api public584 */585586res.cookie = function(name, val, options){use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 587why, one step back587 options = mixin({}, options);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 588–589why, one step back588 var secret = this.req.secret;589 var signed = options.signed;remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
line 590why, one step back590 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 591–598why, one step back591 if ('number' == typeof val) val = val.toString();592 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);593 if (signed) val = 's:' + sign(val, secret);594 if ('maxAge' in options) {595 options.expires = new Date(Date.now() + options.maxAge);596 options.maxAge /= 1000;597 }598 if (null == options.path) options.path = '/';move support for multiple `res.cookie` calls to lib/responseRoman Shtylmanbefore adoptiond42d8f5
lines 599–610why, one step back599 var headerVal = cookie.serialize(name, String(val), options);600601 // supports multiple 'res.cookie' calls by getting previous value602 var prev = this.get('Set-Cookie');603 if (prev) {604 if (Array.isArray(prev)) {605 headerVal = prev.concat(headerVal);606 } else {607 headerVal = [prev, headerVal];608 }609 }610 this.set('Set-Cookie', headerVal);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 611–617why, one step back611 return this;612};613614615/**616 * Set the location header to `url`.617 *Merge pull request #1829 from michaelficarra/patch-1TJ Holowaychukbefore adoptionde54af4
line 618why, one step back618 * The given `url` can also be "back", which redirectsfix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 619–624why, one step back619 * to the _Referrer_ or _Referer_ headers or "/".620 *621 * Examples:622 *623 * res.location('/foo/bar').;624 * res.location('http://example.com');res.location: remove resolving relative urlsJonathan Ongbefore adoptionaac1d52
line 625why, one step back625 * res.location('../login');fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 626–631why, one step back626 *627 * @param {String} url628 * @api public629 */630631res.location = function(url){res.location: remove resolving relative urlsJonathan Ongbefore adoptionaac1d52
line 632why, one step back632 var req = this.req;fix package.json conflictTJ Holowaychukbefore adoption26802a6
line 633why, one step back633Merge pull request #1829 from michaelficarra/patch-1TJ Holowaychukbefore adoptionde54af4
line 634why, one step back634 // "back" is an alias for the referrerocdTJ Holowaychukbefore adoption8a7a695
line 635why, one step back635 if ('back' == url) url = req.get('Referrer') || '/';fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 636–663why, one step back636637 // Respond638 this.set('Location', url);639 return this;640};641642/**643 * Redirect to the given `url` with optional response `status`644 * defaulting to 302.645 *646 * The resulting `url` is determined by `res.location()`, so647 * it will play nicely with mounted apps, relative paths,648 * `"back"` etc.649 *650 * Examples:651 *652 * res.redirect('/foo/bar');653 * res.redirect('http://example.com');654 * res.redirect(301, 'http://example.com');655 * res.redirect('http://example.com', 301);656 * res.redirect('../login'); // /blog/post/1 -> /blog/login657 *658 * @param {String} url659 * @param {Number} code660 * @api public661 */662663res.redirect = function(url){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 664–666why, one step back664 var head = 'HEAD' == this.req.method;665 var status = 302;666 var body;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 667–688why, one step back667668 // allow status / url669 if (2 == arguments.length) {670 if ('number' == typeof url) {671 status = url;672 url = arguments[1];673 } else {674 status = arguments[1];675 }676 }677678 // Set location header679 this.location(url);680 url = this.get('Location');681682 // Support text/{plain,html} by default683 this.format({684 text: function(){685 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);686 },687688 html: function(){use escape-html module to escape htmlRoman Shtylmanbefore adoption63c6a9c
line 689why, one step back689 var u = escapeHtml(url);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 690–701why, one step back690 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';691 },692693 default: function(){694 body = '';695 }696 });697698 // Respond699 this.statusCode = status;700 this.set('Content-Length', Buffer.byteLength(body));701 this.end(head ? null : body);add res.vary(). Closes #1682cjihrigbefore adoptione5de08f
lines 702–728why, one step back702};703704/**705 * Add `field` to Vary. If already present in the Vary set, then706 * this call is simply ignored.707 *708 * @param {Array|String} field709 * @param {ServerResponse} for chaining710 * @api public711 */712713res.vary = function(field){714 var self = this;715716 // nothing717 if (!field) return this;718719 // array720 if (Array.isArray(field)) {721 field.forEach(function(field){722 self.vary(field);723 });724 return;725 }726727 var vary = this.get('Vary');728Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionbd8b9f5
line 729why, one step back729 // appendadd res.vary(). Closes #1682cjihrigbefore adoptione5de08f
lines 730–739why, one step back730 if (vary) {731 vary = vary.split(/ *, */);732 if (!~vary.indexOf(field)) vary.push(field);733 this.set('Vary', vary.join(', '));734 return this;735 }736737 // set738 this.set('Vary', field);739 return this;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 740–758why, one step back740};741742/**743 * Render `view` with the given `options` and optional callback `fn`.744 * When a callback function is given a response will _not_ be made745 * automatically, otherwise a response of _200_ and _text/html_ is given.746 *747 * Options:748 *749 * - `cache` boolean hinting to the engine it should cache750 * - `filename` filename of the view being rendered751 *752 * @param {String} view753 * @param {Object|Function} options or callback function754 * @param {Function} fn755 * @api public756 */757758res.render = function(view, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 759–762why, one step back759 options = options || {};760 var self = this;761 var req = this.req;762 var app = req.app;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 763–780why, one step back763764 // support callback function as second arg765 if ('function' == typeof options) {766 fn = options, options = {};767 }768769 // merge res.locals770 options._locals = self.locals;771772 // default callback to respond773 fn = fn || function(err, str){774 if (err) return req.next(err);775 self.send(str);776 };777778 // render779 app.render(view, options, fn);780};