response.js
This file
Path
lib/response.js
775 lines · 17.9 KiB · JavaScript
Last changed by
Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
History of this fileTake it
The walk stopped after 200 commits: lines older than 7724fc6 point at it.
3.4.6Jonathan Ongbefore adoption7724fc6
lines 1–4why, one step back1/**2 * Module dependencies.3 */4Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 5why, one step back5var deprecate = require('depd')('express');Merge tag '3.10.0'Douglas Christopher Wilsonbefore adoption402ec83
line 6why, one step back6var escapeHtml = require('escape-html');move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 7–12why, one step back7var http = require('http');8var path = require('path');9var mixin = require('utils-merge');10var sign = require('cookie-signature').sign;11var normalizeType = require('./utils').normalizeType;12var normalizeTypes = require('./utils').normalizeTypes;Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
line 13why, one step back13var setCharset = require('./utils').setCharset;Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9
line 14why, one step back14var contentDisposition = require('./utils').contentDisposition;move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 15–20why, one step back15var statusCodes = http.STATUS_CODES;16var cookie = require('cookie');17var send = require('send');18var basename = path.basename;19var extname = path.extname;20var mime = send.mime;Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247
line 21why, one step back21var vary = require('vary');3.4.6Jonathan Ongbefore adoption7724fc6
lines 22–83why, one step back2223/**24 * Response prototype.25 */2627var res = module.exports = {28 __proto__: http.ServerResponse.prototype29};3031/**32 * Set status `code`.33 *34 * @param {Number} code35 * @return {ServerResponse}36 * @api public37 */3839res.status = function(code){40 this.statusCode = code;41 return this;42};4344/**45 * Set Link header field with the given `links`.46 *47 * Examples:48 *49 * res.links({50 * next: 'http://api.example.com/users?page=2',51 * last: 'http://api.example.com/users?page=5'52 * });53 *54 * @param {Object} links55 * @return {ServerResponse}56 * @api public57 */5859res.links = function(links){60 var link = this.get('Link') || '';61 if (link) link += ', ';62 return this.set('Link', link + Object.keys(links).map(function(rel){63 return '<' + links[rel] + '>; rel="' + rel + '"';64 }).join(', '));65};6667/**68 * Send a response.69 *70 * Examples:71 *72 * res.send(new Buffer('wahoo'));73 * res.send({ some: 'json' });74 * res.send('<p>some html</p>');75 * res.send(404, 'Sorry, cant find that');76 * res.send(404);77 *78 * @api public79 */8081res.send = function(body){82 var req = this.req;83 var head = 'HEAD' == req.method;Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
lines 84–85why, one step back84 var type;85 var encoding;3.4.6Jonathan Ongbefore adoption7724fc6
lines 86–110why, one step back86 var len;8788 // settings89 var app = this.app;9091 // allow status / body92 if (2 == arguments.length) {93 // res.send(body, status) backwards compat94 if ('number' != typeof body && 'number' == typeof arguments[1]) {95 this.statusCode = arguments[1];96 } else {97 this.statusCode = body;98 body = arguments[1];99 }100 }101102 switch (typeof body) {103 // response status104 case 'number':105 this.get('Content-Type') || this.type('txt');106 this.statusCode = body;107 body = http.STATUS_CODES[body];108 break;109 // string defaulting to html110 case 'string':remove res.charset usageJonathan Ongbefore adoption2064f41
line 111why, one step back111 if (!this.get('Content-Type')) this.type('html');3.4.6Jonathan Ongbefore adoption7724fc6
lines 112–124why, one step back112 break;113 case 'boolean':114 case 'object':115 if (null == body) {116 body = '';117 } else if (Buffer.isBuffer(body)) {118 this.get('Content-Type') || this.type('bin');119 } else {120 return this.json(body);121 }122 break;123 }124Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
lines 125–132why, one step back125 // write strings in utf-8126 if ('string' === typeof body) {127 encoding = 'utf8';128 type = this.get('Content-Type');129130 // reflect this in content-type131 if ('string' === typeof type) {132 this.set('Content-Type', setCharset(type, 'utf-8'));Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 133–149why, one step back133 }134 }135136 // populate Content-Length137 if (undefined !== body && !this.get('Content-Length')) {138 len = Buffer.isBuffer(body)139 ? body.length140 : Buffer.byteLength(body, encoding);141 this.set('Content-Length', len);142 }143144 // ETag support145 var etag = len !== undefined && app.get('etag fn');146 if (etag && ('GET' === req.method || 'HEAD' === req.method)) {147 if (!this.get('ETag')) {148 etag = etag(body, encoding);149 etag && this.set('ETag', etag);Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
lines 150–152why, one step back150 }151 }1523.4.6Jonathan Ongbefore adoption7724fc6
lines 153–164why, one step back153 // freshness154 if (req.fresh) this.statusCode = 304;155156 // strip irrelevant headers157 if (204 == this.statusCode || 304 == this.statusCode) {158 this.removeHeader('Content-Type');159 this.removeHeader('Content-Length');160 this.removeHeader('Transfer-Encoding');161 body = '';162 }163164 // respondMerge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
lines 165–166why, one step back165 this.end((head ? null : body), encoding);1663.4.6Jonathan Ongbefore adoption7724fc6
lines 167–188why, one step back167 return this;168};169170/**171 * Send JSON response.172 *173 * Examples:174 *175 * res.json(null);176 * res.json({ user: 'tj' });177 * res.json(500, 'oh noes!');178 * res.json(404, 'I dont have that');179 *180 * @api public181 */182183res.json = function(obj){184 // allow status / body185 if (2 == arguments.length) {186 // res.json(body, status) backwards compat187 if ('number' == typeof arguments[1]) {188 this.statusCode = arguments[1];Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
lines 189–193why, one step back189 if (typeof obj === 'number') {190 deprecate('res.json(obj, status): Use res.json(status, obj) instead');191 } else {192 deprecate('res.json(num, status): Use res.status(status).json(num) instead');193 }3.4.6Jonathan Ongbefore adoption7724fc6
lines 194–230why, one step back194 } else {195 this.statusCode = obj;196 obj = arguments[1];197 }198 }199200 // settings201 var app = this.app;202 var replacer = app.get('json replacer');203 var spaces = app.get('json spaces');204 var body = JSON.stringify(obj, replacer, spaces);205206 // content-type207 this.get('Content-Type') || this.set('Content-Type', 'application/json');208209 return this.send(body);210};211212/**213 * Send JSON response with JSONP callback support.214 *215 * Examples:216 *217 * res.jsonp(null);218 * res.jsonp({ user: 'tj' });219 * res.jsonp(500, 'oh noes!');220 * res.jsonp(404, 'I dont have that');221 *222 * @api public223 */224225res.jsonp = function(obj){226 // allow status / body227 if (2 == arguments.length) {228 // res.json(body, status) backwards compat229 if ('number' == typeof arguments[1]) {230 this.statusCode = arguments[1];Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
lines 231–235why, one step back231 if (typeof obj === 'number') {232 deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');233 } else {234 deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');235 }3.4.6Jonathan Ongbefore adoption7724fc6
lines 236–251why, one step back236 } else {237 this.statusCode = obj;238 obj = arguments[1];239 }240 }241242 // settings243 var app = this.app;244 var replacer = app.get('json replacer');245 var spaces = app.get('json spaces');246 var body = JSON.stringify(obj, replacer, spaces)247 .replace(/\u2028/g, '\\u2028')248 .replace(/\u2029/g, '\\u2029');249 var callback = this.req.query[app.get('jsonp callback name')];250251 // content-typeKeep previous Content-Type for res.jsonpAlberto Lealbefore adoptionbe997fd
line 252why, one step back252 this.get('Content-Type') || this.set('Content-Type', 'application/json');3.4.6Jonathan Ongbefore adoption7724fc6
line 253why, one step back253Merge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84
lines 254–258why, one step back254 // fixup callback255 if (Array.isArray(callback)) {256 callback = callback[0];257 }2583.4.6Jonathan Ongbefore adoption7724fc6
line 259why, one step back259 // jsonpMerge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84
line 260why, one step back260 if (callback && 'string' === typeof callback) {3.4.6Jonathan Ongbefore adoption7724fc6
lines 261–281why, one step back261 this.set('Content-Type', 'text/javascript');262 var cb = callback.replace(/[^\[\]\w$.]/g, '');263 body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';264 }265266 return this.send(body);267};268269/**270 * Transfer the file at the given `path`.271 *272 * Automatically sets the _Content-Type_ response header field.273 * The callback `fn(err)` is invoked when the transfer is complete274 * or when an error occurs. Be sure to check `res.sentHeader`275 * if you wish to attempt responding, as the header and some data276 * may have already been transferred.277 *278 * Options:279 *280 * - `maxAge` defaulting to 0281 * - `root` root directory for relative filenamesPass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
line 282why, one step back282 * - `hidden` serve hidden files, defaulting to false3.4.6Jonathan Ongbefore adoption7724fc6
line 283why, one step back283 *Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
lines 284–285why, one step back284 * Other options are passed along to `send`.285 *3.4.6Jonathan Ongbefore adoption7724fc6
lines 286–309why, one step back286 * Examples:287 *288 * The following example illustrates how `res.sendfile()` may289 * be used as an alternative for the `static()` middleware for290 * dynamic situations. The code backing `res.sendfile()` is actually291 * the same code, so HTTP cache support etc is identical.292 *293 * app.get('/user/:uid/photos/:file', function(req, res){294 * var uid = req.params.uid295 * , file = req.params.file;296 *297 * req.user.mayViewFilesFrom(uid, function(yes){298 * if (yes) {299 * res.sendfile('/uploads/' + uid + '/' + file);300 * } else {301 * res.send(403, 'Sorry! you cant see that.');302 * }303 * });304 * });305 *306 * @api public307 */308309res.sendfile = function(path, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 310–314why, one step back310 options = options || {};311 var self = this;312 var req = self.req;313 var next = this.req.next;314 var done;3.4.6Jonathan Ongbefore adoption7724fc6
line 315why, one step back315Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
line 316why, one step back3163.4.6Jonathan Ongbefore adoption7724fc6
lines 317–332why, one step back317 // support function as second arg318 if ('function' == typeof options) {319 fn = options;320 options = {};321 }322323 // socket errors324 req.socket.on('error', error);325326 // errors327 function error(err) {328 if (done) return;329 done = true;330331 // clean up332 cleanup();remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289
line 333why, one step back333 if (!self.headersSent) self.removeHeader('Content-Disposition');3.4.6Jonathan Ongbefore adoption7724fc6
lines 334–338why, one step back334335 // callback available336 if (fn) return fn(err);337338 // list in limbo if there's no callbackremove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289
line 339why, one step back339 if (self.headersSent) return;3.4.6Jonathan Ongbefore adoption7724fc6
lines 340–356why, one step back340341 // delegate342 next(err);343 }344345 // streaming346 function stream(stream) {347 if (done) return;348 cleanup();349 if (fn) stream.on('end', fn);350 }351352 // cleanup353 function cleanup() {354 req.socket.removeListener('error', error);355 }356Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
lines 357–359why, one step back357 // Back-compat358 options.maxage = options.maxage || options.maxAge || 0;3593.4.6Jonathan Ongbefore adoption7724fc6
line 360why, one step back360 // transferPass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
line 361why, one step back361 var file = send(req, path, options);3.4.6Jonathan Ongbefore adoption7724fc6
lines 362–374why, one step back362 file.on('error', error);363 file.on('directory', next);364 file.on('stream', stream);365 file.pipe(this);366 this.on('finish', cleanup);367};368369/**370 * Transfer the file at the given `path` as an attachment.371 *372 * Optionally providing an alternate attachment `filename`,373 * and optional callback `fn(err)`. The callback is invoked374 * when the data transfer is complete, or when an error hasremove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289
line 375why, one step back375 * ocurred. Be sure to check `res.headersSent` if you plan to respond.3.4.6Jonathan Ongbefore adoption7724fc6
lines 376–389why, one step back376 *377 * This method uses `res.sendfile()`.378 *379 * @api public380 */381382res.download = function(path, filename, fn){383 // support function as second arg384 if ('function' == typeof filename) {385 fn = filename;386 filename = null;387 }388389 filename = filename || path;Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9
line 390why, one step back390 this.set('Content-Disposition', contentDisposition(filename));3.4.6Jonathan Ongbefore adoption7724fc6
lines 391–475why, one step back391 return this.sendfile(path, fn);392};393394/**395 * Set _Content-Type_ response header with `type` through `mime.lookup()`396 * when it does not contain "/", or set the Content-Type to `type` otherwise.397 *398 * Examples:399 *400 * res.type('.html');401 * res.type('html');402 * res.type('json');403 * res.type('application/json');404 * res.type('png');405 *406 * @param {String} type407 * @return {ServerResponse} for chaining408 * @api public409 */410411res.contentType =412res.type = function(type){413 return this.set('Content-Type', ~type.indexOf('/')414 ? type415 : mime.lookup(type));416};417418/**419 * Respond to the Acceptable formats using an `obj`420 * of mime-type callbacks.421 *422 * This method uses `req.accepted`, an array of423 * acceptable types ordered by their quality values.424 * When "Accept" is not present the _first_ callback425 * is invoked, otherwise the first match is used. When426 * no match is performed the server responds with427 * 406 "Not Acceptable".428 *429 * Content-Type is set for you, however if you choose430 * you may alter this within the callback using `res.type()`431 * or `res.set('Content-Type', ...)`.432 *433 * res.format({434 * 'text/plain': function(){435 * res.send('hey');436 * },437 *438 * 'text/html': function(){439 * res.send('<p>hey</p>');440 * },441 *442 * 'appliation/json': function(){443 * res.send({ message: 'hey' });444 * }445 * });446 *447 * In addition to canonicalized MIME types you may448 * also use extnames mapped to these types:449 *450 * res.format({451 * text: function(){452 * res.send('hey');453 * },454 *455 * html: function(){456 * res.send('<p>hey</p>');457 * },458 *459 * json: function(){460 * res.send({ message: 'hey' });461 * }462 * });463 *464 * By default Express passes an `Error`465 * with a `.status` of 406 to `next(err)`466 * if a match is not made. If you provide467 * a `.default` callback it will be invoked468 * instead.469 *470 * @param {Object} obj471 * @return {ServerResponse} for chaining472 * @api public473 */474475res.format = function(obj){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 476–477why, one step back476 var req = this.req;477 var next = req.next;3.4.6Jonathan Ongbefore adoption7724fc6
lines 478–487why, one step back478479 var fn = obj.default;480 if (fn) delete obj.default;481 var keys = Object.keys(obj);482483 var key = req.accepts(keys);484485 this.vary("Accept");486487 if (key) {remove res.charset usageJonathan Ongbefore adoption2064f41
line 488why, one step back488 this.set('Content-Type', normalizeType(key).value);3.4.6Jonathan Ongbefore adoption7724fc6
lines 489–511why, one step back489 obj[key](req, this, next);490 } else if (fn) {491 fn();492 } else {493 var err = new Error('Not Acceptable');494 err.status = 406;495 err.types = normalizeTypes(keys).map(function(o){ return o.value });496 next(err);497 }498499 return this;500};501502/**503 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.504 *505 * @param {String} filename506 * @return {ServerResponse}507 * @api public508 */509510res.attachment = function(filename){511 if (filename) this.type(extname(filename));Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9
line 512why, one step back512 this.set('Content-Disposition', contentDisposition(filename));3.4.6Jonathan Ongbefore adoption7724fc6
lines 513–538why, one step back513 return this;514};515516/**517 * Set header `field` to `val`, or pass518 * an object of header fields.519 *520 * Examples:521 *522 * res.set('Foo', ['bar', 'baz']);523 * res.set('Accept', 'application/json');524 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });525 *526 * Aliased as `res.header()`.527 *528 * @param {String|Object|Array} field529 * @param {String} val530 * @return {ServerResponse} for chaining531 * @api public532 */533534res.set =535res.header = function(field, val){536 if (2 == arguments.length) {537 if (Array.isArray(val)) val = val.map(String);538 else val = String(val);preserve casing of headers in res.header and res.setDouglas Christopher Wilsonbefore adoption1536a21
line 539why, one step back539 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 540–542why, one step back540 var charset = mime.charsets.lookup(val.split(';')[0]);541 if (charset) val += '; charset=' + charset.toLowerCase();542 }3.4.6Jonathan Ongbefore adoption7724fc6
lines 543–575why, one step back543 this.setHeader(field, val);544 } else {545 for (var key in field) {546 this.set(key, field[key]);547 }548 }549 return this;550};551552/**553 * Get value for header `field`.554 *555 * @param {String} field556 * @return {String}557 * @api public558 */559560res.get = function(field){561 return this.getHeader(field);562};563564/**565 * Clear cookie `name`.566 *567 * @param {String} name568 * @param {Object} options569 * @param {ServerResponse} for chaining570 * @api public571 */572573res.clearCookie = function(name, options){574 var opts = { expires: new Date(1), path: '/' };575 return this.cookie(name, '', optionsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 576why, one step back576 ? mixin(opts, options)3.4.6Jonathan Ongbefore adoption7724fc6
lines 577–603why, one step back577 : opts);578};579580/**581 * Set cookie `name` to `val`, with the given `options`.582 *583 * Options:584 *585 * - `maxAge` max-age in milliseconds, converted to `expires`586 * - `signed` sign the cookie587 * - `path` defaults to "/"588 *589 * Examples:590 *591 * // "Remember Me" for 15 minutes592 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });593 *594 * // save as above595 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })596 *597 * @param {String} name598 * @param {String|Object} val599 * @param {Options} options600 * @api public601 */602603res.cookie = function(name, val, options){use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 604why, one step back604 options = mixin({}, options);3.4.6Jonathan Ongbefore adoption7724fc6
lines 605–606why, one step back605 var secret = this.req.secret;606 var signed = options.signed;remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
line 607why, one step back607 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');3.4.6Jonathan Ongbefore adoption7724fc6
lines 608–615why, one step back608 if ('number' == typeof val) val = val.toString();609 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);610 if (signed) val = 's:' + sign(val, secret);611 if ('maxAge' in options) {612 options.expires = new Date(Date.now() + options.maxAge);613 options.maxAge /= 1000;614 }615 if (null == options.path) options.path = '/';move support for multiple `res.cookie` calls to lib/responseRoman Shtylmanbefore adoptiond42d8f5
lines 616–627why, one step back616 var headerVal = cookie.serialize(name, String(val), options);617618 // supports multiple 'res.cookie' calls by getting previous value619 var prev = this.get('Set-Cookie');620 if (prev) {621 if (Array.isArray(prev)) {622 headerVal = prev.concat(headerVal);623 } else {624 headerVal = [prev, headerVal];625 }626 }627 this.set('Set-Cookie', headerVal);3.4.6Jonathan Ongbefore adoption7724fc6
lines 628–641why, one step back628 return this;629};630631632/**633 * Set the location header to `url`.634 *635 * The given `url` can also be "back", which redirects636 * to the _Referrer_ or _Referer_ headers or "/".637 *638 * Examples:639 *640 * res.location('/foo/bar').;641 * res.location('http://example.com');res.location: remove resolving relative urlsJonathan Ongbefore adoptionaac1d52
line 642why, one step back642 * res.location('../login');3.4.6Jonathan Ongbefore adoption7724fc6
lines 643–648why, one step back643 *644 * @param {String} url645 * @api public646 */647648res.location = function(url){res.location: remove resolving relative urlsJonathan Ongbefore adoptionaac1d52
line 649why, one step back649 var req = this.req;3.4.6Jonathan Ongbefore adoption7724fc6
lines 650–680why, one step back650651 // "back" is an alias for the referrer652 if ('back' == url) url = req.get('Referrer') || '/';653654 // Respond655 this.set('Location', url);656 return this;657};658659/**660 * Redirect to the given `url` with optional response `status`661 * defaulting to 302.662 *663 * The resulting `url` is determined by `res.location()`, so664 * it will play nicely with mounted apps, relative paths,665 * `"back"` etc.666 *667 * Examples:668 *669 * res.redirect('/foo/bar');670 * res.redirect('http://example.com');671 * res.redirect(301, 'http://example.com');672 * res.redirect('http://example.com', 301);673 * res.redirect('../login'); // /blog/post/1 -> /blog/login674 *675 * @param {String} url676 * @param {Number} code677 * @api public678 */679680res.redirect = function(url){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 681–683why, one step back681 var head = 'HEAD' == this.req.method;682 var status = 302;683 var body;3.4.6Jonathan Ongbefore adoption7724fc6
lines 684–705why, one step back684685 // allow status / url686 if (2 == arguments.length) {687 if ('number' == typeof url) {688 status = url;689 url = arguments[1];690 } else {691 status = arguments[1];692 }693 }694695 // Set location header696 this.location(url);697 url = this.get('Location');698699 // Support text/{plain,html} by default700 this.format({701 text: function(){702 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);703 },704705 html: function(){use escape-html module to escape htmlRoman Shtylmanbefore adoption63c6a9c
line 706why, one step back706 var u = escapeHtml(url);3.4.6Jonathan Ongbefore adoption7724fc6
lines 707–730why, one step back707 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';708 },709710 default: function(){711 body = '';712 }713 });714715 // Respond716 this.statusCode = status;717 this.set('Content-Length', Buffer.byteLength(body));718 this.end(head ? null : body);719};720721/**722 * Add `field` to Vary. If already present in the Vary set, then723 * this call is simply ignored.724 *725 * @param {Array|String} field726 * @param {ServerResponse} for chaining727 * @api public728 */729730res.vary = function(field){Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247
line 731why, one step back731 // checks for back-compat3.4.6Jonathan Ongbefore adoption7724fc6
line 732why, one step back732 if (!field) return this;Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247
line 733why, one step back733 if (Array.isArray(field) && !field.length) return this;3.4.6Jonathan Ongbefore adoption7724fc6
line 734why, one step back734Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247
line 735why, one step back735 vary(this, field);3.4.6Jonathan Ongbefore adoption7724fc6
lines 736–753why, one step back736737 return this;738};739740/**741 * Render `view` with the given `options` and optional callback `fn`.742 * When a callback function is given a response will _not_ be made743 * automatically, otherwise a response of _200_ and _text/html_ is given.744 *745 * Options:746 *747 * - `cache` boolean hinting to the engine it should cache748 * - `filename` filename of the view being rendered749 *750 * @api public751 */752753res.render = function(view, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 754–757why, one step back754 options = options || {};755 var self = this;756 var req = this.req;757 var app = req.app;3.4.6Jonathan Ongbefore adoption7724fc6
lines 758–775why, one step back758759 // support callback function as second arg760 if ('function' == typeof options) {761 fn = options, options = {};762 }763764 // merge res.locals765 options._locals = self.locals;766767 // default callback to respond768 fn = fn || function(err, str){769 if (err) return req.next(err);770 self.send(str);771 };772773 // render774 app.render(view, options, fn);775};