response.js
This file
Path
lib/response.js
1,053 lines · 24.2 KiB · JavaScript
Last changed by
Add statusCode properties to two errorsDouglas Christopher Wilsonbefore adoption5b4d4b4
History of this fileTake it
The walk stopped after 200 commits: lines older than 6bc7574 point at it.
Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024
lines 1–7why, one step back1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */7perf: enable strict modeDouglas Christopher Wilsonbefore adoptione71014f
lines 8–9why, one step back8'use strict';9docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 10–11why, one step back10/**11 * Module dependencies.perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 12why, one step back12 * @privatedocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 13–14why, one step back13 */14Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218
line 15why, one step back15var contentDisposition = require('content-disposition');docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 16–19why, one step back16var deprecate = require('depd')('express');17var escapeHtml = require('escape-html');18var http = require('http');19var isAbsolute = require('./utils').isAbsolute;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 20why, one step back20var onFinished = require('on-finished');docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 21why, one step back21var path = require('path');Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
line 22why, one step back22var merge = require('utils-merge');docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 23–43why, one step back23var sign = require('cookie-signature').sign;24var normalizeType = require('./utils').normalizeType;25var normalizeTypes = require('./utils').normalizeTypes;26var setCharset = require('./utils').setCharset;27var statusCodes = http.STATUS_CODES;28var cookie = require('cookie');29var send = require('send');30var extname = path.extname;31var mime = send.mime;32var resolve = path.resolve;33var vary = require('vary');3435/**36 * Response prototype.37 */3839var res = module.exports = {40 __proto__: http.ServerResponse.prototype41};4243/**perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 44–50why, one step back44 * Module variables.45 * @private46 */4748var charsetRegExp = /;\s*charset\s*=/;4950/**docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 51–54why, one step back51 * Set status `code`.52 *53 * @param {Number} code54 * @return {ServerResponse}perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 55why, one step back55 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 56–57why, one step back56 */57perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 58why, one step back58res.status = function status(code) {docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 59–74why, one step back59 this.statusCode = code;60 return this;61};6263/**64 * Set Link header field with the given `links`.65 *66 * Examples:67 *68 * res.links({69 * next: 'http://api.example.com/users?page=2',70 * last: 'http://api.example.com/users?page=5'71 * });72 *73 * @param {Object} links74 * @return {ServerResponse}perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 75why, one step back75 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 76–95why, one step back76 */7778res.links = function(links){79 var link = this.get('Link') || '';80 if (link) link += ', ';81 return this.set('Link', link + Object.keys(links).map(function(rel){82 return '<' + links[rel] + '>; rel="' + rel + '"';83 }).join(', '));84};8586/**87 * Send a response.88 *89 * Examples:90 *91 * res.send(new Buffer('wahoo'));92 * res.send({ some: 'json' });93 * res.send('<p>some html</p>');94 *95 * @param {string|number|boolean|object|Buffer} bodyperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 96why, one step back96 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 97–128why, one step back97 */9899res.send = function send(body) {100 var chunk = body;101 var encoding;102 var len;103 var req = this.req;104 var type;105106 // settings107 var app = this.app;108109 // allow status / body110 if (arguments.length === 2) {111 // res.send(body, status) backwards compat112 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {113 deprecate('res.send(body, status): Use res.status(status).send(body) instead');114 this.statusCode = arguments[1];115 } else {116 deprecate('res.send(status, body): Use res.status(status).send(body) instead');117 this.statusCode = arguments[0];118 chunk = arguments[1];119 }120 }121122 // disambiguate res.send(status) and res.send(status, num)123 if (typeof chunk === 'number' && arguments.length === 1) {124 // res.send(status) will set status message as text string125 if (!this.get('Content-Type')) {126 this.type('txt');127 }128Fix res.send to mention res.sendStatusDouglas Christopher Wilsonbefore adoption4dd9705
line 129why, one step back129 deprecate('res.send(status): Use res.sendStatus(status) instead');docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 130why, one step back130 this.statusCode = chunk;perf: use saved reference to http.STATUS_CODESThomas Cortbefore adoption91731b4
line 131why, one step back131 chunk = statusCodes[chunk];docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 132–178why, one step back132 }133134 switch (typeof chunk) {135 // string defaulting to html136 case 'string':137 if (!this.get('Content-Type')) {138 this.type('html');139 }140 break;141 case 'boolean':142 case 'number':143 case 'object':144 if (chunk === null) {145 chunk = '';146 } else if (Buffer.isBuffer(chunk)) {147 if (!this.get('Content-Type')) {148 this.type('bin');149 }150 } else {151 return this.json(chunk);152 }153 break;154 }155156 // write strings in utf-8157 if (typeof chunk === 'string') {158 encoding = 'utf8';159 type = this.get('Content-Type');160161 // reflect this in content-type162 if (typeof type === 'string') {163 this.set('Content-Type', setCharset(type, 'utf-8'));164 }165 }166167 // populate Content-Length168 if (chunk !== undefined) {169 if (!Buffer.isBuffer(chunk)) {170 // convert chunk to Buffer; saves later double conversions171 chunk = new Buffer(chunk, encoding);172 encoding = undefined;173 }174175 len = chunk.length;176 this.set('Content-Length', len);177 }178Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024
lines 179–184why, one step back179 // populate ETag180 var etag;181 var generateETag = len !== undefined && app.get('etag fn');182 if (typeof generateETag === 'function' && !this.get('ETag')) {183 if ((etag = generateETag(chunk, encoding))) {184 this.set('ETag', etag);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 185–198why, one step back185 }186 }187188 // freshness189 if (req.fresh) this.statusCode = 304;190191 // strip irrelevant headers192 if (204 == this.statusCode || 304 == this.statusCode) {193 this.removeHeader('Content-Type');194 this.removeHeader('Content-Length');195 this.removeHeader('Transfer-Encoding');196 chunk = '';197 }198Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024
line 199why, one step back199 if (req.method === 'HEAD') {Fix res.send double-calling res.end for HEAD requestsDouglas Christopher Wilsonbefore adoptionc24463d
line 200why, one step back200 // skip body for HEADdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 201why, one step back201 this.end();Fix res.send double-calling res.end for HEAD requestsDouglas Christopher Wilsonbefore adoptionc24463d
lines 202–204why, one step back202 } else {203 // respond204 this.end(chunk, encoding);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 205–218why, one step back205 }206207 return this;208};209210/**211 * Send JSON response.212 *213 * Examples:214 *215 * res.json(null);216 * res.json({ user: 'tj' });217 *218 * @param {string|number|boolean|object} objperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 219why, one step back219 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 220–260why, one step back220 */221222res.json = function json(obj) {223 var val = obj;224225 // allow status / body226 if (arguments.length === 2) {227 // res.json(body, status) backwards compat228 if (typeof arguments[1] === 'number') {229 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');230 this.statusCode = arguments[1];231 } else {232 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');233 this.statusCode = arguments[0];234 val = arguments[1];235 }236 }237238 // settings239 var app = this.app;240 var replacer = app.get('json replacer');241 var spaces = app.get('json spaces');242 var body = JSON.stringify(val, replacer, spaces);243244 // content-type245 if (!this.get('Content-Type')) {246 this.set('Content-Type', 'application/json');247 }248249 return this.send(body);250};251252/**253 * Send JSON response with JSONP callback support.254 *255 * Examples:256 *257 * res.jsonp(null);258 * res.jsonp({ user: 'tj' });259 *260 * @param {string|number|boolean|object} objperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 261why, one step back261 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 262–320why, one step back262 */263264res.jsonp = function jsonp(obj) {265 var val = obj;266267 // allow status / body268 if (arguments.length === 2) {269 // res.json(body, status) backwards compat270 if (typeof arguments[1] === 'number') {271 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');272 this.statusCode = arguments[1];273 } else {274 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');275 this.statusCode = arguments[0];276 val = arguments[1];277 }278 }279280 // settings281 var app = this.app;282 var replacer = app.get('json replacer');283 var spaces = app.get('json spaces');284 var body = JSON.stringify(val, replacer, spaces);285 var callback = this.req.query[app.get('jsonp callback name')];286287 // content-type288 if (!this.get('Content-Type')) {289 this.set('X-Content-Type-Options', 'nosniff');290 this.set('Content-Type', 'application/json');291 }292293 // fixup callback294 if (Array.isArray(callback)) {295 callback = callback[0];296 }297298 // jsonp299 if (typeof callback === 'string' && callback.length !== 0) {300 this.charset = 'utf-8';301 this.set('X-Content-Type-Options', 'nosniff');302 this.set('Content-Type', 'text/javascript');303304 // restrict callback charset305 callback = callback.replace(/[^\[\]\w$.]/g, '');306307 // replace chars not allowed in JavaScript that are in JSON308 body = body309 .replace(/\u2028/g, '\\u2028')310 .replace(/\u2029/g, '\\u2029');311312 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"313 // the typeof check is just to reduce client error noise314 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';315 }316317 return this.send(body);318};319320/**Add res.sendStatusSeth Samuelbefore adoption12f92a5
lines 321–331why, one step back321 * Send given HTTP status code.322 *323 * Sets the response status to `statusCode` and the body of the324 * response to the standard description from node's http.STATUS_CODES325 * or the statusCode number if no description.326 *327 * Examples:328 *329 * res.sendStatus(200);330 *331 * @param {number} statusCodeperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 332why, one step back332 * @publicAdd res.sendStatusSeth Samuelbefore adoption12f92a5
lines 333–335why, one step back333 */334335res.sendStatus = function sendStatus(statusCode) {perf: use saved reference to http.STATUS_CODESThomas Cortbefore adoption91731b4
line 336why, one step back336 var body = statusCodes[statusCode] || String(statusCode);Add res.sendStatusSeth Samuelbefore adoption12f92a5
lines 337–344why, one step back337338 this.statusCode = statusCode;339 this.type('txt');340341 return this.send(body);342};343344/**docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 345–347why, one step back345 * Transfer the file at the given `path`.346 *347 * Automatically sets the _Content-Type_ response header field.perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 348why, one step back348 * The callback `callback(err)` is invoked when the transfer is completedocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 349–381why, one step back349 * or when an error occurs. Be sure to check `res.sentHeader`350 * if you wish to attempt responding, as the header and some data351 * may have already been transferred.352 *353 * Options:354 *355 * - `maxAge` defaulting to 0 (can be string converted by `ms`)356 * - `root` root directory for relative filenames357 * - `headers` object of headers to serve with file358 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them359 *360 * Other options are passed along to `send`.361 *362 * Examples:363 *364 * The following example illustrates how `res.sendFile()` may365 * be used as an alternative for the `static()` middleware for366 * dynamic situations. The code backing `res.sendFile()` is actually367 * the same code, so HTTP cache support etc is identical.368 *369 * app.get('/user/:uid/photos/:file', function(req, res){370 * var uid = req.params.uid371 * , file = req.params.file;372 *373 * req.user.mayViewFilesFrom(uid, function(yes){374 * if (yes) {375 * res.sendFile('/uploads/' + uid + '/' + file);376 * } else {377 * res.send(403, 'Sorry! you cant see that.');378 * }379 * });380 * });381 *perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 382why, one step back382 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 383–384why, one step back383 */384perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 385–386why, one step back385res.sendFile = function sendFile(path, options, callback) {386 var done = callback;docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 387why, one step back387 var req = this.req;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 388why, one step back388 var res = this;docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 389why, one step back389 var next = req.next;perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 390why, one step back390 var opts = options || {};docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 391–397why, one step back391392 if (!path) {393 throw new TypeError('path argument is required to res.sendFile');394 }395396 // support function as second arg397 if (typeof options === 'function') {perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 398–399why, one step back398 done = options;399 opts = {};docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 400–401why, one step back400 }401perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 402why, one step back402 if (!opts.root && !isAbsolute(path)) {docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 403–405why, one step back403 throw new TypeError('path must be absolute or specify root to res.sendFile');404 }405Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 406why, one step back406 // create file streamdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 407why, one step back407 var pathname = encodeURI(path);perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 408why, one step back408 var file = send(req, pathname, opts);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 409why, one step back409Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 410why, one step back410 // transferperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 411–412why, one step back411 sendfile(res, file, opts, function (err) {412 if (done) return done(err);Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 413why, one step back413 if (err && err.code === 'EISDIR') return next();docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 414why, one step back414Fix res.sendFile logging standard write errorsDouglas Christopher Wilsonbefore adoptionb326ae8
line 415why, one step back415 // next() all but write errorsFix regression where "Request aborted" is logged using res.sendFileDouglas Christopher Wilsonbefore adoption7e0afa8
line 416why, one step back416 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 417–419why, one step back417 next(err);418 }419 });docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 420–425why, one step back420};421422/**423 * Transfer the file at the given `path`.424 *425 * Automatically sets the _Content-Type_ response header field.perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 426why, one step back426 * The callback `callback(err)` is invoked when the transfer is completedocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 427–459why, one step back427 * or when an error occurs. Be sure to check `res.sentHeader`428 * if you wish to attempt responding, as the header and some data429 * may have already been transferred.430 *431 * Options:432 *433 * - `maxAge` defaulting to 0 (can be string converted by `ms`)434 * - `root` root directory for relative filenames435 * - `headers` object of headers to serve with file436 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them437 *438 * Other options are passed along to `send`.439 *440 * Examples:441 *442 * The following example illustrates how `res.sendfile()` may443 * be used as an alternative for the `static()` middleware for444 * dynamic situations. The code backing `res.sendfile()` is actually445 * the same code, so HTTP cache support etc is identical.446 *447 * app.get('/user/:uid/photos/:file', function(req, res){448 * var uid = req.params.uid449 * , file = req.params.file;450 *451 * req.user.mayViewFilesFrom(uid, function(yes){452 * if (yes) {453 * res.sendfile('/uploads/' + uid + '/' + file);454 * } else {455 * res.send(403, 'Sorry! you cant see that.');456 * }457 * });458 * });459 *perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 460why, one step back460 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 461–462why, one step back461 */462perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 463–464why, one step back463res.sendfile = function (path, options, callback) {464 var done = callback;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 465–467why, one step back465 var req = this.req;466 var res = this;467 var next = req.next;perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 468why, one step back468 var opts = options || {};docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 469–470why, one step back469470 // support function as second argInvoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 471why, one step back471 if (typeof options === 'function') {perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 472–473why, one step back472 done = options;473 opts = {};docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 474–475why, one step back474 }475Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 476why, one step back476 // create file streamperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 477why, one step back477 var file = send(req, path, opts);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 478why, one step back478Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 479why, one step back479 // transferperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 480–481why, one step back480 sendfile(res, file, opts, function (err) {481 if (done) return done(err);Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 482why, one step back482 if (err && err.code === 'EISDIR') return next();docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 483why, one step back483Fix res.sendFile logging standard write errorsDouglas Christopher Wilsonbefore adoption4b26bbd
lines 484–485why, one step back484 // next() all but write errors485 if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 486–488why, one step back486 next(err);487 }488 });docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 489–497why, one step back489};490491res.sendfile = deprecate.function(res.sendfile,492 'res.sendfile: Use res.sendFile instead');493494/**495 * Transfer the file at the given `path` as an attachment.496 *497 * Optionally providing an alternate attachment `filename`,perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 498why, one step back498 * and optional callback `callback(err)`. The callback is invokeddocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 499–503why, one step back499 * when the data transfer is complete, or when an error has500 * ocurred. Be sure to check `res.headersSent` if you plan to respond.501 *502 * This method uses `res.sendfile()`.503 *perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 504why, one step back504 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 505–506why, one step back505 */506perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 507–510why, one step back507res.download = function download(path, filename, callback) {508 var done = callback;509 var name = filename;510docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 511–512why, one step back511 // support function as second arg512 if (typeof filename === 'function') {perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 513–514why, one step back513 done = filename;514 name = null;docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 515–518why, one step back515 }516517 // set Content-Disposition when file is sent518 var headers = {perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 519why, one step back519 'Content-Disposition': contentDisposition(name || path)docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 520–524why, one step back520 };521522 // Resolve the full path for sendFile523 var fullPath = resolve(path);524perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 525why, one step back525 return this.sendFile(fullPath, { headers: headers }, done);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 526–541why, one step back526};527528/**529 * Set _Content-Type_ response header with `type` through `mime.lookup()`530 * when it does not contain "/", or set the Content-Type to `type` otherwise.531 *532 * Examples:533 *534 * res.type('.html');535 * res.type('html');536 * res.type('json');537 * res.type('application/json');538 * res.type('png');539 *540 * @param {String} type541 * @return {ServerResponse} for chainingperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 542why, one step back542 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 543–545why, one step back543 */544545res.contentType =perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 546–551why, one step back546res.type = function contentType(type) {547 var ct = type.indexOf('/') === -1548 ? mime.lookup(type)549 : type;550551 return this.set('Content-Type', ct);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 552–607why, one step back552};553554/**555 * Respond to the Acceptable formats using an `obj`556 * of mime-type callbacks.557 *558 * This method uses `req.accepted`, an array of559 * acceptable types ordered by their quality values.560 * When "Accept" is not present the _first_ callback561 * is invoked, otherwise the first match is used. When562 * no match is performed the server responds with563 * 406 "Not Acceptable".564 *565 * Content-Type is set for you, however if you choose566 * you may alter this within the callback using `res.type()`567 * or `res.set('Content-Type', ...)`.568 *569 * res.format({570 * 'text/plain': function(){571 * res.send('hey');572 * },573 *574 * 'text/html': function(){575 * res.send('<p>hey</p>');576 * },577 *578 * 'appliation/json': function(){579 * res.send({ message: 'hey' });580 * }581 * });582 *583 * In addition to canonicalized MIME types you may584 * also use extnames mapped to these types:585 *586 * res.format({587 * text: function(){588 * res.send('hey');589 * },590 *591 * html: function(){592 * res.send('<p>hey</p>');593 * },594 *595 * json: function(){596 * res.send({ message: 'hey' });597 * }598 * });599 *600 * By default Express passes an `Error`601 * with a `.status` of 406 to `next(err)`602 * if a match is not made. If you provide603 * a `.default` callback it will be invoked604 * instead.605 *606 * @param {Object} obj607 * @return {ServerResponse} for chainingperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 608why, one step back608 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 609–618why, one step back609 */610611res.format = function(obj){612 var req = this.req;613 var next = req.next;614615 var fn = obj.default;616 if (fn) delete obj.default;617 var keys = Object.keys(obj);618Fix res.format error when only default providedBehcet Uyarbefore adoption24d1c98
lines 619–621why, one step back619 var key = keys.length > 0620 ? req.accepts(keys)621 : false;docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 622–631why, one step back622623 this.vary("Accept");624625 if (key) {626 this.set('Content-Type', normalizeType(key).value);627 obj[key](req, this, next);628 } else if (fn) {629 fn();630 } else {631 var err = new Error('Not Acceptable');Add statusCode properties to two errorsDouglas Christopher Wilsonbefore adoption5b4d4b4
line 632why, one step back632 err.status = err.statusCode = 406;docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 633–644why, one step back633 err.types = normalizeTypes(keys).map(function(o){ return o.value });634 next(err);635 }636637 return this;638};639640/**641 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.642 *643 * @param {String} filename644 * @return {ServerResponse}perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 645why, one step back645 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 646–647why, one step back646 */647Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218
lines 648–652why, one step back648res.attachment = function attachment(filename) {649 if (filename) {650 this.type(extname(filename));651 }652docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 653why, one step back653 this.set('Content-Disposition', contentDisposition(filename));Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218
line 654why, one step back654docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 655–658why, one step back655 return this;656};657658/**Add res.append(field, val) to append headersDouglas Christopher Wilsonbefore adoptionf6f78e5
lines 659–669why, one step back659 * Append additional header `field` with value `val`.660 *661 * Example:662 *663 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);664 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');665 * res.append('Warning', '199 Miscellaneous warning');666 *667 * @param {String} field668 * @param {String|Array} val669 * @return {ServerResponse} for chainingperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 670why, one step back670 * @publicAdd res.append(field, val) to append headersDouglas Christopher Wilsonbefore adoptionf6f78e5
lines 671–687why, one step back671 */672673res.append = function append(field, val) {674 var prev = this.get(field);675 var value = val;676677 if (prev) {678 // concat the new and prev vals679 value = Array.isArray(prev) ? prev.concat(val)680 : Array.isArray(val) ? [prev].concat(val)681 : [prev, val];682 }683684 return this.set(field, value);685};686687/**docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 688–698why, one step back688 * Set header `field` to `val`, or pass689 * an object of header fields.690 *691 * Examples:692 *693 * res.set('Foo', ['bar', 'baz']);694 * res.set('Accept', 'application/json');695 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });696 *697 * Aliased as `res.header()`.698 *docs: update res.set jsdocPhatbefore adoption4b70375
lines 699–700why, one step back699 * @param {String|Object} field700 * @param {String|Array} valdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 701why, one step back701 * @return {ServerResponse} for chainingperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 702why, one step back702 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 703–707why, one step back703 */704705res.set =706res.header = function header(field, val) {707 if (arguments.length === 2) {perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 708–715why, one step back708 var value = Array.isArray(val)709 ? val.map(String)710 : String(val);711712 // add charset to content-type713 if (field.toLowerCase() === 'content-type' && !charsetRegExp.test(value)) {714 var charset = mime.charsets.lookup(value.split(';')[0]);715 if (charset) value += '; charset=' + charset.toLowerCase();docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 716why, one step back716 }perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 717–718why, one step back717718 this.setHeader(field, value);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 719–731why, one step back719 } else {720 for (var key in field) {721 this.set(key, field[key]);722 }723 }724 return this;725};726727/**728 * Get value for header `field`.729 *730 * @param {String} field731 * @return {String}perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 732why, one step back732 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 733–744why, one step back733 */734735res.get = function(field){736 return this.getHeader(field);737};738739/**740 * Clear cookie `name`.741 *742 * @param {String} name743 * @param {Object} options744 * @return {ServerResponse} for chainingperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 745why, one step back745 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 746–747why, one step back746 */747perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 748–751why, one step back748res.clearCookie = function clearCookie(name, options) {749 var opts = merge({ expires: new Date(1), path: '/' }, options);750751 return this.cookie(name, '', opts);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 752–754why, one step back752};753754/**perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 755why, one step back755 * Set cookie `name` to `value`, with the given `options`.docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 756–771why, one step back756 *757 * Options:758 *759 * - `maxAge` max-age in milliseconds, converted to `expires`760 * - `signed` sign the cookie761 * - `path` defaults to "/"762 *763 * Examples:764 *765 * // "Remember Me" for 15 minutes766 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });767 *768 * // save as above769 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })770 *771 * @param {String} nameperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 772why, one step back772 * @param {String|Object} valuedocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 773–774why, one step back773 * @param {Options} options774 * @return {ServerResponse} for chainingperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 775why, one step back775 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 776–777why, one step back776 */777perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 778–779why, one step back778res.cookie = function (name, value, options) {779 var opts = merge({}, options);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 780why, one step back780 var secret = this.req.secret;perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 781–784why, one step back781 var signed = opts.signed;782783 if (signed && !secret) {784 throw new Error('cookieParser("secret") required for signed cookies');docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 785–786why, one step back785 }786perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 787–803why, one step back787 var val = typeof value === 'object'788 ? 'j:' + JSON.stringify(value)789 : String(value);790791 if (signed) {792 val = 's:' + sign(val, secret);793 }794795 if ('maxAge' in opts) {796 opts.expires = new Date(Date.now() + opts.maxAge);797 opts.maxAge /= 1000;798 }799800 if (opts.path == null) {801 opts.path = '/';802 }803Simplify res.cookie to call res.appendDouglas Christopher Wilsonbefore adoption5915894
line 804why, one step back804 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 805why, one step back805docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 806–822why, one step back806 return this;807};808809/**810 * Set the location header to `url`.811 *812 * The given `url` can also be "back", which redirects813 * to the _Referrer_ or _Referer_ headers or "/".814 *815 * Examples:816 *817 * res.location('/foo/bar').;818 * res.location('http://example.com');819 * res.location('../login');820 *821 * @param {String} url822 * @return {ServerResponse} for chainingperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 823why, one step back823 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 824–825why, one step back824 */825perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 826–827why, one step back826res.location = function location(url) {827 var loc = url;docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 828–829why, one step back828829 // "back" is an alias for the referrerperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 830–832why, one step back830 if (url === 'back') {831 loc = this.req.get('Referrer') || '/';832 }docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 833why, one step back833perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 834–835why, one step back834 // set location835 this.set('Location', loc);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 836–853why, one step back836 return this;837};838839/**840 * Redirect to the given `url` with optional response `status`841 * defaulting to 302.842 *843 * The resulting `url` is determined by `res.location()`, so844 * it will play nicely with mounted apps, relative paths,845 * `"back"` etc.846 *847 * Examples:848 *849 * res.redirect('/foo/bar');850 * res.redirect('http://example.com');851 * res.redirect(301, 'http://example.com');852 * res.redirect('../login'); // /blog/post/1 -> /blog/login853 *perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 854why, one step back854 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 855–867why, one step back855 */856857res.redirect = function redirect(url) {858 var address = url;859 var body;860 var status = 302;861862 // allow status / url863 if (arguments.length === 2) {864 if (typeof arguments[0] === 'number') {865 status = arguments[0];866 address = arguments[1];867 } else {Merge tag '3.17.8'Douglas Christopher Wilsonbefore adoption2c5ed88
line 868why, one step back868 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 869–879why, one step back869 status = arguments[1];870 }871 }872873 // Set location header874 this.location(address);875 address = this.get('Location');876877 // Support text/{plain,html} by default878 this.format({879 text: function(){Fix res.redirect body when redirect status specifiedAlex Upadhyaybefore adoption6f0302f
line 880why, one step back880 body = statusCodes[status] + '. Redirecting to ' + encodeURI(address);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 881–883why, one step back881 },882883 html: function(){Fix res.redirect body when redirect status specifiedAlex Upadhyaybefore adoption6f0302f
line 884why, one step back884 var u = escapeHtml(address);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 885–898why, one step back885 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';886 },887888 default: function(){889 body = '';890 }891 });892893 // Respond894 this.statusCode = status;895 this.set('Content-Length', Buffer.byteLength(body));896897 if (this.req.method === 'HEAD') {898 this.end();Fix res.redirect double-calling res.end for HEAD requestsKevin Shaybefore adoption2ccb6cf
lines 899–900why, one step back899 } else {900 this.end(body);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 901–909why, one step back901 }902};903904/**905 * Add `field` to Vary. If already present in the Vary set, then906 * this call is simply ignored.907 *908 * @param {Array|String} field909 * @return {ServerResponse} for chainingperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 910why, one step back910 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 911–934why, one step back911 */912913res.vary = function(field){914 // checks for back-compat915 if (!field || (Array.isArray(field) && !field.length)) {916 deprecate('res.vary(): Provide a field name');917 return this;918 }919920 vary(this, field);921922 return this;923};924925/**926 * Render `view` with the given `options` and optional callback `fn`.927 * When a callback function is given a response will _not_ be made928 * automatically, otherwise a response of _200_ and _text/html_ is given.929 *930 * Options:931 *932 * - `cache` boolean hinting to the engine it should cache933 * - `filename` filename of the view being rendered934 *perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 935why, one step back935 * @publicdocs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 936–937why, one step back936 */937perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 938–941why, one step back938res.render = function render(view, options, callback) {939 var app = this.req.app;940 var done = callback;941 var opts = options || {};docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 942why, one step back942 var req = this.req;perf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 943why, one step back943 var self = this;docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 944–945why, one step back944945 // support callback function as second argperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
lines 946–948why, one step back946 if (typeof options === 'function') {947 done = options;948 opts = {};docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 949–951why, one step back949 }950951 // merge res.localsperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 952why, one step back952 opts._locals = self.locals;docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 953–954why, one step back953954 // default callback to respondperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 955why, one step back955 done = done || function (err, str) {docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
lines 956–960why, one step back956 if (err) return req.next(err);957 self.send(str);958 };959960 // renderperf: remove argument reassignments in response prototypeDouglas Christopher Wilsonbefore adoptionbb53b20
line 961why, one step back961 app.render(view, opts, done);docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574
line 962why, one step back962};Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 963–966why, one step back963964// pipe the send file stream965function sendfile(res, file, options, callback) {966 var done = false;Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99
line 967why, one step back967 var streaming;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 968why, one step back968Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99
lines 969–974why, one step back969 // request aborted970 function onaborted() {971 if (done) return;972 done = true;973974 var err = new Error('Request aborted');Fix wrong code on aborted connections from res.sendFileDouglas Christopher Wilsonbefore adoptiondbc61fc
line 975why, one step back975 err.code = 'ECONNABORTED';Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99
lines 976–978why, one step back976 callback(err);977 }978Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 979–1002why, one step back979 // directory980 function ondirectory() {981 if (done) return;982 done = true;983984 var err = new Error('EISDIR, read');985 err.code = 'EISDIR';986 callback(err);987 }988989 // errors990 function onerror(err) {991 if (done) return;992 done = true;993 callback(err);994 }995996 // ended997 function onend() {998 if (done) return;999 done = true;1000 callback();1001 }1002Fix incorrect "Request aborted" for res.sendFile when HEAD or 304Douglas Christopher Wilsonbefore adoption3387916
lines 1003–1004why, one step back1003 // file1004 function onfile() {Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99
line 1005why, one step back1005 streaming = false;Fix incorrect "Request aborted" for res.sendFile when HEAD or 304Douglas Christopher Wilsonbefore adoption3387916
lines 1006–1007why, one step back1006 }1007Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 1008–1009why, one step back1008 // finished1009 function onfinish(err) {Fix ECONNRESET errors from res.sendFile usageDouglas Christopher Wilsonbefore adoption14a5875
line 1010why, one step back1010 if (err && err.code === 'ECONNRESET') return onaborted();Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 1011–1014why, one step back1011 if (err) return onerror(err);1012 if (done) return;10131014 setImmediate(function () {Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99
lines 1015–1016why, one step back1015 if (streaming !== false && !done) {1016 onaborted();Fix incorrect "Request aborted" for res.sendFile when HEAD or 304Douglas Christopher Wilsonbefore adoption3387916
lines 1017–1019why, one step back1017 return;1018 }1019Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99
lines 1020–1022why, one step back1020 if (done) return;1021 done = true;1022 callback();Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 1023–1025why, one step back1023 });1024 }1025Fix incorrect "Request aborted" for res.sendFile when HEAD or 304Douglas Christopher Wilsonbefore adoption3387916
lines 1026–1031why, one step back1026 // streaming1027 function onstream() {1028 streaming = true;1029 }10301031 file.on('directory', ondirectory);Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 1032–1033why, one step back1032 file.on('end', onend);1033 file.on('error', onerror);Fix incorrect "Request aborted" for res.sendFile when HEAD or 304Douglas Christopher Wilsonbefore adoption3387916
lines 1034–1035why, one step back1034 file.on('file', onfile);1035 file.on('stream', onstream);Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99
line 1036why, one step back1036 onFinished(res, onfinish);Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 1037–1053why, one step back10371038 if (options.headers) {1039 // set headers on successful transfer1040 file.on('headers', function headers(res) {1041 var obj = options.headers;1042 var keys = Object.keys(obj);10431044 for (var i = 0; i < keys.length; i++) {1045 var k = keys[i];1046 res.setHeader(k, obj[k]);1047 }1048 });1049 }10501051 // pipe1052 file.pipe(res);1053}