response.js
This file
Path
lib/response.js
757 lines · 17.4 KiB · JavaScript
Last changed by
remove charset from json responses. Closes #1631TJ Holowaychukbefore adoption138d74a
History of this fileTake it
The walk stopped after 200 commits: lines older than 75debbe point at it.
update connect depTJ Holowaychukbefore adoption75debbe
lines 1–4why, one step back1/**2 * Module dependencies.3 */4Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption2d49c0d
line 5why, one step back5var http = require('http')update connect depTJ Holowaychukbefore adoption75debbe
lines 6–8why, one step back6 , path = require('path')7 , connect = require('connect')8 , utils = connect.utilsupdate connectTJ Holowaychukbefore adoption612fc47
line 9why, one step back9 , sign = require('cookie-signature').signupdate connect depTJ Holowaychukbefore adoption75debbe
lines 10–11why, one step back10 , normalizeType = require('./utils').normalizeType11 , normalizeTypes = require('./utils').normalizeTypesadd etag utilTJ Holowaychukbefore adoptionf2f0976
line 12why, one step back12 , etag = require('./utils').etagupdate connect depTJ Holowaychukbefore adoption75debbe
lines 13–80why, one step back13 , statusCodes = http.STATUS_CODES14 , cookie = require('cookie')15 , send = require('send')16 , mime = connect.mime17 , basename = path.basename18 , extname = path.extname19 , join = path.join;2021/**22 * Response prototype.23 */2425var res = module.exports = {26 __proto__: http.ServerResponse.prototype27};2829/**30 * Set status `code`.31 *32 * @param {Number} code33 * @return {ServerResponse}34 * @api public35 */3637res.status = function(code){38 this.statusCode = code;39 return this;40};4142/**43 * Set Link header field with the given `links`.44 *45 * Examples:46 *47 * res.links({48 * next: 'http://api.example.com/users?page=2',49 * last: 'http://api.example.com/users?page=5'50 * });51 *52 * @param {Object} links53 * @return {ServerResponse}54 * @api public55 */5657res.links = function(links){58 return this.set('Link', Object.keys(links).map(function(rel){59 return '<' + links[rel] + '>; rel="' + rel + '"';60 }).join(', '));61};6263/**64 * Send a response.65 *66 * Examples:67 *68 * res.send(new Buffer('wahoo'));69 * res.send({ some: 'json' });70 * res.send('<p>some html</p>');71 * res.send(404, 'Sorry, cant find that');72 * res.send(404);73 *74 * @param {Mixed} body or status75 * @param {Mixed} body76 * @return {ServerResponse}77 * @api public78 */7980res.send = function(body){change generation of ETags with res.send() to GET requests only. Closes #1619TJ Holowaychukbefore adoption3296ed9
lines 81–83why, one step back81 var req = this.req;82 var head = 'HEAD' == req.method;83 var len;update connect depTJ Holowaychukbefore adoption75debbe
lines 84–130why, one step back8485 // allow status / body86 if (2 == arguments.length) {87 // res.send(body, status) backwards compat88 if ('number' != typeof body && 'number' == typeof arguments[1]) {89 this.statusCode = arguments[1];90 } else {91 this.statusCode = body;92 body = arguments[1];93 }94 }9596 switch (typeof body) {97 // response status98 case 'number':99 this.get('Content-Type') || this.type('txt');100 this.statusCode = body;101 body = http.STATUS_CODES[body];102 break;103 // string defaulting to html104 case 'string':105 if (!this.get('Content-Type')) {106 this.charset = this.charset || 'utf-8';107 this.type('html');108 }109 break;110 case 'boolean':111 case 'object':112 if (null == body) {113 body = '';114 } else if (Buffer.isBuffer(body)) {115 this.get('Content-Type') || this.type('bin');116 } else {117 return this.json(body);118 }119 break;120 }121122 // populate Content-Length123 if (undefined !== body && !this.get('Content-Length')) {124 this.set('Content-Length', len = Buffer.isBuffer(body)125 ? body.length126 : Buffer.byteLength(body));127 }128129 // ETag support130 // TODO: W/ supportchange generation of ETags with res.send() to GET requests only. Closes #1619TJ Holowaychukbefore adoption3296ed9
line 131why, one step back131 if (len > 1024 && 'GET' == req.method) {add etag utilTJ Holowaychukbefore adoptionf2f0976
lines 132–134why, one step back132 if (!this.get('ETag')) {133 this.set('ETag', etag(body));134 }update connect depTJ Holowaychukbefore adoption75debbe
lines 135–143why, one step back135 }136137 // freshness138 if (req.fresh) this.statusCode = 304;139140 // strip irrelevant headers141 if (204 == this.statusCode || 304 == this.statusCode) {142 this.removeHeader('Content-Type');143 this.removeHeader('Content-Length');Merge pull request #1451 from aweeks/fix-304-must-not-contain-bodyTJ Holowaychukbefore adoption3c4fd57
line 144why, one step back144 this.removeHeader('Transfer-Encoding');update connect depTJ Holowaychukbefore adoption75debbe
lines 145–181why, one step back145 body = '';146 }147148 // respond149 this.end(head ? null : body);150 return this;151};152153/**154 * Send JSON response.155 *156 * Examples:157 *158 * res.json(null);159 * res.json({ user: 'tj' });160 * res.json(500, 'oh noes!');161 * res.json(404, 'I dont have that');162 *163 * @param {Mixed} obj or status164 * @param {Mixed} obj165 * @return {ServerResponse}166 * @api public167 */168169res.json = function(obj){170 // allow status / body171 if (2 == arguments.length) {172 // res.json(body, status) backwards compat173 if ('number' == typeof arguments[1]) {174 this.statusCode = arguments[1];175 } else {176 this.statusCode = obj;177 obj = arguments[1];178 }179 }180181 // settingsadd res.jsonp(). Closes #1307TJ Holowaychukbefore adoptiona6caa26
lines 182–185why, one step back182 var app = this.app;183 var replacer = app.get('json replacer');184 var spaces = app.get('json spaces');185 var body = JSON.stringify(obj, replacer, spaces);update connect depTJ Holowaychukbefore adoption75debbe
lines 186–187why, one step back186187 // content-typerefactorTJ Holowaychukbefore adoption88072a5
line 188why, one step back188 this.get('Content-Type') || this.set('Content-Type', 'application/json');refactor vhost exampleTJ Holowaychukbefore adoptionbb29da5
line 189why, one step back189add res.jsonp(). Closes #1307TJ Holowaychukbefore adoptiona6caa26
lines 190–224why, one step back190 return this.send(body);191};192193/**194 * Send JSON response with JSONP callback support.195 *196 * Examples:197 *198 * res.jsonp(null);199 * res.jsonp({ user: 'tj' });200 * res.jsonp(500, 'oh noes!');201 * res.jsonp(404, 'I dont have that');202 *203 * @param {Mixed} obj or status204 * @param {Mixed} obj205 * @return {ServerResponse}206 * @api public207 */208209res.jsonp = function(obj){210 // allow status / body211 if (2 == arguments.length) {212 // res.json(body, status) backwards compat213 if ('number' == typeof arguments[1]) {214 this.statusCode = arguments[1];215 } else {216 this.statusCode = obj;217 obj = arguments[1];218 }219 }220221 // settings222 var app = this.app;223 var replacer = app.get('json replacer');224 var spaces = app.get('json spaces');fix jsonp whitespace escape. Closes #1132Guillermo Rauchbefore adoption64a2349
lines 225–227why, one step back225 var body = JSON.stringify(obj, replacer, spaces)226 .replace(/\u2028/g, '\\u2028')227 .replace(/\u2029/g, '\\u2029');add res.jsonp(). Closes #1307TJ Holowaychukbefore adoptiona6caa26
lines 228–232why, one step back228 var callback = this.req.query[app.get('jsonp callback name')];229230 // content-type231 this.charset = this.charset || 'utf-8';232 this.set('Content-Type', 'application/json');refactor vhost exampleTJ Holowaychukbefore adoptionbb29da5
line 233why, one step back233update connect depTJ Holowaychukbefore adoption75debbe
line 234why, one step back234 // jsonpadd res.jsonp(). Closes #1307TJ Holowaychukbefore adoptiona6caa26
line 235why, one step back235 if (callback) {Merge pull request #1643 from jonjenkins/masterTJ Holowaychukbefore adoption28562b2
line 236why, one step back236 if (callback instanceof Array) callback = callback[0];update connect depTJ Holowaychukbefore adoption75debbe
line 237why, one step back237 this.set('Content-Type', 'text/javascript');add cb && cb(payload) to `res.jsonp()`. Closes #1374TJ Holowaychukbefore adoptionb3936b9
lines 238–239why, one step back238 var cb = callback.replace(/[^\[\]\w$.]/g, '');239 body = cb + ' && ' + cb + '(' + body + ');';update connect depTJ Holowaychukbefore adoption75debbe
lines 240–246why, one step back240 }241242 return this.send(body);243};244245/**246 * Transfer the file at the given `path`.refactor vhost exampleTJ Holowaychukbefore adoptionbb29da5
line 247why, one step back247 *update connect depTJ Holowaychukbefore adoption75debbe
lines 248–268why, one step back248 * Automatically sets the _Content-Type_ response header field.249 * The callback `fn(err)` is invoked when the transfer is complete250 * or when an error occurs. Be sure to check `res.sentHeader`251 * if you wish to attempt responding, as the header and some data252 * may have already been transferred.253 *254 * Options:255 *256 * - `maxAge` defaulting to 0257 * - `root` root directory for relative filenames258 *259 * Examples:260 *261 * The following example illustrates how `res.sendfile()` may262 * be used as an alternative for the `static()` middleware for263 * dynamic situations. The code backing `res.sendfile()` is actually264 * the same code, so HTTP cache support etc is identical.265 *266 * app.get('/user/:uid/photos/:file', function(req, res){267 * var uid = req.params.uid268 * , file = req.params.file;refactor vhost exampleTJ Holowaychukbefore adoptionbb29da5
line 269why, one step back269 *update connect depTJ Holowaychukbefore adoption75debbe
lines 270–413why, one step back270 * req.user.mayViewFilesFrom(uid, function(yes){271 * if (yes) {272 * res.sendfile('/uploads/' + uid + '/' + file);273 * } else {274 * res.send(403, 'Sorry! you cant see that.');275 * }276 * });277 * });278 *279 * @param {String} path280 * @param {Object|Function} options or fn281 * @param {Function} fn282 * @api public283 */284285res.sendfile = function(path, options, fn){286 var self = this287 , req = self.req288 , next = this.req.next289 , options = options || {}290 , done;291292 // support function as second arg293 if ('function' == typeof options) {294 fn = options;295 options = {};296 }297298 // socket errors299 req.socket.on('error', error);300301 // errors302 function error(err) {303 if (done) return;304 done = true;305306 // clean up307 cleanup();308 if (!self.headerSent) self.removeHeader('Content-Disposition');309310 // callback available311 if (fn) return fn(err);312313 // list in limbo if there's no callback314 if (self.headerSent) return;315316 // delegate317 next(err);318 }319320 // streaming321 function stream() {322 if (done) return;323 cleanup();324 if (fn) self.on('finish', fn);325 }326327 // cleanup328 function cleanup() {329 req.socket.removeListener('error', error);330 }331332 // transfer333 var file = send(req, path);334 if (options.root) file.root(options.root);335 file.maxage(options.maxAge || 0);336 file.on('error', error);337 file.on('directory', next);338 file.on('stream', stream);339 file.pipe(this);340 this.on('finish', cleanup);341};342343/**344 * Transfer the file at the given `path` as an attachment.345 *346 * Optionally providing an alternate attachment `filename`,347 * and optional callback `fn(err)`. The callback is invoked348 * when the data transfer is complete, or when an error has349 * ocurred. Be sure to check `res.headerSent` if you plan to respond.350 *351 * This method uses `res.sendfile()`.352 *353 * @param {String} path354 * @param {String|Function} filename or fn355 * @param {Function} fn356 * @api public357 */358359res.download = function(path, filename, fn){360 // support function as second arg361 if ('function' == typeof filename) {362 fn = filename;363 filename = null;364 }365366 filename = filename || path;367 this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');368 return this.sendfile(path, fn);369};370371/**372 * Set _Content-Type_ response header with `type` through `mime.lookup()`373 * when it does not contain "/", or set the Content-Type to `type` otherwise.374 *375 * Examples:376 *377 * res.type('.html');378 * res.type('html');379 * res.type('json');380 * res.type('application/json');381 * res.type('png');382 *383 * @param {String} type384 * @return {ServerResponse} for chaining385 * @api public386 */387388res.contentType =389res.type = function(type){390 return this.set('Content-Type', ~type.indexOf('/')391 ? type392 : mime.lookup(type));393};394395/**396 * Respond to the Acceptable formats using an `obj`397 * of mime-type callbacks.398 *399 * This method uses `req.accepted`, an array of400 * acceptable types ordered by their quality values.401 * When "Accept" is not present the _first_ callback402 * is invoked, otherwise the first match is used. When403 * no match is performed the server responds with404 * 406 "Not Acceptable".405 *406 * Content-Type is set for you, however if you choose407 * you may alter this within the callback using `res.type()`408 * or `res.set('Content-Type', ...)`.409 *410 * res.format({411 * 'text/plain': function(){412 * res.send('hey');413 * },refactor vhost exampleTJ Holowaychukbefore adoptionbb29da5
line 414why, one step back414 *update connect depTJ Holowaychukbefore adoption75debbe
lines 415–417why, one step back415 * 'text/html': function(){416 * res.send('<p>hey</p>');417 * },refactor vhost exampleTJ Holowaychukbefore adoptionbb29da5
line 418why, one step back418 *update connect depTJ Holowaychukbefore adoption75debbe
lines 419–430why, one step back419 * 'appliation/json': function(){420 * res.send({ message: 'hey' });421 * }422 * });423 *424 * In addition to canonicalized MIME types you may425 * also use extnames mapped to these types:426 *427 * res.format({428 * text: function(){429 * res.send('hey');430 * },refactor vhost exampleTJ Holowaychukbefore adoptionbb29da5
line 431why, one step back431 *update connect depTJ Holowaychukbefore adoption75debbe
lines 432–434why, one step back432 * html: function(){433 * res.send('<p>hey</p>');434 * },refactor vhost exampleTJ Holowaychukbefore adoptionbb29da5
line 435why, one step back435 *update connect depTJ Holowaychukbefore adoption75debbe
lines 436–452why, one step back436 * json: function(){437 * res.send({ message: 'hey' });438 * }439 * });440 *441 * By default Express passes an `Error`442 * with a `.status` of 406 to `next(err)`443 * if a match is not made. If you provide444 * a `.default` callback it will be invoked445 * instead.446 *447 * @param {Object} obj448 * @return {ServerResponse} for chaining449 * @api public450 */451452res.format = function(obj){refactor res.format(), dont pass "default" to req.accepts()TJ Holowaychukbefore adoption8edf358
line 453why, one step back453 var req = this.requpdate connect depTJ Holowaychukbefore adoption75debbe
lines 454–457why, one step back454 , next = req.next;455456 var fn = obj.default;457 if (fn) delete obj.default;refactor res.format(), dont pass "default" to req.accepts()TJ Holowaychukbefore adoption8edf358
line 458why, one step back458 var keys = Object.keys(obj);update connect depTJ Holowaychukbefore adoption75debbe
lines 459–464why, one step back459460 var key = req.accepts(keys);461462 this.set('Vary', 'Accept');463464 if (key) {add support for custom Accept parametersPavel Brylovbefore adoption9e684d4
line 465why, one step back465 this.set('Content-Type', normalizeType(key).value);update connect depTJ Holowaychukbefore adoption75debbe
lines 466–471why, one step back466 obj[key](req, this, next);467 } else if (fn) {468 fn();469 } else {470 var err = new Error('Not Acceptable');471 err.status = 406;add support for custom Accept parametersPavel Brylovbefore adoption9e684d4
line 472why, one step back472 err.types = normalizeTypes(keys).map(function(o){ return o.value });update connect depTJ Holowaychukbefore adoption75debbe
lines 473–500why, one step back473 next(err);474 }475476 return this;477};478479/**480 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.481 *482 * @param {String} filename483 * @return {ServerResponse}484 * @api public485 */486487res.attachment = function(filename){488 if (filename) this.type(extname(filename));489 this.set('Content-Disposition', filename490 ? 'attachment; filename="' + basename(filename) + '"'491 : 'attachment');492 return this;493};494495/**496 * Set header `field` to `val`, or pass497 * an object of header fields.498 *499 * Examples:500 *refactor res.set() array supportTJ Holowaychukbefore adoptiona4b2e48
line 501why, one step back501 * res.set('Foo', ['bar', 'baz']);update connect depTJ Holowaychukbefore adoption75debbe
lines 502–504why, one step back502 * res.set('Accept', 'application/json');503 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });504 *refactor vhost exampleTJ Holowaychukbefore adoptionbb29da5
line 505why, one step back505 * Aliased as `res.header()`.update connect depTJ Holowaychukbefore adoption75debbe
line 506why, one step back506 *refactor res.set() array supportTJ Holowaychukbefore adoptiona4b2e48
line 507why, one step back507 * @param {String|Object|Array} fieldupdate connect depTJ Holowaychukbefore adoption75debbe
lines 508–512why, one step back508 * @param {String} val509 * @return {ServerResponse} for chaining510 * @api public511 */512refactor vhost exampleTJ Holowaychukbefore adoptionbb29da5
line 513why, one step back513res.set =refactor res.set() array supportTJ Holowaychukbefore adoptiona4b2e48
line 514why, one step back514res.header = function(field, val){update connect depTJ Holowaychukbefore adoption75debbe
line 515why, one step back515 if (2 == arguments.length) {refactor res.set() array supportTJ Holowaychukbefore adoptiona4b2e48
lines 516–518why, one step back516 if (Array.isArray(val)) val = val.map(String);517 else val = String(val);518 this.setHeader(field, val);update connect depTJ Holowaychukbefore adoption75debbe
lines 519–520why, one step back519 } else {520 for (var key in field) {refactor res.set() array supportTJ Holowaychukbefore adoptiona4b2e48
line 521why, one step back521 this.set(key, field[key]);update connect depTJ Holowaychukbefore adoption75debbe
lines 522–578why, one step back522 }523 }524 return this;525};526527/**528 * Get value for header `field`.529 *530 * @param {String} field531 * @return {String}532 * @api public533 */534535res.get = function(field){536 return this.getHeader(field);537};538539/**540 * Clear cookie `name`.541 *542 * @param {String} name543 * @param {Object} options544 * @param {ServerResponse} for chaining545 * @api public546 */547548res.clearCookie = function(name, options){549 var opts = { expires: new Date(1), path: '/' };550 return this.cookie(name, '', options551 ? utils.merge(opts, options)552 : opts);553};554555/**556 * Set cookie `name` to `val`, with the given `options`.557 *558 * Options:559 *560 * - `maxAge` max-age in milliseconds, converted to `expires`561 * - `signed` sign the cookie562 * - `path` defaults to "/"563 *564 * Examples:565 *566 * // "Remember Me" for 15 minutes567 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });568 *569 * // save as above570 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })571 *572 * @param {String} name573 * @param {String|Object} val574 * @param {Options} options575 * @api public576 */577578res.cookie = function(name, val, options){Merge pull request #1458 from gmethvin/cookie_optionsTJ Holowaychukbefore adoptiond4e56c1
line 579why, one step back579 options = utils.merge({}, options);update connect depTJ Holowaychukbefore adoption75debbe
lines 580–582why, one step back580 var secret = this.req.secret;581 var signed = options.signed;582 if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionea2664a
line 583why, one step back583 if ('number' == typeof val) val = val.toString();update connect depTJ Holowaychukbefore adoption75debbe
line 584why, one step back584 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);update connectTJ Holowaychukbefore adoption612fc47
line 585why, one step back585 if (signed) val = 's:' + sign(val, secret);Merge pull request #1458 from gmethvin/cookie_optionsTJ Holowaychukbefore adoptiond4e56c1
lines 586–589why, one step back586 if ('maxAge' in options) {587 options.expires = new Date(Date.now() + options.maxAge);588 options.maxAge /= 1000;589 }update connect depTJ Holowaychukbefore adoption75debbe
lines 590–594why, one step back590 if (null == options.path) options.path = '/';591 this.set('Set-Cookie', cookie.serialize(name, String(val), options));592 return this;593};594Merge branch 'integrate'TJ Holowaychukbefore adoption6b1d7a9
line 595why, one step back595update connect depTJ Holowaychukbefore adoption75debbe
line 596why, one step back596/**Merge branch 'integrate'TJ Holowaychukbefore adoption6b1d7a9
line 597why, one step back597 * Set the location header to `url`.update connect depTJ Holowaychukbefore adoption75debbe
lines 598–604why, one step back598 *599 * The given `url` can also be the name of a mapped url, for600 * example by default express supports "back" which redirects601 * to the _Referrer_ or _Referer_ headers or "/".602 *603 * Examples:604 *Merge branch 'integrate'TJ Holowaychukbefore adoption6b1d7a9
lines 605–607why, one step back605 * res.location('/foo/bar').;606 * res.location('http://example.com');607 * res.location('../login'); // /blog/post/1 -> /blog/loginupdate connect depTJ Holowaychukbefore adoption75debbe
lines 608–610why, one step back608 *609 * Mounting:610 *Merge branch 'integrate'TJ Holowaychukbefore adoption6b1d7a9
lines 611–614why, one step back611 * When an application is mounted and `res.location()`612 * is given a path that does _not_ lead with "/" it becomes613 * relative to the mount-point. For example if the application614 * is mounted at "/blog", the following would become "/blog/login".update connect depTJ Holowaychukbefore adoption75debbe
line 615why, one step back615 *Merge branch 'integrate'TJ Holowaychukbefore adoption6b1d7a9
line 616why, one step back616 * res.location('login');update connect depTJ Holowaychukbefore adoption75debbe
line 617why, one step back617 *Merge branch 'integrate'TJ Holowaychukbefore adoption6b1d7a9
line 618why, one step back618 * While the leading slash would result in a location of "/login":update connect depTJ Holowaychukbefore adoption75debbe
line 619why, one step back619 *Merge branch 'integrate'TJ Holowaychukbefore adoption6b1d7a9
line 620why, one step back620 * res.location('/login');update connect depTJ Holowaychukbefore adoption75debbe
lines 621–625why, one step back621 *622 * @param {String} url623 * @api public624 */625Merge branch 'integrate'TJ Holowaychukbefore adoption6b1d7a9
line 626why, one step back626res.location = function(url){update connect depTJ Holowaychukbefore adoption75debbe
line 627why, one step back627 var app = this.appMerge branch 'integrate'TJ Holowaychukbefore adoption6b1d7a9
line 628why, one step back628 , req = this.req;update connect depTJ Holowaychukbefore adoption75debbe
lines 629–637why, one step back629630 // setup redirect map631 var map = { back: req.get('Referrer') || '/' };632633 // perform redirect634 url = map[url] || url;635636 // relative637 if (!~url.indexOf('://') && 0 != url.indexOf('//')) {Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionc6d7352
line 638why, one step back638 var pathupdate connect depTJ Holowaychukbefore adoption75debbe
lines 639–641why, one step back639640 // relative to path641 if ('.' == url[0]) {Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionc6d7352
lines 642–644why, one step back642 path = req.originalUrl.split('?')[0]643 url = path + ('/' == path[path.length - 1] ? '' : '/') + url;644 // relative to mount-pointupdate connect depTJ Holowaychukbefore adoption75debbe
line 645why, one step back645 } else if ('/' != url[0]) {Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionc6d7352
line 646why, one step back646 path = app.path();update connect depTJ Holowaychukbefore adoption75debbe
lines 647–650why, one step back647 url = path + '/' + url;648 }649 }650Merge branch 'integrate'TJ Holowaychukbefore adoption6b1d7a9
lines 651–696why, one step back651 // Respond652 this.set('Location', url);653 return this;654};655656/**657 * Redirect to the given `url` with optional response `status`658 * defaulting to 302.659 *660 * The resulting `url` is determined by `res.location()`, so661 * it will play nicely with mounted apps, relative paths,662 * `"back"` etc.663 *664 * Examples:665 *666 * res.redirect('/foo/bar');667 * res.redirect('http://example.com');668 * res.redirect(301, 'http://example.com');669 * res.redirect('http://example.com', 301);670 * res.redirect('../login'); // /blog/post/1 -> /blog/login671 *672 * @param {String} url673 * @param {Number} code674 * @api public675 */676677res.redirect = function(url){678 var app = this.app679 , head = 'HEAD' == this.req.method680 , status = 302681 , body;682683 // allow status / url684 if (2 == arguments.length) {685 if ('number' == typeof url) {686 status = url;687 url = arguments[1];688 } else {689 status = arguments[1];690 }691 }692693 // Set location header694 this.location(url);695 url = this.get('Location');696update connect depTJ Holowaychukbefore adoption75debbe
lines 697–699why, one step back697 // Support text/{plain,html} by default698 this.format({699 text: function(){Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionc852693
line 700why, one step back700 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);update connect depTJ Holowaychukbefore adoption75debbe
lines 701–703why, one step back701 },702703 html: function(){escape res.redirect() linkTJ Holowaychukbefore adoptionbac0c64
lines 704–705why, one step back704 var u = utils.escape(url);705 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';update connect depTJ Holowaychukbefore adoption75debbe
lines 706–746why, one step back706 },707708 default: function(){709 body = '';710 }711 });712713 // Respond714 this.statusCode = status;715 this.set('Content-Length', Buffer.byteLength(body));716 this.end(head ? null : body);717};718719/**720 * Render `view` with the given `options` and optional callback `fn`.721 * When a callback function is given a response will _not_ be made722 * automatically, otherwise a response of _200_ and _text/html_ is given.723 *724 * Options:725 *726 * - `cache` boolean hinting to the engine it should cache727 * - `filename` filename of the view being rendered728 *729 * @param {String} view730 * @param {Object|Function} options or callback function731 * @param {Function} fn732 * @api public733 */734735res.render = function(view, options, fn){736 var self = this737 , options = options || {}738 , req = this.req739 , app = req.app;740741 // support callback function as second arg742 if ('function' == typeof options) {743 fn = options, options = {};744 }745746 // merge res.localsrefactor res.render() to prevent clobbering "locals"TJ Holowaychukbefore adoption6bebe08
line 747why, one step back747 options._locals = self.locals;update connect depTJ Holowaychukbefore adoption75debbe
lines 748–757why, one step back748749 // default callback to respond750 fn = fn || function(err, str){751 if (err) return req.next(err);752 self.send(str);753 };754755 // render756 app.render(view, options, fn);757};