response.js
This file
Path
lib/response.js
841 lines · 19.5 KiB · JavaScript
Last changed by
build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
History of this fileTake it
The walk stopped after 200 commits: lines older than 9df1067 point at it.
4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 1–4why, one step back1/**2 * Module dependencies.3 */4Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 5why, one step back5var deprecate = require('depd')('express');Merge tag '3.10.0'Douglas Christopher Wilsonbefore adoption402ec83
line 6why, one step back6var escapeHtml = require('escape-html');move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 7–12why, one step back7var 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 back13var setCharset = require('./utils').setCharset;Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9
line 14why, one step back14var contentDisposition = require('./utils').contentDisposition;move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 15–20why, one step back15var 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 back21var vary = require('vary');4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 22–80why, one step back2223/**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 */80perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 81–82why, one step back81res.send = function send(body) {82 var chunk = body;Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
line 83why, one step back83 var encoding;4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 84why, one step back84 var len;perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 85–86why, one step back85 var req = this.req;86 var type;4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 87–91why, one step back8788 // settings89 var app = this.app;9091 // allow status / bodyperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 92why, one step back92 if (arguments.length === 2) {4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 93why, one step back93 // res.send(body, status) backwards compatperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 94why, one step back94 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {add deprecation message to res.send(body, status)Douglas Christopher Wilsonbefore adoptionba8a4c5
line 95why, one step back95 deprecate('res.send(body, status): Use res.send(status, body) instead');4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 96–97why, one step back96 this.statusCode = arguments[1];97 } else {perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 98–99why, one step back98 this.statusCode = arguments[0];99 chunk = arguments[1];4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 100–102why, one step back100 }101 }102Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
line 103why, one step back103 // disambiguate res.send(status) and res.send(status, num)perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 104why, one step back104 if (typeof chunk === 'number' && arguments.length === 1) {Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
line 105why, one step back105 // res.send(status) will set status message as text stringperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 106–111why, one step back106 if (!this.get('Content-Type')) {107 this.type('txt');108 }109110 this.statusCode = chunk;111 chunk = http.STATUS_CODES[chunk];Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 112–113why, one step back112 }113perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 114why, one step back114 switch (typeof chunk) {4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 115–116why, one step back115 // string defaulting to html116 case 'string':perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 117–119why, one step back117 if (!this.get('Content-Type')) {118 this.type('html');119 }4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 120–121why, one step back120 break;121 case 'boolean':Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
line 122why, one step back122 case 'number':4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 123why, one step back123 case 'object':perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 124–129why, one step back124 if (chunk === null) {125 chunk = '';126 } else if (Buffer.isBuffer(chunk)) {127 if (!this.get('Content-Type')) {128 this.type('bin');129 }4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 130why, one step back130 } else {perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 131why, one step back131 return this.json(chunk);4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 132–135why, one step back132 }133 break;134 }135Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
line 136why, one step back136 // write strings in utf-8perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 137why, one step back137 if (typeof chunk === 'string') {Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
lines 138–141why, one step back138 encoding = 'utf8';139 type = this.get('Content-Type');140141 // reflect this in content-typeperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 142why, one step back142 if (typeof type === 'string') {Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
line 143why, one step back143 this.set('Content-Type', setCharset(type, 'utf-8'));Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 144–147why, one step back144 }145 }146147 // populate Content-Lengthperf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
lines 148–155why, one step back148 if (chunk !== undefined) {149 if (!Buffer.isBuffer(chunk)) {150 // convert chunk to Buffer; saves later double conversions151 chunk = new Buffer(chunk, encoding);152 encoding = undefined;153 }154155 len = chunk.length;Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 156–158why, one step back156 this.set('Content-Length', len);157 }158perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
lines 159–161why, one step back159 // method check160 var isHead = req.method === 'HEAD';161Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 162why, one step back162 // ETag supportperf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
lines 163–165why, one step back163 if (len !== undefined && (isHead || req.method === 'GET')) {164 var etag = app.get('etag fn');165 if (etag && !this.get('ETag')) {perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 166why, one step back166 etag = etag(chunk, encoding);Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 167why, one step back167 etag && this.set('ETag', etag);Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
lines 168–170why, one step back168 }169 }1704.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 171–178why, one step back171 // freshness172 if (req.fresh) this.statusCode = 304;173174 // strip irrelevant headers175 if (204 == this.statusCode || 304 == this.statusCode) {176 this.removeHeader('Content-Type');177 this.removeHeader('Content-Length');178 this.removeHeader('Transfer-Encoding');perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 179why, one step back179 chunk = '';4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 180–181why, one step back180 }181perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 182why, one step back182 // skip body for HEADperf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
line 183why, one step back183 if (isHead) {perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 184–186why, one step back184 this.end();185 }1864.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 187why, one step back187 // respondperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 188why, one step back188 this.end(chunk, encoding);Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061
line 189why, one step back1894.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 190–205why, one step back190 return this;191};192193/**194 * Send JSON response.195 *196 * Examples:197 *198 * res.json(null);199 * res.json({ user: 'tj' });200 * res.json(500, 'oh noes!');201 * res.json(404, 'I dont have that');202 *203 * @api public204 */205perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 206–208why, one step back206res.json = function json(obj) {207 var val = obj;2084.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 209why, one step back209 // allow status / bodyperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 210why, one step back210 if (arguments.length === 2) {4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 211why, one step back211 // res.json(body, status) backwards compatperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 212why, one step back212 if (typeof arguments[1] === 'number') {4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 213why, one step back213 this.statusCode = arguments[1];perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 214why, one step back214 if (typeof arguments[0] === 'number') {Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
lines 215–218why, one step back215 deprecate('res.json(obj, status): Use res.json(status, obj) instead');216 } else {217 deprecate('res.json(num, status): Use res.status(status).json(num) instead');218 }4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 219why, one step back219 } else {perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 220–221why, one step back220 this.statusCode = arguments[0];221 val = arguments[1];4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 222–228why, one step back222 }223 }224225 // settings226 var app = this.app;227 var replacer = app.get('json replacer');228 var spaces = app.get('json spaces');perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 229why, one step back229 var body = JSON.stringify(val, replacer, spaces);4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 230–231why, one step back230231 // content-typeperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 232–234why, one step back232 if (!this.get('Content-Type')) {233 this.set('Content-Type', 'application/json');234 }4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 235–251why, one step back235236 return this.send(body);237};238239/**240 * Send JSON response with JSONP callback support.241 *242 * Examples:243 *244 * res.jsonp(null);245 * res.jsonp({ user: 'tj' });246 * res.jsonp(500, 'oh noes!');247 * res.jsonp(404, 'I dont have that');248 *249 * @api public250 */251perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 252–254why, one step back252res.jsonp = function jsonp(obj) {253 var val = obj;2544.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 255why, one step back255 // allow status / bodyperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 256why, one step back256 if (arguments.length === 2) {4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 257why, one step back257 // res.json(body, status) backwards compatperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 258why, one step back258 if (typeof arguments[1] === 'number') {4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 259why, one step back259 this.statusCode = arguments[1];perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 260why, one step back260 if (typeof arguments[0] === 'number') {Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
lines 261–264why, one step back261 deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');262 } else {263 deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');264 }4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 265why, one step back265 } else {perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 266–267why, one step back266 this.statusCode = arguments[0];267 val = arguments[1];4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 268–274why, one step back268 }269 }270271 // settings272 var app = this.app;273 var replacer = app.get('json replacer');274 var spaces = app.get('json spaces');perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 275why, one step back275 var body = JSON.stringify(val, replacer, spaces);4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 276–278why, one step back276 var callback = this.req.query[app.get('jsonp callback name')];277278 // content-typeMerge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 279–282why, one step back279 if (!this.get('Content-Type')) {280 this.set('X-Content-Type-Options', 'nosniff');281 this.set('Content-Type', 'application/json');282 }4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 283why, one step back283Merge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84
lines 284–288why, one step back284 // fixup callback285 if (Array.isArray(callback)) {286 callback = callback[0];287 }2884.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 289why, one step back289 // jsonpMerge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 290–292why, one step back290 if (typeof callback === 'string' && callback.length !== 0) {291 this.charset = 'utf-8';292 this.set('X-Content-Type-Options', 'nosniff');4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 293why, one step back293 this.set('Content-Type', 'text/javascript');Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 294–305why, one step back294295 // restrict callback charset296 callback = callback.replace(/[^\[\]\w$.]/g, '');297298 // replace chars not allowed in JavaScript that are in JSON299 body = body300 .replace(/\u2028/g, '\\u2028')301 .replace(/\u2029/g, '\\u2029');302303 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"304 // the typeof check is just to reduce client error noise305 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 306–321why, one step back306 }307308 return this.send(body);309};310311/**312 * Transfer the file at the given `path`.313 *314 * Automatically sets the _Content-Type_ response header field.315 * The callback `fn(err)` is invoked when the transfer is complete316 * or when an error occurs. Be sure to check `res.sentHeader`317 * if you wish to attempt responding, as the header and some data318 * may have already been transferred.319 *320 * Options:321 *Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe
lines 322–325why, one step back322 * - `maxAge` defaulting to 0 (can be string converted by `ms`)323 * - `root` root directory for relative filenames324 * - `headers` object of headers to serve with file325 * - `hidden` serve hidden files, defaulting to false4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 326why, one step back326 *Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
lines 327–328why, one step back327 * Other options are passed along to `send`.328 *4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 329–352why, one step back329 * Examples:330 *331 * The following example illustrates how `res.sendfile()` may332 * be used as an alternative for the `static()` middleware for333 * dynamic situations. The code backing `res.sendfile()` is actually334 * the same code, so HTTP cache support etc is identical.335 *336 * app.get('/user/:uid/photos/:file', function(req, res){337 * var uid = req.params.uid338 * , file = req.params.file;339 *340 * req.user.mayViewFilesFrom(uid, function(yes){341 * if (yes) {342 * res.sendfile('/uploads/' + uid + '/' + file);343 * } else {344 * res.send(403, 'Sorry! you cant see that.');345 * }346 * });347 * });348 *349 * @api public350 */351352res.sendfile = function(path, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 353–357why, one step back353 options = options || {};354 var self = this;355 var req = self.req;356 var next = this.req.next;357 var done;4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 358why, one step back358Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
line 359why, one step back3594.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 360–395why, one step back360 // support function as second arg361 if ('function' == typeof options) {362 fn = options;363 options = {};364 }365366 // socket errors367 req.socket.on('error', error);368369 // errors370 function error(err) {371 if (done) return;372 done = true;373374 // clean up375 cleanup();376377 // callback available378 if (fn) return fn(err);379380 // delegate381 next(err);382 }383384 // streaming385 function stream(stream) {386 if (done) return;387 cleanup();388 if (fn) stream.on('end', fn);389 }390391 // cleanup392 function cleanup() {393 req.socket.removeListener('error', error);394 }395Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
lines 396–398why, one step back396 // Back-compat397 options.maxage = options.maxage || options.maxAge || 0;3984.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 399why, one step back399 // transferPass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72
line 400why, one step back400 var file = send(req, path, options);4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 401–403why, one step back401 file.on('error', error);402 file.on('directory', next);403 file.on('stream', stream);Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe
lines 404–418why, one step back404405 if (options.headers) {406 // set headers on successful transfer407 file.on('headers', function headers(res) {408 var obj = options.headers;409 var keys = Object.keys(obj);410411 for (var i = 0; i < keys.length; i++) {412 var k = keys[i];413 res.setHeader(k, obj[k]);414 }415 });416 }417418 // pipe4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 419–443why, one step back419 file.pipe(this);420 this.on('finish', cleanup);421};422423/**424 * Transfer the file at the given `path` as an attachment.425 *426 * Optionally providing an alternate attachment `filename`,427 * and optional callback `fn(err)`. The callback is invoked428 * when the data transfer is complete, or when an error has429 * ocurred. Be sure to check `res.headersSent` if you plan to respond.430 *431 * This method uses `res.sendfile()`.432 *433 * @api public434 */435436res.download = function(path, filename, fn){437 // support function as second arg438 if ('function' == typeof filename) {439 fn = filename;440 filename = null;441 }442443 filename = filename || path;Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe
lines 444–450why, one step back444445 // set Content-Disposition when file is sent446 var headers = {447 'Content-Disposition': contentDisposition(filename)448 };449450 return this.sendfile(path, { headers: headers }, fn);4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 451–534why, one step back451};452453/**454 * Set _Content-Type_ response header with `type` through `mime.lookup()`455 * when it does not contain "/", or set the Content-Type to `type` otherwise.456 *457 * Examples:458 *459 * res.type('.html');460 * res.type('html');461 * res.type('json');462 * res.type('application/json');463 * res.type('png');464 *465 * @param {String} type466 * @return {ServerResponse} for chaining467 * @api public468 */469470res.contentType =471res.type = function(type){472 return this.set('Content-Type', ~type.indexOf('/')473 ? type474 : mime.lookup(type));475};476477/**478 * Respond to the Acceptable formats using an `obj`479 * of mime-type callbacks.480 *481 * This method uses `req.accepted`, an array of482 * acceptable types ordered by their quality values.483 * When "Accept" is not present the _first_ callback484 * is invoked, otherwise the first match is used. When485 * no match is performed the server responds with486 * 406 "Not Acceptable".487 *488 * Content-Type is set for you, however if you choose489 * you may alter this within the callback using `res.type()`490 * or `res.set('Content-Type', ...)`.491 *492 * res.format({493 * 'text/plain': function(){494 * res.send('hey');495 * },496 *497 * 'text/html': function(){498 * res.send('<p>hey</p>');499 * },500 *501 * 'appliation/json': function(){502 * res.send({ message: 'hey' });503 * }504 * });505 *506 * In addition to canonicalized MIME types you may507 * also use extnames mapped to these types:508 *509 * res.format({510 * text: function(){511 * res.send('hey');512 * },513 *514 * html: function(){515 * res.send('<p>hey</p>');516 * },517 *518 * json: function(){519 * res.send({ message: 'hey' });520 * }521 * });522 *523 * By default Express passes an `Error`524 * with a `.status` of 406 to `next(err)`525 * if a match is not made. If you provide526 * a `.default` callback it will be invoked527 * instead.528 *529 * @param {Object} obj530 * @return {ServerResponse} for chaining531 * @api public532 */533534res.format = function(obj){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 535–536why, one step back535 var req = this.req;536 var next = req.next;4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 537–546why, one step back537538 var fn = obj.default;539 if (fn) delete obj.default;540 var keys = Object.keys(obj);541542 var key = req.accepts(keys);543544 this.vary("Accept");545546 if (key) {remove res.charset usageJonathan Ongbefore adoption2064f41
line 547why, one step back547 this.set('Content-Type', normalizeType(key).value);4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 548–570why, one step back548 obj[key](req, this, next);549 } else if (fn) {550 fn();551 } else {552 var err = new Error('Not Acceptable');553 err.status = 406;554 err.types = normalizeTypes(keys).map(function(o){ return o.value });555 next(err);556 }557558 return this;559};560561/**562 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.563 *564 * @param {String} filename565 * @return {ServerResponse}566 * @api public567 */568569res.attachment = function(filename){570 if (filename) this.type(extname(filename));Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9
line 571why, one step back571 this.set('Content-Disposition', contentDisposition(filename));4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 572–593why, one step back572 return this;573};574575/**576 * Set header `field` to `val`, or pass577 * an object of header fields.578 *579 * Examples:580 *581 * res.set('Foo', ['bar', 'baz']);582 * res.set('Accept', 'application/json');583 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });584 *585 * Aliased as `res.header()`.586 *587 * @param {String|Object|Array} field588 * @param {String} val589 * @return {ServerResponse} for chaining590 * @api public591 */592593res.set =perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 594–595why, one step back594res.header = function header(field, val) {595 if (arguments.length === 2) {4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 596–597why, one step back596 if (Array.isArray(val)) val = val.map(String);597 else val = String(val);preserve casing of headers in res.header and res.setDouglas Christopher Wilsonbefore adoption1536a21
line 598why, one step back598 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7
lines 599–601why, one step back599 var charset = mime.charsets.lookup(val.split(';')[0]);600 if (charset) val += '; charset=' + charset.toLowerCase();601 }4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 602–627why, one step back602 this.setHeader(field, val);603 } else {604 for (var key in field) {605 this.set(key, field[key]);606 }607 }608 return this;609};610611/**612 * Get value for header `field`.613 *614 * @param {String} field615 * @return {String}616 * @api public617 */618619res.get = function(field){620 return this.getHeader(field);621};622623/**624 * Clear cookie `name`.625 *626 * @param {String} name627 * @param {Object} optionsbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 628why, one step back628 * @return {ServerResponse} for chaining4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 629–658why, one step back629 * @api public630 */631632res.clearCookie = function(name, options){633 var opts = { expires: new Date(1), path: '/' };634 return this.cookie(name, '', options635 ? mixin(opts, options)636 : opts);637};638639/**640 * Set cookie `name` to `val`, with the given `options`.641 *642 * Options:643 *644 * - `maxAge` max-age in milliseconds, converted to `expires`645 * - `signed` sign the cookie646 * - `path` defaults to "/"647 *648 * Examples:649 *650 * // "Remember Me" for 15 minutes651 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });652 *653 * // save as above654 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })655 *656 * @param {String} name657 * @param {String|Object} val658 * @param {Options} optionsbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 659why, one step back659 * @return {ServerResponse} for chaining4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 660–704why, one step back660 * @api public661 */662663res.cookie = function(name, val, options){664 options = mixin({}, options);665 var secret = this.req.secret;666 var signed = options.signed;667 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');668 if ('number' == typeof val) val = val.toString();669 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);670 if (signed) val = 's:' + sign(val, secret);671 if ('maxAge' in options) {672 options.expires = new Date(Date.now() + options.maxAge);673 options.maxAge /= 1000;674 }675 if (null == options.path) options.path = '/';676 var headerVal = cookie.serialize(name, String(val), options);677678 // supports multiple 'res.cookie' calls by getting previous value679 var prev = this.get('Set-Cookie');680 if (prev) {681 if (Array.isArray(prev)) {682 headerVal = prev.concat(headerVal);683 } else {684 headerVal = [prev, headerVal];685 }686 }687 this.set('Set-Cookie', headerVal);688 return this;689};690691692/**693 * Set the location header to `url`.694 *695 * The given `url` can also be "back", which redirects696 * to the _Referrer_ or _Referer_ headers or "/".697 *698 * Examples:699 *700 * res.location('/foo/bar').;701 * res.location('http://example.com');702 * res.location('../login');703 *704 * @param {String} urlbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 705why, one step back705 * @return {ServerResponse} for chaining4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 706–737why, one step back706 * @api public707 */708709res.location = function(url){710 var req = this.req;711712 // "back" is an alias for the referrer713 if ('back' == url) url = req.get('Referrer') || '/';714715 // Respond716 this.set('Location', url);717 return this;718};719720/**721 * Redirect to the given `url` with optional response `status`722 * defaulting to 302.723 *724 * The resulting `url` is determined by `res.location()`, so725 * it will play nicely with mounted apps, relative paths,726 * `"back"` etc.727 *728 * Examples:729 *730 * res.redirect('/foo/bar');731 * res.redirect('http://example.com');732 * res.redirect(301, 'http://example.com');733 * res.redirect('../login'); // /blog/post/1 -> /blog/login734 *735 * @api public736 */737perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 738–739why, one step back738res.redirect = function redirect(url) {739 var address = url;Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
line 740why, one step back740 var body;perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 741why, one step back741 var status = 302;4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 742–743why, one step back742743 // allow status / urlperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 744–747why, one step back744 if (arguments.length === 2) {745 if (typeof arguments[0] === 'number') {746 status = arguments[0];747 address = arguments[1];4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 748why, one step back748 } else {Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
line 749why, one step back749 deprecate('res.redirect(ur, status): Use res.redirect(status, url) instead');4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 750–754why, one step back750 status = arguments[1];751 }752 }753754 // Set location headerperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 755–756why, one step back755 this.location(address);756 address = this.get('Location');4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 757–776why, one step back757758 // Support text/{plain,html} by default759 this.format({760 text: function(){761 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);762 },763764 html: function(){765 var u = escapeHtml(url);766 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';767 },768769 default: function(){770 body = '';771 }772 });773774 // Respond775 this.statusCode = status;776 this.set('Content-Length', Buffer.byteLength(body));perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 777–782why, one step back777778 if (this.req.method === 'HEAD') {779 this.end();780 }781782 this.end(body);4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 783–789why, one step back783};784785/**786 * Add `field` to Vary. If already present in the Vary set, then787 * this call is simply ignored.788 *789 * @param {Array|String} fieldbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 790why, one step back790 * @return {ServerResponse} for chaining4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 791–794why, one step back791 * @api public792 */793794res.vary = function(field){Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247
line 795why, one step back795 // checks for back-compatadd deprecation message to res.vary()Douglas Christopher Wilsonbefore adoption381b3b0
lines 796–799why, one step back796 if (!field || (Array.isArray(field) && !field.length)) {797 deprecate('res.vary(): Provide a field name');798 return this;799 }4.0.0-rc1Roman Shtylmanbefore adoption9df1067
line 800why, one step back800Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247
line 801why, one step back801 vary(this, field);4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 802–819why, one step back802803 return this;804};805806/**807 * Render `view` with the given `options` and optional callback `fn`.808 * When a callback function is given a response will _not_ be made809 * automatically, otherwise a response of _200_ and _text/html_ is given.810 *811 * Options:812 *813 * - `cache` boolean hinting to the engine it should cache814 * - `filename` filename of the view being rendered815 *816 * @api public817 */818819res.render = function(view, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 820–823why, one step back820 options = options || {};821 var self = this;822 var req = this.req;823 var app = req.app;4.0.0-rc1Roman Shtylmanbefore adoption9df1067
lines 824–841why, one step back824825 // support callback function as second arg826 if ('function' == typeof options) {827 fn = options, options = {};828 }829830 // merge res.locals831 options._locals = self.locals;832833 // default callback to respond834 fn = fn || function(err, str){835 if (err) return req.next(err);836 self.send(str);837 };838839 // render840 app.render(view, options, fn);841};