response.js
This file
Path
lib/response.js
803 lines · 18.6 KiB · JavaScript
Last changed by
Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060
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;Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060
line 13why, one step back13var deprecate = require('./utils').deprecate;move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 14–20why, one step back14var etag = require('./utils').etag;15var statusCodes = http.STATUS_CODES;16var cookie = require('cookie');17var send = require('send');18var basename = path.basename;19var extname = path.extname;20var mime = send.mime;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 21–58why, one step back2122/**23 * Response prototype.24 */2526var res = module.exports = {27 __proto__: http.ServerResponse.prototype28};2930/**31 * Set status `code`.32 *33 * @param {Number} code34 * @return {ServerResponse}35 * @api public36 */3738res.status = function(code){39 this.statusCode = code;40 return this;41};4243/**44 * Set Link header field with the given `links`.45 *46 * Examples:47 *48 * res.links({49 * next: 'http://api.example.com/users?page=2',50 * last: 'http://api.example.com/users?page=5'51 * });52 *53 * @param {Object} links54 * @return {ServerResponse}55 * @api public56 */5758res.links = function(links){refactor res.links()TJ Holowaychukbefore adoption8e2f538
lines 59–61why, one step back59 var link = this.get('Link') || '';60 if (link) link += ', ';61 return this.set('Link', link + Object.keys(links).map(function(rel){fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 62–87why, one step back62 return '<' + links[rel] + '>; rel="' + rel + '"';63 }).join(', '));64};6566/**67 * Send a response.68 *69 * Examples:70 *71 * res.send(new Buffer('wahoo'));72 * res.send({ some: 'json' });73 * res.send('<p>some html</p>');74 * res.send(404, 'Sorry, cant find that');75 * res.send(404);76 *77 * @param {Mixed} body or status78 * @param {Mixed} body79 * @return {ServerResponse}80 * @api public81 */8283res.send = function(body){84 var req = this.req;85 var head = 'HEAD' == req.method;86 var len;87Merge pull request #1694 from kavu/add_disable_etagTJ Holowaychukbefore adoption610e172
lines 88–90why, one step back88 // settings89 var app = this.app;90fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 91–110why, one step back91 // 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');fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 112–133why, 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 }124125 // populate Content-Length126 if (undefined !== body && !this.get('Content-Length')) {127 this.set('Content-Length', len = Buffer.isBuffer(body)128 ? body.length129 : Buffer.byteLength(body));130 }131132 // ETag support133 // TODO: W/ supportInclude ETag in HEAD requestsTiago Relvaobefore adoption3c7310e
line 134why, one step back134 if (app.settings.etag && len && ('GET' == req.method || 'HEAD' == req.method)) {fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 135–177why, one step back135 if (!this.get('ETag')) {136 this.set('ETag', etag(body));137 }138 }139140 // freshness141 if (req.fresh) this.statusCode = 304;142143 // strip irrelevant headers144 if (204 == this.statusCode || 304 == this.statusCode) {145 this.removeHeader('Content-Type');146 this.removeHeader('Content-Length');147 this.removeHeader('Transfer-Encoding');148 body = '';149 }150151 // respond152 this.end(head ? null : body);153 return this;154};155156/**157 * Send JSON response.158 *159 * Examples:160 *161 * res.json(null);162 * res.json({ user: 'tj' });163 * res.json(500, 'oh noes!');164 * res.json(404, 'I dont have that');165 *166 * @param {Mixed} obj or status167 * @param {Mixed} obj168 * @return {ServerResponse}169 * @api public170 */171172res.json = function(obj){173 // allow status / body174 if (2 == arguments.length) {175 // res.json(body, status) backwards compat176 if ('number' == typeof arguments[1]) {177 this.statusCode = arguments[1];Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060
lines 178–180why, one step back178 return 'number' === typeof obj179 ? jsonNumDeprecated.call(this, obj)180 : jsonDeprecated.call(this, obj);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 181–198why, one step back181 } else {182 this.statusCode = obj;183 obj = arguments[1];184 }185 }186187 // settings188 var app = this.app;189 var replacer = app.get('json replacer');190 var spaces = app.get('json spaces');191 var body = JSON.stringify(obj, replacer, spaces);192193 // content-type194 this.get('Content-Type') || this.set('Content-Type', 'application/json');195196 return this.send(body);197};198Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060
lines 199–204why, one step back199var jsonDeprecated = deprecate(res.json,200 'res.json(obj, status): Use res.json(status, obj) instead');201202var jsonNumDeprecated = deprecate(res.json,203 'res.json(num, status): Use res.status(status).json(num) instead');204fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 205–226why, one step back205/**206 * Send JSON response with JSONP callback support.207 *208 * Examples:209 *210 * res.jsonp(null);211 * res.jsonp({ user: 'tj' });212 * res.jsonp(500, 'oh noes!');213 * res.jsonp(404, 'I dont have that');214 *215 * @param {Mixed} obj or status216 * @param {Mixed} obj217 * @return {ServerResponse}218 * @api public219 */220221res.jsonp = function(obj){222 // allow status / body223 if (2 == arguments.length) {224 // res.json(body, status) backwards compat225 if ('number' == typeof arguments[1]) {226 this.statusCode = arguments[1];Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060
lines 227–229why, one step back227 return 'number' === typeof obj228 ? jsonpNumDeprecated.call(this, obj)229 : jsonpDeprecated.call(this, obj);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 230–245why, one step back230 } else {231 this.statusCode = obj;232 obj = arguments[1];233 }234 }235236 // settings237 var app = this.app;238 var replacer = app.get('json replacer');239 var spaces = app.get('json spaces');240 var body = JSON.stringify(obj, replacer, spaces)241 .replace(/\u2028/g, '\\u2028')242 .replace(/\u2029/g, '\\u2029');243 var callback = this.req.query[app.get('jsonp callback name')];244245 // content-typeKeep previous Content-Type for res.jsonpAlberto Lealbefore adoptionbe997fd
line 246why, one step back246 this.get('Content-Type') || this.set('Content-Type', 'application/json');fix package.json conflictTJ Holowaychukbefore adoption26802a6
line 247why, one step back247Merge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84
lines 248–252why, one step back248 // fixup callback249 if (Array.isArray(callback)) {250 callback = callback[0];251 }252fix package.json conflictTJ Holowaychukbefore adoption26802a6
line 253why, one step back253 // jsonpMerge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84
line 254why, one step back254 if (callback && 'string' === typeof callback) {fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 255–256why, one step back255 this.set('Content-Type', 'text/javascript');256 var cb = callback.replace(/[^\[\]\w$.]/g, '');Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionbd8b9f5
line 257why, one step back257 body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 258–261why, one step back258 }259260 return this.send(body);261};Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060
lines 262–267why, one step back262263var jsonpDeprecated = deprecate(res.json,264 'res.jsonp(obj, status): Use res.jsonp(status, obj) instead');265266var jsonpNumDeprecated = deprecate(res.json,267 'res.jsonp(num, status): Use res.status(status).jsonp(num) instead');fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 268–281why, one step back268269/**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 falsefix package.json conflictTJ Holowaychukbefore adoption26802a6
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 *fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 286–312why, 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 * @param {String} path307 * @param {Object|Function} options or fn308 * @param {Function} fn309 * @api public310 */311312res.sendfile = function(path, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 313–317why, one step back313 options = options || {};314 var self = this;315 var req = self.req;316 var next = this.req.next;317 var done;fix package.json conflictTJ Holowaychukbefore adoption26802a6
line 318why, one step back318Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
line 319why, one step back319fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 320–335why, one step back320 // support function as second arg321 if ('function' == typeof options) {322 fn = options;323 options = {};324 }325326 // socket errors327 req.socket.on('error', error);328329 // errors330 function error(err) {331 if (done) return;332 done = true;333334 // clean up335 cleanup();remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289
line 336why, one step back336 if (!self.headersSent) self.removeHeader('Content-Disposition');fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 337–341why, one step back337338 // callback available339 if (fn) return fn(err);340341 // list in limbo if there's no callbackremove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289
line 342why, one step back342 if (self.headersSent) return;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 343–348why, one step back343344 // delegate345 next(err);346 }347348 // streamingMerge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption0b88208
line 349why, one step back349 function stream(stream) {fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 350–351why, one step back350 if (done) return;351 cleanup();Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption0b88208
line 352why, one step back352 if (fn) stream.on('end', fn);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 353–359why, one step back353 }354355 // cleanup356 function cleanup() {357 req.socket.removeListener('error', error);358 }359Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
lines 360–362why, one step back360 // Back-compat361 options.maxage = options.maxage || options.maxAge || 0;362fix package.json conflictTJ Holowaychukbefore adoption26802a6
line 363why, one step back363 // transferPass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
line 364why, one step back364 var file = send(req, path, options);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 365–377why, one step back365 file.on('error', error);366 file.on('directory', next);367 file.on('stream', stream);368 file.pipe(this);369 this.on('finish', cleanup);370};371372/**373 * Transfer the file at the given `path` as an attachment.374 *375 * Optionally providing an alternate attachment `filename`,376 * and optional callback `fn(err)`. The callback is invoked377 * when the data transfer is complete, or when an error hasremove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289
line 378why, one step back378 * ocurred. Be sure to check `res.headersSent` if you plan to respond.fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 379–395why, one step back379 *380 * This method uses `res.sendfile()`.381 *382 * @param {String} path383 * @param {String|Function} filename or fn384 * @param {Function} fn385 * @api public386 */387388res.download = function(path, filename, fn){389 // support function as second arg390 if ('function' == typeof filename) {391 fn = filename;392 filename = null;393 }394395 filename = filename || path;Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9
line 396why, one step back396 this.set('Content-Disposition', contentDisposition(filename));fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 397–481why, one step back397 return this.sendfile(path, fn);398};399400/**401 * Set _Content-Type_ response header with `type` through `mime.lookup()`402 * when it does not contain "/", or set the Content-Type to `type` otherwise.403 *404 * Examples:405 *406 * res.type('.html');407 * res.type('html');408 * res.type('json');409 * res.type('application/json');410 * res.type('png');411 *412 * @param {String} type413 * @return {ServerResponse} for chaining414 * @api public415 */416417res.contentType =418res.type = function(type){419 return this.set('Content-Type', ~type.indexOf('/')420 ? type421 : mime.lookup(type));422};423424/**425 * Respond to the Acceptable formats using an `obj`426 * of mime-type callbacks.427 *428 * This method uses `req.accepted`, an array of429 * acceptable types ordered by their quality values.430 * When "Accept" is not present the _first_ callback431 * is invoked, otherwise the first match is used. When432 * no match is performed the server responds with433 * 406 "Not Acceptable".434 *435 * Content-Type is set for you, however if you choose436 * you may alter this within the callback using `res.type()`437 * or `res.set('Content-Type', ...)`.438 *439 * res.format({440 * 'text/plain': function(){441 * res.send('hey');442 * },443 *444 * 'text/html': function(){445 * res.send('<p>hey</p>');446 * },447 *448 * 'appliation/json': function(){449 * res.send({ message: 'hey' });450 * }451 * });452 *453 * In addition to canonicalized MIME types you may454 * also use extnames mapped to these types:455 *456 * res.format({457 * text: function(){458 * res.send('hey');459 * },460 *461 * html: function(){462 * res.send('<p>hey</p>');463 * },464 *465 * json: function(){466 * res.send({ message: 'hey' });467 * }468 * });469 *470 * By default Express passes an `Error`471 * with a `.status` of 406 to `next(err)`472 * if a match is not made. If you provide473 * a `.default` callback it will be invoked474 * instead.475 *476 * @param {Object} obj477 * @return {ServerResponse} for chaining478 * @api public479 */480481res.format = function(obj){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 482–483why, one step back482 var req = this.req;483 var next = req.next;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 484–490why, one step back484485 var fn = obj.default;486 if (fn) delete obj.default;487 var keys = Object.keys(obj);488489 var key = req.accepts(keys);490add res.vary(). Closes #1682cjihrigbefore adoptione5de08f
line 491why, one step back491 this.vary("Accept");fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 492–493why, one step back492493 if (key) {remove res.charset usageJonathan Ongbefore adoption2064f41
line 494why, one step back494 this.set('Content-Type', normalizeType(key).value);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 495–517why, one step back495 obj[key](req, this, next);496 } else if (fn) {497 fn();498 } else {499 var err = new Error('Not Acceptable');500 err.status = 406;501 err.types = normalizeTypes(keys).map(function(o){ return o.value });502 next(err);503 }504505 return this;506};507508/**509 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.510 *511 * @param {String} filename512 * @return {ServerResponse}513 * @api public514 */515516res.attachment = function(filename){517 if (filename) this.type(extname(filename));Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9
line 518why, one step back518 this.set('Content-Disposition', contentDisposition(filename));fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 519–544why, one step back519 return this;520};521522/**523 * Set header `field` to `val`, or pass524 * an object of header fields.525 *526 * Examples:527 *528 * res.set('Foo', ['bar', 'baz']);529 * res.set('Accept', 'application/json');530 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });531 *532 * Aliased as `res.header()`.533 *534 * @param {String|Object|Array} field535 * @param {String} val536 * @return {ServerResponse} for chaining537 * @api public538 */539540res.set =541res.header = function(field, val){542 if (2 == arguments.length) {543 if (Array.isArray(val)) val = val.map(String);544 else val = String(val);preserve casing of headers in res.header and res.setDouglas Christopher Wilsonbefore adoption1536a21
line 545why, one step back545 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 546–548why, one step back546 var charset = mime.charsets.lookup(val.split(';')[0]);547 if (charset) val += '; charset=' + charset.toLowerCase();548 }fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 549–581why, one step back549 this.setHeader(field, val);550 } else {551 for (var key in field) {552 this.set(key, field[key]);553 }554 }555 return this;556};557558/**559 * Get value for header `field`.560 *561 * @param {String} field562 * @return {String}563 * @api public564 */565566res.get = function(field){567 return this.getHeader(field);568};569570/**571 * Clear cookie `name`.572 *573 * @param {String} name574 * @param {Object} options575 * @param {ServerResponse} for chaining576 * @api public577 */578579res.clearCookie = function(name, options){580 var opts = { expires: new Date(1), path: '/' };581 return this.cookie(name, '', optionsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 582why, one step back582 ? mixin(opts, options)fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 583–609why, one step back583 : opts);584};585586/**587 * Set cookie `name` to `val`, with the given `options`.588 *589 * Options:590 *591 * - `maxAge` max-age in milliseconds, converted to `expires`592 * - `signed` sign the cookie593 * - `path` defaults to "/"594 *595 * Examples:596 *597 * // "Remember Me" for 15 minutes598 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });599 *600 * // save as above601 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })602 *603 * @param {String} name604 * @param {String|Object} val605 * @param {Options} options606 * @api public607 */608609res.cookie = function(name, val, options){use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 610why, one step back610 options = mixin({}, options);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 611–612why, one step back611 var secret = this.req.secret;612 var signed = options.signed;remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
line 613why, one step back613 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 614–621why, one step back614 if ('number' == typeof val) val = val.toString();615 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);616 if (signed) val = 's:' + sign(val, secret);617 if ('maxAge' in options) {618 options.expires = new Date(Date.now() + options.maxAge);619 options.maxAge /= 1000;620 }621 if (null == options.path) options.path = '/';move support for multiple `res.cookie` calls to lib/responseRoman Shtylmanbefore adoptiond42d8f5
lines 622–633why, one step back622 var headerVal = cookie.serialize(name, String(val), options);623624 // supports multiple 'res.cookie' calls by getting previous value625 var prev = this.get('Set-Cookie');626 if (prev) {627 if (Array.isArray(prev)) {628 headerVal = prev.concat(headerVal);629 } else {630 headerVal = [prev, headerVal];631 }632 }633 this.set('Set-Cookie', headerVal);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 634–640why, one step back634 return this;635};636637638/**639 * Set the location header to `url`.640 *Merge pull request #1829 from michaelficarra/patch-1TJ Holowaychukbefore adoptionde54af4
line 641why, one step back641 * The given `url` can also be "back", which redirectsfix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 642–647why, one step back642 * to the _Referrer_ or _Referer_ headers or "/".643 *644 * Examples:645 *646 * res.location('/foo/bar').;647 * res.location('http://example.com');res.location: remove resolving relative urlsJonathan Ongbefore adoptionaac1d52
line 648why, one step back648 * res.location('../login');fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 649–654why, one step back649 *650 * @param {String} url651 * @api public652 */653654res.location = function(url){res.location: remove resolving relative urlsJonathan Ongbefore adoptionaac1d52
line 655why, one step back655 var req = this.req;fix package.json conflictTJ Holowaychukbefore adoption26802a6
line 656why, one step back656Merge pull request #1829 from michaelficarra/patch-1TJ Holowaychukbefore adoptionde54af4
line 657why, one step back657 // "back" is an alias for the referrerocdTJ Holowaychukbefore adoption8a7a695
line 658why, one step back658 if ('back' == url) url = req.get('Referrer') || '/';fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 659–686why, one step back659660 // Respond661 this.set('Location', url);662 return this;663};664665/**666 * Redirect to the given `url` with optional response `status`667 * defaulting to 302.668 *669 * The resulting `url` is determined by `res.location()`, so670 * it will play nicely with mounted apps, relative paths,671 * `"back"` etc.672 *673 * Examples:674 *675 * res.redirect('/foo/bar');676 * res.redirect('http://example.com');677 * res.redirect(301, 'http://example.com');678 * res.redirect('http://example.com', 301);679 * res.redirect('../login'); // /blog/post/1 -> /blog/login680 *681 * @param {String} url682 * @param {Number} code683 * @api public684 */685686res.redirect = function(url){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 687–689why, one step back687 var head = 'HEAD' == this.req.method;688 var status = 302;689 var body;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 690–711why, one step back690691 // allow status / url692 if (2 == arguments.length) {693 if ('number' == typeof url) {694 status = url;695 url = arguments[1];696 } else {697 status = arguments[1];698 }699 }700701 // Set location header702 this.location(url);703 url = this.get('Location');704705 // Support text/{plain,html} by default706 this.format({707 text: function(){708 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);709 },710711 html: function(){use escape-html module to escape htmlRoman Shtylmanbefore adoption63c6a9c
line 712why, one step back712 var u = escapeHtml(url);fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 713–724why, one step back713 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';714 },715716 default: function(){717 body = '';718 }719 });720721 // Respond722 this.statusCode = status;723 this.set('Content-Length', Buffer.byteLength(body));724 this.end(head ? null : body);add res.vary(). Closes #1682cjihrigbefore adoptione5de08f
lines 725–751why, one step back725};726727/**728 * Add `field` to Vary. If already present in the Vary set, then729 * this call is simply ignored.730 *731 * @param {Array|String} field732 * @param {ServerResponse} for chaining733 * @api public734 */735736res.vary = function(field){737 var self = this;738739 // nothing740 if (!field) return this;741742 // array743 if (Array.isArray(field)) {744 field.forEach(function(field){745 self.vary(field);746 });747 return;748 }749750 var vary = this.get('Vary');751Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionbd8b9f5
line 752why, one step back752 // appendadd res.vary(). Closes #1682cjihrigbefore adoptione5de08f
lines 753–762why, one step back753 if (vary) {754 vary = vary.split(/ *, */);755 if (!~vary.indexOf(field)) vary.push(field);756 this.set('Vary', vary.join(', '));757 return this;758 }759760 // set761 this.set('Vary', field);762 return this;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 763–781why, one step back763};764765/**766 * Render `view` with the given `options` and optional callback `fn`.767 * When a callback function is given a response will _not_ be made768 * automatically, otherwise a response of _200_ and _text/html_ is given.769 *770 * Options:771 *772 * - `cache` boolean hinting to the engine it should cache773 * - `filename` filename of the view being rendered774 *775 * @param {String} view776 * @param {Object|Function} options or callback function777 * @param {Function} fn778 * @api public779 */780781res.render = function(view, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 782–785why, one step back782 options = options || {};783 var self = this;784 var req = this.req;785 var app = req.app;fix package.json conflictTJ Holowaychukbefore adoption26802a6
lines 786–803why, one step back786787 // support callback function as second arg788 if ('function' == typeof options) {789 fn = options, options = {};790 }791792 // merge res.locals793 options._locals = self.locals;794795 // default callback to respond796 fn = fn || function(err, str){797 if (err) return req.next(err);798 self.send(str);799 };800801 // render802 app.render(view, options, fn);803};