Skip to content
Myr

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 file

Take it

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

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

move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7

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

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

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

move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 21–58why, one step back
21
22/**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 back
59 var link = this.get('Link') || '';
60 if (link) link += ', ';61 return this.set('Link', link + Object.keys(links).map(function(rel){

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 62–110why, one step back
62 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;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 back
111 if (!this.get('Content-Type')) this.type('html');

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 112–133why, one step back
112 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/ support

Include ETag in HEAD requestsTiago Relvaobefore adoption3c7310e

line 134why, one step back
134 if (app.settings.etag && len && ('GET' == req.method || 'HEAD' == req.method)) {

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 135–177why, one step back
135 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 back
178 return 'number' === typeof obj
179 ? jsonNumDeprecated.call(this, obj)180 : jsonDeprecated.call(this, obj);

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 181–198why, one step back
181 } 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};198

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

lines 199–204why, one step back
199var 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');204

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 205–226why, one step back
205/**
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 back
227 return 'number' === typeof obj
228 ? jsonpNumDeprecated.call(this, obj)229 : jsonpDeprecated.call(this, obj);

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 230–245why, one step back
230 } 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-type

Keep previous Content-Type for res.jsonpAlberto Lealbefore adoptionbe997fd

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

line 247why, one step back
247

Merge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84

lines 248–252why, one step back
248 // fixup callback
249 if (Array.isArray(callback)) {250 callback = callback[0];251 }252

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

line 253why, one step back
253 // jsonp

Merge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 255–256why, one step back
255 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 back
257 body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 258–261why, one step back
258 }
259260 return this.send(body);261};

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

lines 262–267why, one step back
262
263var 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');

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 268–281why, one step back
268
269/**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 filenames

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

line 282why, one step back
282 * - `hidden` serve hidden files, defaulting to false

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

line 283why, one step back
283 *

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 286–312why, one step back
286 * 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 back
313 options = options || {};
314 var self = this;315 var req = self.req;316 var next = this.req.next;317 var done;

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

line 318why, one step back
318

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

line 319why, one step back
319

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 320–335why, one step back
320 // support function as second arg
321 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 back
336 if (!self.headersSent) self.removeHeader('Content-Disposition');

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 337–341why, one step back
337
338 // callback available339 if (fn) return fn(err);340341 // list in limbo if there's no callback

remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289

line 342why, one step back
342 if (self.headersSent) return;

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 343–348why, one step back
343
344 // delegate345 next(err);346 }347348 // streaming

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption0b88208

line 349why, one step back
349 function stream(stream) {

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 350–351why, one step back
350 if (done) return;
351 cleanup();

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption0b88208

line 352why, one step back
352 if (fn) stream.on('end', fn);

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 353–359why, one step back
353 }
354355 // cleanup356 function cleanup() {357 req.socket.removeListener('error', error);358 }359

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

lines 360–362why, one step back
360 // Back-compat
361 options.maxage = options.maxage || options.maxAge || 0;362

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

line 363why, one step back
363 // transfer

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 365–377why, one step back
365 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 has

remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 379–395why, one step back
379 *
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 back
396 this.set('Content-Disposition', contentDisposition(filename));

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 397–481why, one step back
397 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 back
482 var req = this.req;
483 var next = req.next;

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 484–490why, one step back
484
485 var fn = obj.default;486 if (fn) delete obj.default;487 var keys = Object.keys(obj);488489 var key = req.accepts(keys);490

add res.vary(). Closes #1682cjihrigbefore adoptione5de08f

line 491why, one step back
491 this.vary("Accept");

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 492–493why, one step back
492
493 if (key) {

remove res.charset usageJonathan Ongbefore adoption2064f41

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 495–517why, one step back
495 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 back
518 this.set('Content-Disposition', contentDisposition(filename));

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 519–544why, one step back
519 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 back
545 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {

move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 549–581why, one step back
549 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, '', options

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 583–609why, one step back
583 : 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 back
610 options = mixin({}, options);

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

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

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 614–621why, one step back
614 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 back
622 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);

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 634–640why, one step back
634 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 back
641 * The given `url` can also be "back", which redirects

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 642–647why, one step back
642 * 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 back
648 * res.location('../login');

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 649–654why, one step back
649 *
650 * @param {String} url651 * @api public652 */653654res.location = function(url){

res.location: remove resolving relative urlsJonathan Ongbefore adoptionaac1d52

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

line 656why, one step back
656

Merge pull request #1829 from michaelficarra/patch-1TJ Holowaychukbefore adoptionde54af4

line 657why, one step back
657 // "back" is an alias for the referrer

ocdTJ Holowaychukbefore adoption8a7a695

line 658why, one step back
658 if ('back' == url) url = req.get('Referrer') || '/';

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 659–686why, one step back
659
660 // 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 back
687 var head = 'HEAD' == this.req.method;
688 var status = 302;689 var body;

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 690–711why, one step back
690
691 // 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 back
712 var u = escapeHtml(url);

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 713–724why, one step back
713 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 back
725};
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');751

Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionbd8b9f5

line 752why, one step back
752 // append

add res.vary(). Closes #1682cjihrigbefore adoptione5de08f

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

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 763–781why, one step back
763};
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 back
782 options = options || {};
783 var self = this;784 var req = this.req;785 var app = req.app;

Release 3.3.8TJ Holowaychukbefore adoptionf1c46f5

lines 786–803why, one step back
786
787 // 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};