response.js
This file
Path
lib/response.js
720 lines · 16.5 KiB · JavaScript
Last changed by
fix jsonp whitespace escape. Closes #1132Guillermo Rauchbefore adoption64a2349
History of this fileTake it
The walk stopped after 200 commits: lines older than 9fda13b point at it.
Added url rewriting testTJ Holowaychukbefore adoption9fda13b
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')Added url rewriting testTJ Holowaychukbefore adoption9fda13b
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').signAdded url rewriting testTJ Holowaychukbefore adoption9fda13b
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').etagAdded url rewriting testTJ Holowaychukbefore adoption9fda13b
line 13why, one step back13 , statusCodes = http.STATUS_CODESfixing cookies for connect 2.3.1TJ Holowaychukbefore adoption02d4384
line 14why, one step back14 , cookie = require('cookie')change res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
line 15why, one step back15 , send = require('send')Fixed: expose connects mime module. Cloases #1165TJ Holowaychukbefore adoption8956731
line 16why, one step back16 , mime = connect.mimeAdded url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 17–42why, one step back17 , 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/**Added `res.links(obj)`TJ Holowaychukbefore adoptione6129d8
lines 43–63why, one step back43 * 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/**Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 64–79why, one step back64 * 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 */79mergeTJ Holowaychukbefore adoption214f913
lines 80–130why, one step back80res.send = function(body){81 var req = this.req82 , head = 'HEAD' == req.method83 , len;8485 // 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/ supportRevert "add 'etag' option"TJ Holowaychukbefore adoption9bd86cd
line 131why, one step back131 if (len > 1024) {add etag utilTJ Holowaychukbefore adoptionf2f0976
lines 132–134why, one step back132 if (!this.get('ETag')) {133 this.set('ETag', etag(body));134 }mergeTJ Holowaychukbefore adoption214f913
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');mergeTJ Holowaychukbefore adoption214f913
lines 145–151why, one step back145 body = '';146 }147148 // respond149 this.end(head ? null : body);150 return this;151};Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 152–171why, one step back152153/**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) {Added `res.json(obj, status)` support back for BCTJ Holowaychukbefore adoption70d6841
lines 172–178why, one step back172 // 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 }Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 179–180why, one step back179 }180docsTJ Holowaychukbefore adoption2e8d44b
line 181why, one step back181 // 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);Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 186why, one step back186docsTJ Holowaychukbefore adoption2e8d44b
line 187why, one step back187 // content-typeAdded url rewriting testTJ Holowaychukbefore adoption9fda13b
line 188why, one step back188 this.charset = this.charset || 'utf-8';refactorTJ Holowaychukbefore adoption88072a5
line 189why, one step back189 this.get('Content-Type') || this.set('Content-Type', 'application/json');add "jsonp callback name" settingriadhbefore adoption5426eb0
line 190why, one step back190 add res.jsonp(). Closes #1307TJ Holowaychukbefore adoptiona6caa26
lines 191–225why, one step back191 return this.send(body);192};193194/**195 * Send JSON response with JSONP callback support.196 *197 * Examples:198 *199 * res.jsonp(null);200 * res.jsonp({ user: 'tj' });201 * res.jsonp(500, 'oh noes!');202 * res.jsonp(404, 'I dont have that');203 *204 * @param {Mixed} obj or status205 * @param {Mixed} obj206 * @return {ServerResponse}207 * @api public208 */209210res.jsonp = function(obj){211 // allow status / body212 if (2 == arguments.length) {213 // res.json(body, status) backwards compat214 if ('number' == typeof arguments[1]) {215 this.statusCode = arguments[1];216 } else {217 this.statusCode = obj;218 obj = arguments[1];219 }220 }221222 // settings223 var app = this.app;224 var replacer = app.get('json replacer');225 var spaces = app.get('json spaces');fix jsonp whitespace escape. Closes #1132Guillermo Rauchbefore adoption64a2349
lines 226–228why, one step back226 var body = JSON.stringify(obj, replacer, spaces)227 .replace(/\u2028/g, '\\u2028')228 .replace(/\u2029/g, '\\u2029');add res.jsonp(). Closes #1307TJ Holowaychukbefore adoptiona6caa26
lines 229–234why, one step back229 var callback = this.req.query[app.get('jsonp callback name')];230231 // content-type232 this.charset = this.charset || 'utf-8';233 this.set('Content-Type', 'application/json');234 docsTJ Holowaychukbefore adoption2e8d44b
line 235why, one step back235 // jsonpadd res.jsonp(). Closes #1307TJ Holowaychukbefore adoptiona6caa26
line 236why, one step back236 if (callback) {Added url rewriting testTJ Holowaychukbefore adoption9fda13b
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 + ');';Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 240–246why, one step back240 }241242 return this.send(body);243};244245/**246 * Transfer the file at the given `path`.Revert "add 'etag' option"TJ Holowaychukbefore adoption9bd86cd
line 247why, one step back247 * Added url rewriting testTJ Holowaychukbefore adoption9fda13b
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;Revert "add 'etag' option"TJ Holowaychukbefore adoption9bd86cd
line 269why, one step back269 * Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 270–288why, 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.nextchange res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
lines 289–290why, one step back289 , options = options || {}290 , done;Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 291–297why, one step back291292 // support function as second arg293 if ('function' == typeof options) {294 fn = options;295 options = {};296 }297change res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
lines 298–299why, one step back298 // socket errors299 req.socket.on('error', error);Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 300why, one step back300change res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
lines 301–304why, one step back301 // errors302 function error(err) {303 if (done) return;304 done = true;Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 305why, one step back305change res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
line 306why, one step back306 // clean upMerge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3865168
line 307why, one step back307 cleanup();change res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
line 308why, one step back308 if (!self.headerSent) self.removeHeader('Content-Disposition');Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 309why, one step back309change res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
lines 310–311why, one step back310 // callback available311 if (fn) return fn(err);Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 312why, one step back312change res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
lines 313–314why, one step back313 // list in limbo if there's no callback314 if (self.headerSent) return;Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 315why, one step back315change res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
lines 316–318why, one step back316 // delegate317 next(err);318 }Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 319why, one step back319change res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
lines 320–322why, one step back320 // streaming321 function stream() {322 if (done) return;Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3865168
line 323why, one step back323 cleanup();change res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
lines 324–326why, one step back324 if (fn) self.on('finish', fn);325 }326Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3865168
lines 327–331why, one step back327 // cleanup328 function cleanup() {329 req.socket.removeListener('error', error);330 }331Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 332why, one step back332 // transferchange res.sendfile() to use send() moduleTJ Holowaychukbefore adoptionab61837
lines 333–339why, one step back333 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);Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption3865168
line 340why, one step back340 this.on('finish', cleanup);Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 341–350why, one step back341};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 *Added res.download() testsTJ Holowaychukbefore adoption5840b42
line 351why, one step back351 * This method uses `res.sendfile()`.Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 352–365why, one step back352 *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 }365Added res.download() testsTJ Holowaychukbefore adoption5840b42
lines 366–368why, one step back366 filename = filename || path;367 this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');368 return this.sendfile(path, fn);Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 369–413why, one step back369};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 * },Revert "add 'etag' option"TJ Holowaychukbefore adoption9bd86cd
line 414why, one step back414 * Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 415–417why, one step back415 * 'text/html': function(){416 * res.send('<p>hey</p>');417 * },Revert "add 'etag' option"TJ Holowaychukbefore adoption9bd86cd
line 418why, one step back418 * Added url rewriting testTJ Holowaychukbefore adoption9fda13b
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 * },Revert "add 'etag' option"TJ Holowaychukbefore adoption9bd86cd
line 431why, one step back431 * Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 432–434why, one step back432 * html: function(){433 * res.send('<p>hey</p>');434 * },Revert "add 'etag' option"TJ Holowaychukbefore adoption9bd86cd
line 435why, one step back435 * Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 436–440why, one step back436 * json: function(){437 * res.send({ message: 'hey' });438 * }439 * });440 *mention res.format() callbackTJ Holowaychukbefore adoptionfd42b5c
lines 441–442why, one step back441 * By default Express passes an `Error`442 * with a `.status` of 406 to `next(err)`docsTJ Holowaychukbefore adoptiond2baf11
lines 443–445why, one step back443 * if a match is not made. If you provide444 * a `.default` callback it will be invoked445 * instead.mention res.format() callbackTJ Holowaychukbefore adoptionfd42b5c
line 446why, one step back446 *Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 447–451why, one step back447 * @param {Object} obj448 * @return {ServerResponse} for chaining449 * @api public450 */451Added `.default()` support to `res.format()`TJ Holowaychukbefore adoption82b5b12
line 452why, one step back452res.format = function(obj){refactor res.format(), dont pass "default" to req.accepts()TJ Holowaychukbefore adoption8edf358
line 453why, one step back453 var req = this.reqAdded `.default()` support to `res.format()`TJ Holowaychukbefore adoption82b5b12
line 454why, one step back454 , next = req.next;Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 455why, one step back455Added `.default()` support to `res.format()`TJ Holowaychukbefore adoption82b5b12
lines 456–457why, one step back456 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);Added `.default()` support to `res.format()`TJ Holowaychukbefore adoption82b5b12
lines 459–461why, one step back459460 var key = req.accepts(keys);461Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 462–466why, one step back462 this.set('Vary', 'Accept');463464 if (key) {465 this.set('Content-Type', normalizeType(key));466 obj[key](req, this, next);Fixed res.redirect() 406. Closes #1154TJ Holowaychukbefore adoption1311f2a
lines 467–468why, one step back467 } else if (fn) {468 fn();Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 469–496why, one step back469 } else {470 var err = new Error('Not Acceptable');471 err.status = 406;472 err.types = normalizeTypes(keys);473 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 passMerge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoption0acee67
line 497why, one step back497 * an object of header fields.Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 498–503why, one step back498 *499 * Examples:500 *501 * res.set('Accept', 'application/json');502 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });503 *Revert "add 'etag' option"TJ Holowaychukbefore adoption9bd86cd
line 504why, one step back504 * Aliased as `res.header()`. Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 505–511why, one step back505 *506 * @param {String|Object} field507 * @param {String} val508 * @return {ServerResponse} for chaining509 * @api public510 */511Revert "add 'etag' option"TJ Holowaychukbefore adoption9bd86cd
line 512why, one step back512res.set = Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 513–557why, one step back513res.header = function(field, val){514 if (2 == arguments.length) {515 this.setHeader(field, '' + val);516 } else {517 for (var key in field) {518 this.setHeader(key, '' + field[key]);519 }520 }521 return this;522};523524/**525 * Get value for header `field`.526 *527 * @param {String} field528 * @return {String}529 * @api public530 */531532res.get = function(field){533 return this.getHeader(field);534};535536/**537 * Clear cookie `name`.538 *539 * @param {String} name540 * @param {Object} options541 * @param {ServerResponse} for chaining542 * @api public543 */544545res.clearCookie = function(name, options){546 var opts = { expires: new Date(1), path: '/' };547 return this.cookie(name, '', options548 ? utils.merge(opts, options)549 : opts);550};551552/**553 * Set cookie `name` to `val`, with the given `options`.554 *555 * Options:556 *557 * - `maxAge` max-age in milliseconds, converted to `expires`Added { signed: true } option to res.cookie()TJ Holowaychukbefore adoption1150a88
line 558why, one step back558 * - `signed` sign the cookieAdded url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 559–576why, one step back559 * - `path` defaults to "/"560 *561 * Examples:562 *563 * // "Remember Me" for 15 minutes564 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });565 *566 * // save as above567 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })568 *569 * @param {String} name570 * @param {String|Object} val571 * @param {Options} options572 * @api public573 */574575res.cookie = function(name, val, options){576 options = options || {};Added { signed: true } option to res.cookie()TJ Holowaychukbefore adoption1150a88
lines 577–579why, one step back577 var secret = this.req.secret;578 var signed = options.signed;579 if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 580why, one step back580 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);update connectTJ Holowaychukbefore adoption612fc47
line 581why, one step back581 if (signed) val = 's:' + sign(val, secret);Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 582–583why, one step back582 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);583 if (null == options.path) options.path = '/';fix cookie max-ageTJ Holowaychukbefore adoptionab9c275
line 584why, one step back584 options.maxAge /= 1000;coerce res.cookie values to stringsTJ Holowaychukbefore adoptionebf60d2
line 585why, one step back585 this.set('Set-Cookie', cookie.serialize(name, String(val), options));Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 586–601why, one step back586 return this;587};588589/**590 * Redirect to the given `url` with optional response `status`591 * defaulting to 302.592 *593 * The given `url` can also be the name of a mapped url, for594 * example by default express supports "back" which redirects595 * to the _Referrer_ or _Referer_ headers or "/".596 *597 * Examples:598 *599 * res.redirect('/foo/bar');600 * res.redirect('http://example.com');601 * res.redirect(301, 'http://example.com');add backwards compat for res.redirect() status. Closes #1336TJ Holowaychukbefore adoption56ffab0
line 602why, one step back602 * res.redirect('http://example.com', 301);Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 603–607why, one step back603 * res.redirect('../login'); // /blog/post/1 -> /blog/login604 *605 * Mounting:606 *607 * When an application is mounted, and `res.redirect()`Revert "add 'etag' option"TJ Holowaychukbefore adoption9bd86cd
line 608why, one step back608 * is given a path that does _not_ lead with "/". For Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 609–631why, one step back609 * example suppose a "blog" app is mounted at "/blog",610 * the following redirect would result in "/blog/login":611 *612 * res.redirect('login');613 *614 * While the leading slash would result in a redirect to "/login":615 *616 * res.redirect('/login');617 *618 * @param {String} url619 * @param {Number} code620 * @api public621 */622623res.redirect = function(url){624 var app = this.app625 , req = this.req626 , head = 'HEAD' == req.method627 , status = 302628 , body;629630 // allow status / url631 if (2 == arguments.length) {add backwards compat for res.redirect() status. Closes #1336TJ Holowaychukbefore adoption56ffab0
lines 632–637why, one step back632 if ('number' == typeof url) {633 status = url;634 url = arguments[1];635 } else {636 status = arguments[1];637 }Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 638–646why, one step back638 }639640 // setup redirect map641 var map = { back: req.get('Referrer') || '/' };642643 // perform redirect644 url = map[url] || url;645646 // relativeadd res.redirect("//foo.com") supportTJ Holowaychukbefore adoptiona93d375
line 647why, one step back647 if (!~url.indexOf('://') && 0 != url.indexOf('//')) {Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 648–650why, one step back648 var path = app.path();649650 // relative to pathrefactor res.redirect() relative checkTJ Holowaychukbefore adoption362c96c
line 651why, one step back651 if ('.' == url[0]) {Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 652–661why, one step back652 url = req.path + '/' + url;653 // relative to mount-point654 } else if ('/' != url[0]) {655 url = path + '/' + url;656 }657 }658659 // Support text/{plain,html} by default660 this.format({661 text: function(){Merge branch 'master' of github.com:visionmedia/expressTJ Holowaychukbefore adoptionc852693
line 662why, one step back662 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 663–665why, one step back663 },664665 html: function(){escape res.redirect() linkTJ Holowaychukbefore adoptionbac0c64
lines 666–667why, one step back666 var u = utils.escape(url);667 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';Added `.default()` support to `res.format()`TJ Holowaychukbefore adoption82b5b12
lines 668–671why, one step back668 },669670 default: function(){671 body = '';Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 672why, one step back672 }Added `.default()` support to `res.format()`TJ Holowaychukbefore adoption82b5b12
line 673why, one step back673 });Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 674–677why, one step back674675 // Respond676 this.statusCode = status;677 this.set('Location', url);Fixed res.redirect() 406. Closes #1154TJ Holowaychukbefore adoption1311f2a
line 678why, one step back678 this.set('Content-Length', Buffer.byteLength(body));Added url rewriting testTJ Holowaychukbefore adoption9fda13b
lines 679–708why, one step back679 this.end(head ? null : body);680};681682/**683 * Render `view` with the given `options` and optional callback `fn`.684 * When a callback function is given a response will _not_ be made685 * automatically, otherwise a response of _200_ and _text/html_ is given.686 *687 * Options:688 *689 * - `cache` boolean hinting to the engine it should cache690 * - `filename` filename of the view being rendered691 *692 * @param {String} view693 * @param {Object|Function} options or callback function694 * @param {Function} fn695 * @api public696 */697698res.render = function(view, options, fn){699 var self = this700 , options = options || {}701 , req = this.req702 , app = req.app;703704 // support callback function as second arg705 if ('function' == typeof options) {706 fn = options, options = {};707 }708remove app.locals.use and res.locals.useTJ Holowaychukbefore adoption4f7c4d1
line 709why, one step back709 // merge res.localsrefactor res.render() to prevent clobbering "locals"TJ Holowaychukbefore adoption6bebe08
line 710why, one step back710 options._locals = self.locals;Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 711why, one step back711remove app.locals.use and res.locals.useTJ Holowaychukbefore adoption4f7c4d1
lines 712–716why, one step back712 // default callback to respond713 fn = fn || function(err, str){714 if (err) return req.next(err);715 self.send(str);716 };Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 717why, one step back717remove app.locals.use and res.locals.useTJ Holowaychukbefore adoption4f7c4d1
lines 718–719why, one step back718 // render719 app.render(view, options, fn);Added url rewriting testTJ Holowaychukbefore adoption9fda13b
line 720why, one step back720};