Skip to content
Myr

response.js

This file

Path

lib/response.js

795 lines · 18.4 KiB · JavaScript

Last changed by

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

History of this file

Take it

The walk stopped after 200 commits: lines older than 3baca25 point at it.

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 1–4why, one step back
1/**
2 * Module dependencies.3 */4

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

line 5why, one step back
5var deprecate = require('depd')('express');

Merge tag '3.10.0'Douglas Christopher Wilsonbefore adoption402ec83

line 6why, one step back
6var escapeHtml = require('escape-html');

move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7

lines 7–12why, one step back
7var 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 back
13var setCharset = require('./utils').setCharset;

Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9

line 14why, one step back
14var contentDisposition = require('./utils').contentDisposition;

move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7

lines 15–20why, one step back
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;

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

line 21why, one step back
21var vary = require('vary');

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 22–83why, one step back
22
23/**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 back
84 var type;
85 var encoding;

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 86–94why, one step back
86 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]) {

add deprecation message to res.send(body, status)Douglas Christopher Wilsonbefore adoptionba8a4c5

line 95why, one step back
95 deprecate('res.send(body, status): Use res.send(status, body) instead');

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 96–111why, one step back
96 this.statusCode = arguments[1];
97 } else {98 this.statusCode = body;99 body = arguments[1];100 }101 }102103 switch (typeof body) {104 // response status105 case 'number':106 this.get('Content-Type') || this.type('txt');107 this.statusCode = body;108 body = http.STATUS_CODES[body];109 break;110 // string defaulting to html111 case 'string':

remove res.charset usageJonathan Ongbefore adoption2064f41

line 112why, one step back
112 if (!this.get('Content-Type')) this.type('html');

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 113–125why, one step back
113 break;
114 case 'boolean':115 case 'object':116 if (null == body) {117 body = '';118 } else if (Buffer.isBuffer(body)) {119 this.get('Content-Type') || this.type('bin');120 } else {121 return this.json(body);122 }123 break;124 }125

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

lines 126–133why, one step back
126 // write strings in utf-8
127 if ('string' === typeof body) {128 encoding = 'utf8';129 type = this.get('Content-Type');130131 // reflect this in content-type132 if ('string' === typeof type) {133 this.set('Content-Type', setCharset(type, 'utf-8'));

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 134–150why, one step back
134 }
135 }136137 // populate Content-Length138 if (undefined !== body && !this.get('Content-Length')) {139 len = Buffer.isBuffer(body)140 ? body.length141 : Buffer.byteLength(body, encoding);142 this.set('Content-Length', len);143 }144145 // ETag support146 var etag = len !== undefined && app.get('etag fn');147 if (etag && ('GET' === req.method || 'HEAD' === req.method)) {148 if (!this.get('ETag')) {149 etag = etag(body, encoding);150 etag && this.set('ETag', etag);

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

lines 151–153why, one step back
151 }
152 }153

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 154–165why, one step back
154 // freshness
155 if (req.fresh) this.statusCode = 304;156157 // strip irrelevant headers158 if (204 == this.statusCode || 304 == this.statusCode) {159 this.removeHeader('Content-Type');160 this.removeHeader('Content-Length');161 this.removeHeader('Transfer-Encoding');162 body = '';163 }164165 // respond

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

lines 166–167why, one step back
166 this.end((head ? null : body), encoding);
167

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 168–189why, one step back
168 return this;
169};170171/**172 * Send JSON response.173 *174 * Examples:175 *176 * res.json(null);177 * res.json({ user: 'tj' });178 * res.json(500, 'oh noes!');179 * res.json(404, 'I dont have that');180 *181 * @api public182 */183184res.json = function(obj){185 // allow status / body186 if (2 == arguments.length) {187 // res.json(body, status) backwards compat188 if ('number' == typeof arguments[1]) {189 this.statusCode = arguments[1];

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

lines 190–194why, one step back
190 if (typeof obj === 'number') {
191 deprecate('res.json(obj, status): Use res.json(status, obj) instead');192 } else {193 deprecate('res.json(num, status): Use res.status(status).json(num) instead');194 }

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 195–231why, one step back
195 } else {
196 this.statusCode = obj;197 obj = arguments[1];198 }199 }200201 // settings202 var app = this.app;203 var replacer = app.get('json replacer');204 var spaces = app.get('json spaces');205 var body = JSON.stringify(obj, replacer, spaces);206207 // content-type208 this.get('Content-Type') || this.set('Content-Type', 'application/json');209210 return this.send(body);211};212213/**214 * Send JSON response with JSONP callback support.215 *216 * Examples:217 *218 * res.jsonp(null);219 * res.jsonp({ user: 'tj' });220 * res.jsonp(500, 'oh noes!');221 * res.jsonp(404, 'I dont have that');222 *223 * @api public224 */225226res.jsonp = function(obj){227 // allow status / body228 if (2 == arguments.length) {229 // res.json(body, status) backwards compat230 if ('number' == typeof arguments[1]) {231 this.statusCode = arguments[1];

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

lines 232–236why, one step back
232 if (typeof obj === 'number') {
233 deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');234 } else {235 deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');236 }

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 237–252why, one step back
237 } else {
238 this.statusCode = obj;239 obj = arguments[1];240 }241 }242243 // settings244 var app = this.app;245 var replacer = app.get('json replacer');246 var spaces = app.get('json spaces');247 var body = JSON.stringify(obj, replacer, spaces)248 .replace(/\u2028/g, '\\u2028')249 .replace(/\u2029/g, '\\u2029');250 var callback = this.req.query[app.get('jsonp callback name')];251252 // content-type

Keep previous Content-Type for res.jsonpAlberto Lealbefore adoptionbe997fd

line 253why, one step back
253 this.get('Content-Type') || this.set('Content-Type', 'application/json');

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

line 254why, one step back
254

Merge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84

lines 255–259why, one step back
255 // fixup callback
256 if (Array.isArray(callback)) {257 callback = callback[0];258 }259

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

line 260why, one step back
260 // jsonp

Merge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84

line 261why, one step back
261 if (callback && 'string' === typeof callback) {

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 262–280why, one step back
262 this.set('Content-Type', 'text/javascript');
263 var cb = callback.replace(/[^\[\]\w$.]/g, '');264 body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';265 }266267 return this.send(body);268};269270/**271 * Transfer the file at the given `path`.272 *273 * Automatically sets the _Content-Type_ response header field.274 * The callback `fn(err)` is invoked when the transfer is complete275 * or when an error occurs. Be sure to check `res.sentHeader`276 * if you wish to attempt responding, as the header and some data277 * may have already been transferred.278 *279 * Options:280 *

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 281–284why, one step back
281 * - `maxAge` defaulting to 0 (can be string converted by `ms`)
282 * - `root` root directory for relative filenames283 * - `headers` object of headers to serve with file284 * - `hidden` serve hidden files, defaulting to false

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

line 285why, one step back
285 *

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

lines 286–287why, one step back
286 * Other options are passed along to `send`.
287 *

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 288–311why, one step back
288 * Examples:
289 *290 * The following example illustrates how `res.sendfile()` may291 * be used as an alternative for the `static()` middleware for292 * dynamic situations. The code backing `res.sendfile()` is actually293 * the same code, so HTTP cache support etc is identical.294 *295 * app.get('/user/:uid/photos/:file', function(req, res){296 * var uid = req.params.uid297 * , file = req.params.file;298 *299 * req.user.mayViewFilesFrom(uid, function(yes){300 * if (yes) {301 * res.sendfile('/uploads/' + uid + '/' + file);302 * } else {303 * res.send(403, 'Sorry! you cant see that.');304 * }305 * });306 * });307 *308 * @api public309 */310311res.sendfile = function(path, options, fn){

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 312–316why, one step back
312 options = options || {};
313 var self = this;314 var req = self.req;315 var next = this.req.next;316 var done;

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

line 317why, one step back
317

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

line 318why, one step back
318

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 319–354why, one step back
319 // support function as second arg
320 if ('function' == typeof options) {321 fn = options;322 options = {};323 }324325 // socket errors326 req.socket.on('error', error);327328 // errors329 function error(err) {330 if (done) return;331 done = true;332333 // clean up334 cleanup();335336 // callback available337 if (fn) return fn(err);338339 // delegate340 next(err);341 }342343 // streaming344 function stream(stream) {345 if (done) return;346 cleanup();347 if (fn) stream.on('end', fn);348 }349350 // cleanup351 function cleanup() {352 req.socket.removeListener('error', error);353 }354

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

lines 355–357why, one step back
355 // Back-compat
356 options.maxage = options.maxage || options.maxAge || 0;357

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

line 358why, one step back
358 // transfer

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

line 359why, one step back
359 var file = send(req, path, options);

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 360–362why, one step back
360 file.on('error', error);
361 file.on('directory', next);362 file.on('stream', stream);

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 363–377why, one step back
363
364 if (options.headers) {365 // set headers on successful transfer366 file.on('headers', function headers(res) {367 var obj = options.headers;368 var keys = Object.keys(obj);369370 for (var i = 0; i < keys.length; i++) {371 var k = keys[i];372 res.setHeader(k, obj[k]);373 }374 });375 }376377 // pipe

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 378–387why, one step back
378 file.pipe(this);
379 this.on('finish', cleanup);380};381382/**383 * Transfer the file at the given `path` as an attachment.384 *385 * Optionally providing an alternate attachment `filename`,386 * and optional callback `fn(err)`. The callback is invoked387 * when the data transfer is complete, or when an error has

remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289

line 388why, one step back
388 * ocurred. Be sure to check `res.headersSent` if you plan to respond.

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 389–402why, one step back
389 *
390 * This method uses `res.sendfile()`.391 *392 * @api public393 */394395res.download = function(path, filename, fn){396 // support function as second arg397 if ('function' == typeof filename) {398 fn = filename;399 filename = null;400 }401402 filename = filename || path;

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 403–409why, one step back
403
404 // set Content-Disposition when file is sent405 var headers = {406 'Content-Disposition': contentDisposition(filename)407 };408409 return this.sendfile(path, { headers: headers }, fn);

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 410–493why, one step back
410};
411412/**413 * Set _Content-Type_ response header with `type` through `mime.lookup()`414 * when it does not contain "/", or set the Content-Type to `type` otherwise.415 *416 * Examples:417 *418 * res.type('.html');419 * res.type('html');420 * res.type('json');421 * res.type('application/json');422 * res.type('png');423 *424 * @param {String} type425 * @return {ServerResponse} for chaining426 * @api public427 */428429res.contentType =430res.type = function(type){431 return this.set('Content-Type', ~type.indexOf('/')432 ? type433 : mime.lookup(type));434};435436/**437 * Respond to the Acceptable formats using an `obj`438 * of mime-type callbacks.439 *440 * This method uses `req.accepted`, an array of441 * acceptable types ordered by their quality values.442 * When "Accept" is not present the _first_ callback443 * is invoked, otherwise the first match is used. When444 * no match is performed the server responds with445 * 406 "Not Acceptable".446 *447 * Content-Type is set for you, however if you choose448 * you may alter this within the callback using `res.type()`449 * or `res.set('Content-Type', ...)`.450 *451 * res.format({452 * 'text/plain': function(){453 * res.send('hey');454 * },455 *456 * 'text/html': function(){457 * res.send('<p>hey</p>');458 * },459 *460 * 'appliation/json': function(){461 * res.send({ message: 'hey' });462 * }463 * });464 *465 * In addition to canonicalized MIME types you may466 * also use extnames mapped to these types:467 *468 * res.format({469 * text: function(){470 * res.send('hey');471 * },472 *473 * html: function(){474 * res.send('<p>hey</p>');475 * },476 *477 * json: function(){478 * res.send({ message: 'hey' });479 * }480 * });481 *482 * By default Express passes an `Error`483 * with a `.status` of 406 to `next(err)`484 * if a match is not made. If you provide485 * a `.default` callback it will be invoked486 * instead.487 *488 * @param {Object} obj489 * @return {ServerResponse} for chaining490 * @api public491 */492493res.format = function(obj){

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 494–495why, one step back
494 var req = this.req;
495 var next = req.next;

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 496–505why, one step back
496
497 var fn = obj.default;498 if (fn) delete obj.default;499 var keys = Object.keys(obj);500501 var key = req.accepts(keys);502503 this.vary("Accept");504505 if (key) {

remove res.charset usageJonathan Ongbefore adoption2064f41

line 506why, one step back
506 this.set('Content-Type', normalizeType(key).value);

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 507–529why, one step back
507 obj[key](req, this, next);
508 } else if (fn) {509 fn();510 } else {511 var err = new Error('Not Acceptable');512 err.status = 406;513 err.types = normalizeTypes(keys).map(function(o){ return o.value });514 next(err);515 }516517 return this;518};519520/**521 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.522 *523 * @param {String} filename524 * @return {ServerResponse}525 * @api public526 */527528res.attachment = function(filename){529 if (filename) this.type(extname(filename));

Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9

line 530why, one step back
530 this.set('Content-Disposition', contentDisposition(filename));

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 531–556why, one step back
531 return this;
532};533534/**535 * Set header `field` to `val`, or pass536 * an object of header fields.537 *538 * Examples:539 *540 * res.set('Foo', ['bar', 'baz']);541 * res.set('Accept', 'application/json');542 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });543 *544 * Aliased as `res.header()`.545 *546 * @param {String|Object|Array} field547 * @param {String} val548 * @return {ServerResponse} for chaining549 * @api public550 */551552res.set =553res.header = function(field, val){554 if (2 == arguments.length) {555 if (Array.isArray(val)) val = val.map(String);556 else val = String(val);

preserve casing of headers in res.header and res.setDouglas Christopher Wilsonbefore adoption1536a21

line 557why, one step back
557 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {

move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7

lines 558–560why, one step back
558 var charset = mime.charsets.lookup(val.split(';')[0]);
559 if (charset) val += '; charset=' + charset.toLowerCase();560 }

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 561–593why, one step back
561 this.setHeader(field, val);
562 } else {563 for (var key in field) {564 this.set(key, field[key]);565 }566 }567 return this;568};569570/**571 * Get value for header `field`.572 *573 * @param {String} field574 * @return {String}575 * @api public576 */577578res.get = function(field){579 return this.getHeader(field);580};581582/**583 * Clear cookie `name`.584 *585 * @param {String} name586 * @param {Object} options587 * @param {ServerResponse} for chaining588 * @api public589 */590591res.clearCookie = function(name, options){592 var opts = { expires: new Date(1), path: '/' };593 return this.cookie(name, '', options

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 594why, one step back
594 ? mixin(opts, options)

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 595–621why, one step back
595 : opts);
596};597598/**599 * Set cookie `name` to `val`, with the given `options`.600 *601 * Options:602 *603 * - `maxAge` max-age in milliseconds, converted to `expires`604 * - `signed` sign the cookie605 * - `path` defaults to "/"606 *607 * Examples:608 *609 * // "Remember Me" for 15 minutes610 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });611 *612 * // save as above613 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })614 *615 * @param {String} name616 * @param {String|Object} val617 * @param {Options} options618 * @api public619 */620621res.cookie = function(name, val, options){

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 622why, one step back
622 options = mixin({}, options);

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 623–624why, one step back
623 var secret = this.req.secret;
624 var signed = options.signed;

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

line 625why, one step back
625 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 626–633why, one step back
626 if ('number' == typeof val) val = val.toString();
627 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);628 if (signed) val = 's:' + sign(val, secret);629 if ('maxAge' in options) {630 options.expires = new Date(Date.now() + options.maxAge);631 options.maxAge /= 1000;632 }633 if (null == options.path) options.path = '/';

move support for multiple `res.cookie` calls to lib/responseRoman Shtylmanbefore adoptiond42d8f5

lines 634–645why, one step back
634 var headerVal = cookie.serialize(name, String(val), options);
635636 // supports multiple 'res.cookie' calls by getting previous value637 var prev = this.get('Set-Cookie');638 if (prev) {639 if (Array.isArray(prev)) {640 headerVal = prev.concat(headerVal);641 } else {642 headerVal = [prev, headerVal];643 }644 }645 this.set('Set-Cookie', headerVal);

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 646–659why, one step back
646 return this;
647};648649650/**651 * Set the location header to `url`.652 *653 * The given `url` can also be "back", which redirects654 * to the _Referrer_ or _Referer_ headers or "/".655 *656 * Examples:657 *658 * res.location('/foo/bar').;659 * res.location('http://example.com');

res.location: remove resolving relative urlsJonathan Ongbefore adoptionaac1d52

line 660why, one step back
660 * res.location('../login');

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 661–666why, one step back
661 *
662 * @param {String} url663 * @api public664 */665666res.location = function(url){

res.location: remove resolving relative urlsJonathan Ongbefore adoptionaac1d52

line 667why, one step back
667 var req = this.req;

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 668–698why, one step back
668
669 // "back" is an alias for the referrer670 if ('back' == url) url = req.get('Referrer') || '/';671672 // Respond673 this.set('Location', url);674 return this;675};676677/**678 * Redirect to the given `url` with optional response `status`679 * defaulting to 302.680 *681 * The resulting `url` is determined by `res.location()`, so682 * it will play nicely with mounted apps, relative paths,683 * `"back"` etc.684 *685 * Examples:686 *687 * res.redirect('/foo/bar');688 * res.redirect('http://example.com');689 * res.redirect(301, 'http://example.com');690 * res.redirect('http://example.com', 301);691 * res.redirect('../login'); // /blog/post/1 -> /blog/login692 *693 * @param {String} url694 * @param {Number} code695 * @api public696 */697698res.redirect = function(url){

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 699–701why, one step back
699 var head = 'HEAD' == this.req.method;
700 var status = 302;701 var body;

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 702–723why, one step back
702
703 // allow status / url704 if (2 == arguments.length) {705 if ('number' == typeof url) {706 status = url;707 url = arguments[1];708 } else {709 status = arguments[1];710 }711 }712713 // Set location header714 this.location(url);715 url = this.get('Location');716717 // Support text/{plain,html} by default718 this.format({719 text: function(){720 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);721 },722723 html: function(){

use escape-html module to escape htmlRoman Shtylmanbefore adoption63c6a9c

line 724why, one step back
724 var u = escapeHtml(url);

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 725–748why, one step back
725 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';
726 },727728 default: function(){729 body = '';730 }731 });732733 // Respond734 this.statusCode = status;735 this.set('Content-Length', Buffer.byteLength(body));736 this.end(head ? null : body);737};738739/**740 * Add `field` to Vary. If already present in the Vary set, then741 * this call is simply ignored.742 *743 * @param {Array|String} field744 * @param {ServerResponse} for chaining745 * @api public746 */747748res.vary = function(field){

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

line 749why, one step back
749 // checks for back-compat

add deprecation message to res.vary()Douglas Christopher Wilsonbefore adoption381b3b0

lines 750–753why, one step back
750 if (!field || (Array.isArray(field) && !field.length)) {
751 deprecate('res.vary(): Provide a field name');752 return this;753 }

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

line 754why, one step back
754

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

line 755why, one step back
755 vary(this, field);

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 756–773why, one step back
756
757 return this;758};759760/**761 * Render `view` with the given `options` and optional callback `fn`.762 * When a callback function is given a response will _not_ be made763 * automatically, otherwise a response of _200_ and _text/html_ is given.764 *765 * Options:766 *767 * - `cache` boolean hinting to the engine it should cache768 * - `filename` filename of the view being rendered769 *770 * @api public771 */772773res.render = function(view, options, fn){

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 774–777why, one step back
774 options = options || {};
775 var self = this;776 var req = this.req;777 var app = req.app;

use 8 threads for benchmarksTJ Holowaychukbefore adoption3baca25

lines 778–795why, one step back
778
779 // support callback function as second arg780 if ('function' == typeof options) {781 fn = options, options = {};782 }783784 // merge res.locals785 options._locals = self.locals;786787 // default callback to respond788 fn = fn || function(err, str){789 if (err) return req.next(err);790 self.send(str);791 };792793 // render794 app.render(view, options, fn);795};