response.js
This file
Path
lib/response.js
1,053 lines · 24.3 KiB · JavaScript
Last changed by
feat: add deprecation warnings for redirect arguments undefined (#6405)Sebastian Beltranbefore adoptionc5b8d55
History of this fileTake it
The walk stopped after 200 commits: lines older than 8a387d3 point at it.
deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 1–15why, one step back1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */78'use strict';910/**11 * Module dependencies.12 * @private13 */1415var contentDisposition = require('content-disposition');Merge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
line 16why, one step back16var createError = require('http-errors')feat: add deprecation warnings for redirect arguments undefined (#6405)Sebastian Beltranbefore adoptionc5b8d55
line 17why, one step back17var deprecate = require('depd')('express');Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
line 18why, one step back18var encodeUrl = require('encodeurl');deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 19why, one step back19var escapeHtml = require('escape-html');fix(refactor): prefix built-in node module importsSzymon Łągiewkabefore adoption4111359
line 20why, one step back20var http = require('node:http');deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 21why, one step back21var onFinished = require('on-finished');Use mime-types for file to content type mappingDouglas Christopher Wilsonbefore adoptiona0276c6
line 22why, one step back22var mime = require('mime-types')fix(refactor): prefix built-in node module importsSzymon Łągiewkabefore adoption4111359
lines 23–24why, one step back23var path = require('node:path');24var pathIsAbsolute = require('node:path').isAbsolute;Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
line 25why, one step back25var statuses = require('statuses')deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 26–34why, one step back26var sign = require('cookie-signature').sign;27var normalizeType = require('./utils').normalizeType;28var normalizeTypes = require('./utils').normalizeTypes;29var setCharset = require('./utils').setCharset;30var cookie = require('cookie');31var send = require('send');32var extname = path.extname;33var resolve = path.resolve;34var vary = require('vary');chore: enforce explicit Buffer import and add lint rule (#6525)Shivam Sharmabefore adoption98c85eb
line 35why, one step back35const { Buffer } = require('node:buffer');deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 36–38why, one step back3637/**38 * Response prototype.Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
line 39why, one step back39 * @publicdeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 40–41why, one step back40 */41Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
line 42why, one step back42var res = Object.create(http.ServerResponse.prototype)deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 43–44why, one step back4344/**Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
lines 45–51why, one step back45 * Module exports.46 * @public47 */4849module.exports = res5051/**Merge branch '5.0' into 5-mergectcpipbefore adoptiondde1f7d
line 52why, one step back52 * Set the HTTP status code for the response.deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 53why, one step back53 *Merge branch '5.0' into 5-mergectcpipbefore adoptiondde1f7d
lines 54–60why, one step back54 * Expects an integer value between 100 and 999 inclusive.55 * Throws an error if the provided status code is not an integer or if it's outside the allowable range.56 *57 * @param {number} code - The HTTP status code to set.58 * @return {ServerResponse} - Returns itself for chaining methods.59 * @throws {TypeError} If `code` is not an integer.60 * @throws {RangeError} If `code` is outside the range 100 to 999.deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 61–64why, one step back61 * @public62 */6364res.status = function status(code) {Merge branch '5.0' into 5-mergectcpipbefore adoptiondde1f7d
lines 65–67why, one step back65 // Check if the status code is not an integer66 if (!Number.isInteger(code)) {67 throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`);Merge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
line 68why, one step back68 }Merge branch '5.0' into 5-mergectcpipbefore adoptiondde1f7d
lines 69–73why, one step back69 // Check if the status code is outside of Node's valid range70 if (code < 100 || code > 999) {71 throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`);72 }73deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 74–84why, one step back74 this.statusCode = code;75 return this;76};7778/**79 * Set Link header field with the given `links`.80 *81 * Examples:82 *83 * res.links({84 * next: 'http://api.example.com/users?page=2',feat: Extend res.links() to allow adding multiple links with the same rel (closes #2729) (#4885)Andrea Polverinobefore adoptioncaa4f68
lines 85–89why, one step back85 * last: 'http://api.example.com/users?page=5',86 * pages: [87 * 'http://api.example.com/users?page=1',88 * 'http://api.example.com/users?page=2'89 * ]deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 90–96why, one step back90 * });91 *92 * @param {Object} links93 * @return {ServerResponse}94 * @public95 */96feat: Extend res.links() to allow adding multiple links with the same rel (closes #2729) (#4885)Andrea Polverinobefore adoptioncaa4f68
line 97why, one step back97res.links = function(links) {deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 98–99why, one step back98 var link = this.get('Link') || '';99 if (link) link += ', ';feat: Extend res.links() to allow adding multiple links with the same rel (closes #2729) (#4885)Andrea Polverinobefore adoptioncaa4f68
lines 100–108why, one step back100 return this.set('Link', link + Object.keys(links).map(function(rel) {101 // Allow multiple links if links[rel] is an array102 if (Array.isArray(links[rel])) {103 return links[rel].map(function (singleLink) {104 return `<${singleLink}>; rel="${rel}"`;105 }).join(', ');106 } else {107 return `<${links[rel]}>; rel="${rel}"`;108 }deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 109–116why, one step back109 }).join(', '));110};111112/**113 * Send a response.114 *115 * Examples:116 *Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 117why, one step back117 * res.send(Buffer.from('wahoo'));deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 118–145why, one step back118 * res.send({ some: 'json' });119 * res.send('<p>some html</p>');120 *121 * @param {string|number|boolean|object|Buffer} body122 * @public123 */124125res.send = function send(body) {126 var chunk = body;127 var encoding;128 var req = this.req;129 var type;130131 // settings132 var app = this.app;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 = '';feat: Added check to support Uint8Array in response sending (#6285)Alexander Ceruttibefore adoption55869f4
line 146why, one step back146 } else if (ArrayBuffer.isView(chunk)) {deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 147–166why, one step back147 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 }166Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 167–170why, one step back167 // determine if ETag should be generated168 var etagFn = app.get('etag fn')169 var generateETag = !this.get('ETag') && typeof etagFn === 'function'170deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 171why, one step back171 // populate Content-LengthMerge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 172why, one step back172 var lendeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 173why, one step back173 if (chunk !== undefined) {Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 174–182why, one step back174 if (Buffer.isBuffer(chunk)) {175 // get length of Buffer176 len = chunk.length177 } else if (!generateETag && chunk.length < 1000) {178 // just calculate length when no ETag + small chunk179 len = Buffer.byteLength(chunk, encoding)180 } else {181 // convert chunk to Buffer and calculate182 chunk = Buffer.from(chunk, encoding)deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 183why, one step back183 encoding = undefined;Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 184why, one step back184 len = chunk.lengthdeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 185–191why, one step back185 }186187 this.set('Content-Length', len);188 }189190 // populate ETag191 var etag;Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 192–193why, one step back192 if (generateETag && len !== undefined) {193 if ((etag = etagFn(chunk, encoding))) {deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 194–198why, one step back194 this.set('ETag', etag);195 }196 }197198 // freshnessMerge branch '5.0' into 5-mergectcpipbefore adoptiondde1f7d
line 199why, one step back199 if (req.fresh) this.status(304);deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 200–201why, one step back200201 // strip irrelevant headersMerge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
line 202why, one step back202 if (204 === this.statusCode || 304 === this.statusCode) {deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 203–208why, one step back203 this.removeHeader('Content-Type');204 this.removeHeader('Content-Length');205 this.removeHeader('Transfer-Encoding');206 chunk = '';207 }208Merge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
lines 209–215why, one step back209 // alter headers for 205210 if (this.statusCode === 205) {211 this.set('Content-Length', '0')212 this.removeHeader('Transfer-Encoding')213 chunk = ''214 }215deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 216–241why, one step back216 if (req.method === 'HEAD') {217 // skip body for HEAD218 this.end();219 } else {220 // respond221 this.end(chunk, encoding);222 }223224 return this;225};226227/**228 * Send JSON response.229 *230 * Examples:231 *232 * res.json(null);233 * res.json({ user: 'tj' });234 *235 * @param {string|number|boolean|object} obj236 * @public237 */238239res.json = function json(obj) {240 // settings241 var app = this.app;Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 242why, one step back242 var escape = app.get('json escape')deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 243–244why, one step back243 var replacer = app.get('json replacer');244 var spaces = app.get('json spaces');Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 245why, one step back245 var body = stringify(obj, replacer, spaces, escape)deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 246–269why, one step back246247 // content-type248 if (!this.get('Content-Type')) {249 this.set('Content-Type', 'application/json');250 }251252 return this.send(body);253};254255/**256 * Send JSON response with JSONP callback support.257 *258 * Examples:259 *260 * res.jsonp(null);261 * res.jsonp({ user: 'tj' });262 *263 * @param {string|number|boolean|object} obj264 * @public265 */266267res.jsonp = function jsonp(obj) {268 // settings269 var app = this.app;Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 270why, one step back270 var escape = app.get('json escape')deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 271–272why, one step back271 var replacer = app.get('json replacer');272 var spaces = app.get('json spaces');Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 273why, one step back273 var body = stringify(obj, replacer, spaces, escape)deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 274–294why, one step back274 var callback = this.req.query[app.get('jsonp callback name')];275276 // content-type277 if (!this.get('Content-Type')) {278 this.set('X-Content-Type-Options', 'nosniff');279 this.set('Content-Type', 'application/json');280 }281282 // fixup callback283 if (Array.isArray(callback)) {284 callback = callback[0];285 }286287 // jsonp288 if (typeof callback === 'string' && callback.length !== 0) {289 this.set('X-Content-Type-Options', 'nosniff');290 this.set('Content-Type', 'text/javascript');291292 // restrict callback charset293 callback = callback.replace(/[^\[\]\w$.]/g, '');294Merge tag '4.17.2'Douglas Christopher Wilsonbefore adoptionc7d528c
lines 295–303why, one step back295 if (body === undefined) {296 // empty argument297 body = ''298 } else if (typeof body === 'string') {299 // replace chars not allowed in JavaScript that are in JSON300 body = body301 .replace(/\u2028/g, '\\u2028')302 .replace(/\u2029/g, '\\u2029')303 }deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 304–328why, one step back304305 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"306 // the typeof check is just to reduce client error noise307 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';308 }309310 return this.send(body);311};312313/**314 * Send given HTTP status code.315 *316 * Sets the response status to `statusCode` and the body of the317 * response to the standard description from node's http.STATUS_CODES318 * or the statusCode number if no description.319 *320 * Examples:321 *322 * res.sendStatus(200);323 *324 * @param {number} statusCode325 * @public326 */327328res.sendStatus = function sendStatus(statusCode) {Merge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
line 329why, one step back329 var body = statuses.message[statusCode] || String(statusCode)deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 330why, one step back330Merge branch '5.0' into 5-mergectcpipbefore adoptiondde1f7d
line 331why, one step back331 this.status(statusCode);deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 332–341why, one step back332 this.type('txt');333334 return this.send(body);335};336337/**338 * Transfer the file at the given `path`.339 *340 * Automatically sets the _Content-Type_ response header field.341 * The callback `callback(err)` is invoked when the transfer is completeMerge tag '4.17.2'Douglas Christopher Wilsonbefore adoptionc7d528c
line 342why, one step back342 * or when an error occurs. Be sure to check `res.headersSent`deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 343–388why, one step back343 * if you wish to attempt responding, as the header and some data344 * may have already been transferred.345 *346 * Options:347 *348 * - `maxAge` defaulting to 0 (can be string converted by `ms`)349 * - `root` root directory for relative filenames350 * - `headers` object of headers to serve with file351 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them352 *353 * Other options are passed along to `send`.354 *355 * Examples:356 *357 * The following example illustrates how `res.sendFile()` may358 * be used as an alternative for the `static()` middleware for359 * dynamic situations. The code backing `res.sendFile()` is actually360 * the same code, so HTTP cache support etc is identical.361 *362 * app.get('/user/:uid/photos/:file', function(req, res){363 * var uid = req.params.uid364 * , file = req.params.file;365 *366 * req.user.mayViewFilesFrom(uid, function(yes){367 * if (yes) {368 * res.sendFile('/uploads/' + uid + '/' + file);369 * } else {370 * res.send(403, 'Sorry! you cant see that.');371 * }372 * });373 * });374 *375 * @public376 */377378res.sendFile = function sendFile(path, options, callback) {379 var done = callback;380 var req = this.req;381 var res = this;382 var next = req.next;383 var opts = options || {};384385 if (!path) {386 throw new TypeError('path argument is required to res.sendFile');387 }388Merge tag '4.17.1'Douglas Christopher Wilsonbefore adoption121fe99
lines 389–392why, one step back389 if (typeof path !== 'string') {390 throw new TypeError('path must be a string to res.sendFile')391 }392deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 393–404why, one step back393 // support function as second arg394 if (typeof options === 'function') {395 done = options;396 opts = {};397 }398399 if (!opts.root && !pathIsAbsolute(path)) {400 throw new TypeError('path must be absolute or specify root to res.sendFile');401 }402403 // create file stream404 var pathname = encodeURI(path);feat: add support for ETag option in res.sendFile (#6073)Juan Josébefore adoption327af12
lines 405–407why, one step back405406 // wire application etag option to send407 opts.etag = this.app.enabled('etag');deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 408–427why, one step back408 var file = send(req, pathname, opts);409410 // transfer411 sendfile(res, file, opts, function (err) {412 if (done) return done(err);413 if (err && err.code === 'EISDIR') return next();414415 // next() all but write errors416 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {417 next(err);418 }419 });420};421422/**423 * Transfer the file at the given `path` as an attachment.424 *425 * Optionally providing an alternate attachment `filename`,426 * and optional callback `callback(err)`. The callback is invoked427 * when the data transfer is complete, or when an error hasMerge tag '4.17.3'Douglas Christopher Wilsonbefore adoption318fd4b
line 428why, one step back428 * occurred. Be sure to check `res.headersSent` if you plan to respond.deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 429why, one step back429 *Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 430–434why, one step back430 * Optionally providing an `options` object to use with `res.sendFile()`.431 * This function will set the `Content-Disposition` header, overriding432 * any `Content-Disposition` header passed as header options in order433 * to set the attachment and filename.434 *deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 435–439why, one step back435 * This method uses `res.sendFile()`.436 *437 * @public438 */439Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 440why, one step back440res.download = function download (path, filename, options, callback) {deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 441–442why, one step back441 var done = callback;442 var name = filename;Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 443why, one step back443 var opts = options || nulldeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 444why, one step back444Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 445why, one step back445 // support function as second or third argdeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 446–448why, one step back446 if (typeof filename === 'function') {447 done = filename;448 name = null;Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 449–452why, one step back449 opts = null450 } else if (typeof options === 'function') {451 done = options452 opts = nulldeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 453–454why, one step back453 }454Merge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
lines 455–461why, one step back455 // support optional filename, where options may be in it's place456 if (typeof filename === 'object' &&457 (typeof options === 'function' || options === undefined)) {458 name = null459 opts = filename460 }461deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 462–466why, one step back462 // set Content-Disposition when file is sent463 var headers = {464 'Content-Disposition': contentDisposition(name || path)465 };466Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 467–481why, one step back467 // merge user-provided headers468 if (opts && opts.headers) {469 var keys = Object.keys(opts.headers)470 for (var i = 0; i < keys.length; i++) {471 var key = keys[i]472 if (key.toLowerCase() !== 'content-disposition') {473 headers[key] = opts.headers[key]474 }475 }476 }477478 // merge user-provided options479 opts = Object.create(opts)480 opts.headers = headers481deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 482why, one step back482 // Resolve the full path for sendFileMerge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
lines 483–485why, one step back483 var fullPath = !opts.root484 ? resolve(path)485 : pathdeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 486why, one step back486Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 487–488why, one step back487 // send file488 return this.sendFile(fullPath, opts, done)deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 489–491why, one step back489};490491/**Use mime-types for file to content type mappingDouglas Christopher Wilsonbefore adoptiona0276c6
line 492why, one step back492 * Set _Content-Type_ response header with `type` through `mime.contentType()`deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 493why, one step back493 * when it does not contain "/", or set the Content-Type to `type` otherwise.Use mime-types for file to content type mappingDouglas Christopher Wilsonbefore adoptiona0276c6
lines 494–495why, one step back494 * When no mapping is found though `mime.contentType()`, the type is set to495 * "application/octet-stream".deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 496–512why, one step back496 *497 * Examples:498 *499 * res.type('.html');500 * res.type('html');501 * res.type('json');502 * res.type('application/json');503 * res.type('png');504 *505 * @param {String} type506 * @return {ServerResponse} for chaining507 * @public508 */509510res.contentType =511res.type = function contentType(type) {512 var ct = type.indexOf('/') === -1Use mime-types for file to content type mappingDouglas Christopher Wilsonbefore adoptiona0276c6
line 513why, one step back513 ? (mime.contentType(type) || 'application/octet-stream')deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 514–542why, one step back514 : type;515516 return this.set('Content-Type', ct);517};518519/**520 * Respond to the Acceptable formats using an `obj`521 * of mime-type callbacks.522 *523 * This method uses `req.accepted`, an array of524 * acceptable types ordered by their quality values.525 * When "Accept" is not present the _first_ callback526 * is invoked, otherwise the first match is used. When527 * no match is performed the server responds with528 * 406 "Not Acceptable".529 *530 * Content-Type is set for you, however if you choose531 * you may alter this within the callback using `res.type()`532 * or `res.set('Content-Type', ...)`.533 *534 * res.format({535 * 'text/plain': function(){536 * res.send('hey');537 * },538 *539 * 'text/html': function(){540 * res.send('<p>hey</p>');541 * },542 *Merge tag '4.17.2'Douglas Christopher Wilsonbefore adoptionc7d528c
line 543why, one step back543 * 'application/json': function () {deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 544–579why, one step back544 * res.send({ message: 'hey' });545 * }546 * });547 *548 * In addition to canonicalized MIME types you may549 * also use extnames mapped to these types:550 *551 * res.format({552 * text: function(){553 * res.send('hey');554 * },555 *556 * html: function(){557 * res.send('<p>hey</p>');558 * },559 *560 * json: function(){561 * res.send({ message: 'hey' });562 * }563 * });564 *565 * By default Express passes an `Error`566 * with a `.status` of 406 to `next(err)`567 * if a match is not made. If you provide568 * a `.default` callback it will be invoked569 * instead.570 *571 * @param {Object} obj572 * @return {ServerResponse} for chaining573 * @public574 */575576res.format = function(obj){577 var req = this.req;578 var next = req.next;579Merge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
lines 580–581why, one step back580 var keys = Object.keys(obj)581 .filter(function (v) { return v !== 'default' })deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 582–591why, one step back582583 var key = keys.length > 0584 ? req.accepts(keys)585 : false;586587 this.vary("Accept");588589 if (key) {590 this.set('Content-Type', normalizeType(key).value);591 obj[key](req, this, next);Merge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
lines 592–593why, one step back592 } else if (obj.default) {593 obj.default(req, this, next)deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 594why, one step back594 } else {Merge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
lines 595–597why, one step back595 next(createError(406, {596 types: normalizeTypes(keys).map(function (o) { return o.value })597 }))deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 598–643why, one step back598 }599600 return this;601};602603/**604 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.605 *606 * @param {String} filename607 * @return {ServerResponse}608 * @public609 */610611res.attachment = function attachment(filename) {612 if (filename) {613 this.type(extname(filename));614 }615616 this.set('Content-Disposition', contentDisposition(filename));617618 return this;619};620621/**622 * Append additional header `field` with value `val`.623 *624 * Example:625 *626 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);627 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');628 * res.append('Warning', '199 Miscellaneous warning');629 *630 * @param {String} field631 * @param {String|Array} val632 * @return {ServerResponse} for chaining633 * @public634 */635636res.append = function append(field, val) {637 var prev = this.get(field);638 var value = val;639640 if (prev) {641 // concat the new and prev vals642 value = Array.isArray(prev) ? prev.concat(val)643 : Array.isArray(val) ? [prev].concat(val)Merge tag '4.17.2'Douglas Christopher Wilsonbefore adoptionc7d528c
line 644why, one step back644 : [prev, val]deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 645–661why, one step back645 }646647 return this.set(field, value);648};649650/**651 * Set header `field` to `val`, or pass652 * an object of header fields.653 *654 * Examples:655 *656 * res.set('Foo', ['bar', 'baz']);657 * res.set('Accept', 'application/json');658 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });659 *660 * Aliased as `res.header()`.661 *Use mime-types for file to content type mappingDouglas Christopher Wilsonbefore adoptiona0276c6
lines 662–664why, one step back662 * When the set header is "Content-Type", the type is expanded to include663 * the charset if not present using `mime.contentType()`.664 *deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 665–678why, one step back665 * @param {String|Object} field666 * @param {String|Array} val667 * @return {ServerResponse} for chaining668 * @public669 */670671res.set =672res.header = function header(field, val) {673 if (arguments.length === 2) {674 var value = Array.isArray(val)675 ? val.map(String)676 : String(val);677678 // add charset to content-typeMerge tag '4.15.4'Douglas Christopher Wilsonbefore adoptionc319fe2
lines 679–682why, one step back679 if (field.toLowerCase() === 'content-type') {680 if (Array.isArray(value)) {681 throw new TypeError('Content-Type cannot be set to an Array');682 }Use mime-types for file to content type mappingDouglas Christopher Wilsonbefore adoptiona0276c6
line 683why, one step back683 value = mime.contentType(value)deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 684–710why, one step back684 }685686 this.setHeader(field, value);687 } else {688 for (var key in field) {689 this.set(key, field[key]);690 }691 }692 return this;693};694695/**696 * Get value for header `field`.697 *698 * @param {String} field699 * @return {String}700 * @public701 */702703res.get = function(field){704 return this.getHeader(field);705};706707/**708 * Clear cookie `name`.709 *710 * @param {String} nameMerge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
line 711why, one step back711 * @param {Object} [options]deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 712–716why, one step back712 * @return {ServerResponse} for chaining713 * @public714 */715716res.clearCookie = function clearCookie(name, options) {Merge branch '5.0' into 5-mergectcpipbefore adoptiondde1f7d
lines 717–720why, one step back717 // Force cookie expiration by setting expires to the past718 const opts = { path: '/', ...options, expires: new Date(1)};719 // ensure maxAge is not passed720 delete opts.maxAgedeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 721–738why, one step back721722 return this.cookie(name, '', opts);723};724725/**726 * Set cookie `name` to `value`, with the given `options`.727 *728 * Options:729 *730 * - `maxAge` max-age in milliseconds, converted to `expires`731 * - `signed` sign the cookie732 * - `path` defaults to "/"733 *734 * Examples:735 *736 * // "Remember Me" for 15 minutes737 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });738 *Merge tag '4.17.1'Douglas Christopher Wilsonbefore adoption121fe99
line 739why, one step back739 * // same as abovedeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 740–743why, one step back740 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })741 *742 * @param {String} name743 * @param {String|Object} valueMerge tag '4.15.4'Douglas Christopher Wilsonbefore adoptionc319fe2
line 744why, one step back744 * @param {Object} [options]deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 745–749why, one step back745 * @return {ServerResponse} for chaining746 * @public747 */748749res.cookie = function (name, value, options) {fix: Remove `utils-merge` dependency - use spread syntax instead (#6091)Phillip Bartabefore adoption246f6f5
line 750why, one step back750 var opts = { ...options };deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 751–765why, one step back751 var secret = this.req.secret;752 var signed = opts.signed;753754 if (signed && !secret) {755 throw new Error('cookieParser("secret") required for signed cookies');756 }757758 var val = typeof value === 'object'759 ? 'j:' + JSON.stringify(value)760 : String(value);761762 if (signed) {763 val = 's:' + sign(val, secret);764 }765Merge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
lines 766–772why, one step back766 if (opts.maxAge != null) {767 var maxAge = opts.maxAge - 0768769 if (!isNaN(maxAge)) {770 opts.expires = new Date(Date.now() + maxAge)771 opts.maxAge = Math.floor(maxAge / 1000)772 }deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 773–801why, one step back773 }774775 if (opts.path == null) {776 opts.path = '/';777 }778779 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));780781 return this;782};783784/**785 * Set the location header to `url`.786 *787 * The given `url` can also be "back", which redirects788 * to the _Referrer_ or _Referer_ headers or "/".789 *790 * Examples:791 *792 * res.location('/foo/bar').;793 * res.location('http://example.com');794 * res.location('../login');795 *796 * @param {String} url797 * @return {ServerResponse} for chaining798 * @public799 */800801res.location = function location(url) {Delete `back` as a magic string (#5933)Blake Embreybefore adoptionbdd81f8
line 802why, one step back802 return this.set('Location', encodeUrl(url));deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 803–825why, one step back803};804805/**806 * Redirect to the given `url` with optional response `status`807 * defaulting to 302.808 *809 * Examples:810 *811 * res.redirect('/foo/bar');812 * res.redirect('http://example.com');813 * res.redirect(301, 'http://example.com');814 * res.redirect('../login'); // /blog/post/1 -> /blog/login815 *816 * @public817 */818819res.redirect = function redirect(url) {820 var address = url;821 var body;822 var status = 302;823824 // allow status / url825 if (arguments.length === 2) {Remove res.redirect(url, status) signatureMike Tunnicliffebefore adoption71395f5
lines 826–827why, one step back826 status = arguments[0]827 address = arguments[1]feat: add deprecation warnings for redirect arguments undefined (#6405)Sebastian Beltranbefore adoptionc5b8d55
lines 828–839why, one step back828 }829830 if (!address) {831 deprecate('Provide a url argument');832 }833834 if (typeof address !== 'string') {835 deprecate('Url must be a string');836 }837838 if (typeof status !== 'number') {839 deprecate('Status must be a number');deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 840–842why, one step back840 }841842 // Set location headerMerge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
line 843why, one step back843 address = this.location(address).get('Location');deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 844–847why, one step back844845 // Support text/{plain,html} by default846 this.format({847 text: function(){Merge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
line 848why, one step back848 body = statuses.message[status] + '. Redirecting to ' + addressdeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 849–852why, one step back849 },850851 html: function(){852 var u = escapeHtml(address);Merge tag '4.20.0' into 5.0Wes Toddbefore adoptione5feb9f
line 853why, one step back853 body = '<p>' + statuses.message[status] + '. Redirecting to ' + u + '</p>'deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 854–861why, one step back854 },855856 default: function(){857 body = '';858 }859 });860861 // RespondMerge branch '5.0' into 5-mergectcpipbefore adoptiondde1f7d
line 862why, one step back862 this.status(status);deps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
lines 863–1014why, one step back863 this.set('Content-Length', Buffer.byteLength(body));864865 if (this.req.method === 'HEAD') {866 this.end();867 } else {868 this.end(body);869 }870};871872/**873 * Add `field` to Vary. If already present in the Vary set, then874 * this call is simply ignored.875 *876 * @param {Array|String} field877 * @return {ServerResponse} for chaining878 * @public879 */880881res.vary = function(field){882 vary(this, field);883884 return this;885};886887/**888 * Render `view` with the given `options` and optional callback `fn`.889 * When a callback function is given a response will _not_ be made890 * automatically, otherwise a response of _200_ and _text/html_ is given.891 *892 * Options:893 *894 * - `cache` boolean hinting to the engine it should cache895 * - `filename` filename of the view being rendered896 *897 * @public898 */899900res.render = function render(view, options, callback) {901 var app = this.req.app;902 var done = callback;903 var opts = options || {};904 var req = this.req;905 var self = this;906907 // support callback function as second arg908 if (typeof options === 'function') {909 done = options;910 opts = {};911 }912913 // merge res.locals914 opts._locals = self.locals;915916 // default callback to respond917 done = done || function (err, str) {918 if (err) return req.next(err);919 self.send(str);920 };921922 // render923 app.render(view, opts, done);924};925926// pipe the send file stream927function sendfile(res, file, options, callback) {928 var done = false;929 var streaming;930931 // request aborted932 function onaborted() {933 if (done) return;934 done = true;935936 var err = new Error('Request aborted');937 err.code = 'ECONNABORTED';938 callback(err);939 }940941 // directory942 function ondirectory() {943 if (done) return;944 done = true;945946 var err = new Error('EISDIR, read');947 err.code = 'EISDIR';948 callback(err);949 }950951 // errors952 function onerror(err) {953 if (done) return;954 done = true;955 callback(err);956 }957958 // ended959 function onend() {960 if (done) return;961 done = true;962 callback();963 }964965 // file966 function onfile() {967 streaming = false;968 }969970 // finished971 function onfinish(err) {972 if (err && err.code === 'ECONNRESET') return onaborted();973 if (err) return onerror(err);974 if (done) return;975976 setImmediate(function () {977 if (streaming !== false && !done) {978 onaborted();979 return;980 }981982 if (done) return;983 done = true;984 callback();985 });986 }987988 // streaming989 function onstream() {990 streaming = true;991 }992993 file.on('directory', ondirectory);994 file.on('end', onend);995 file.on('error', onerror);996 file.on('file', onfile);997 file.on('stream', onstream);998 onFinished(res, onfinish);9991000 if (options.headers) {1001 // set headers on successful transfer1002 file.on('headers', function headers(res) {1003 var obj = options.headers;1004 var keys = Object.keys(obj);10051006 for (var i = 0; i < keys.length; i++) {1007 var k = keys[i];1008 res.setHeader(k, obj[k]);1009 }1010 });1011 }10121013 // pipe1014 file.pipe(res);Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
lines 1015–1017why, one step back1015}10161017/**Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 1018–1021why, one step back1018 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1019 * ability to escape characters that can trigger HTML sniffing.1020 *1021 * @param {*} valueMerge tag '4.19.0' into 5.xWes Toddbefore adoptione9f9aae
line 1022why, one step back1022 * @param {function} replacerMerge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 1023–1025why, one step back1023 * @param {number} spaces1024 * @param {boolean} escape1025 * @returns {string}Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
lines 1026–1028why, one step back1026 * @private1027 */1028Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 1029why, one step back1029function stringify (value, replacer, spaces, escape) {Merge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
lines 1030–1031why, one step back1030 // v8 checks arguments.length for optimizing simple call1031 // https://bugs.chromium.org/p/v8/issues/detail?id=4730Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 1032why, one step back1032 var json = replacer || spacesMerge tag '4.14.0'Douglas Christopher Wilsonbefore adoption1dbfee6
lines 1033–1034why, one step back1033 ? JSON.stringify(value, replacer, spaces)1034 : JSON.stringify(value);Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
line 1035why, one step back1035Merge tag '4.17.2'Douglas Christopher Wilsonbefore adoptionc7d528c
line 1036why, one step back1036 if (escape && typeof json === 'string') {Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 1037–1044why, one step back1037 json = json.replace(/[<>&]/g, function (c) {1038 switch (c.charCodeAt(0)) {1039 case 0x3c:1040 return '\\u003c'1041 case 0x3e:1042 return '\\u003e'1043 case 0x26:1044 return '\\u0026'Merge tag '4.17.1'Douglas Christopher Wilsonbefore adoption121fe99
line 1045why, one step back1045 /* istanbul ignore next: unreachable default */Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
lines 1046–1052why, one step back1046 default:1047 return c1048 }1049 })1050 }10511052 return jsondeps: array-flatten@2.0.0Douglas Christopher Wilsonbefore adoption8a387d3
line 1053why, one step back1053}