Skip to content
Myr

response.js

This file

Path

lib/response.js

1,027 lines · 23.6 KiB · JavaScript

Last changed by

fix(buffer): use node:buffer instead of safe-buffer (#6071)Bhavya Dhimanbefore adoptionc70197a

History of this file

Take it

1/*!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 Buffer = require('node:buffer').Buffer16var contentDisposition = require('content-disposition');17var createError = require('http-errors')18var encodeUrl = require('encodeurl');19var escapeHtml = require('escape-html');20var http = require('http');21var onFinished = require('on-finished');22var mime = require('mime-types')23var path = require('path');24var pathIsAbsolute = require('path').isAbsolute;25var statuses = require('statuses')26var merge = require('utils-merge');27var sign = require('cookie-signature').sign;28var normalizeType = require('./utils').normalizeType;29var normalizeTypes = require('./utils').normalizeTypes;30var setCharset = require('./utils').setCharset;31var cookie = require('cookie');32var send = require('send');33var extname = path.extname;34var resolve = path.resolve;35var vary = require('vary');3637/**38 * Response prototype.39 * @public40 */4142var res = Object.create(http.ServerResponse.prototype)4344/**45 * Module exports.46 * @public47 */4849module.exports = res5051/**52 * Set the HTTP status code for the response.53 *54 * 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.61 * @public62 */6364res.status = function status(code) {65  // 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.`);68  }69  // 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  }7374  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',85 *      last: 'http://api.example.com/users?page=5'86 *    });87 *88 * @param {Object} links89 * @return {ServerResponse}90 * @public91 */9293res.links = function(links){94  var link = this.get('Link') || '';95  if (link) link += ', ';96  return this.set('Link', link + Object.keys(links).map(function(rel){97    return '<' + links[rel] + '>; rel="' + rel + '"';98  }).join(', '));99};100101/**102 * Send a response.103 *104 * Examples:105 *106 *     res.send(Buffer.from('wahoo'));107 *     res.send({ some: 'json' });108 *     res.send('<p>some html</p>');109 *110 * @param {string|number|boolean|object|Buffer} body111 * @public112 */113114res.send = function send(body) {115  var chunk = body;116  var encoding;117  var req = this.req;118  var type;119120  // settings121  var app = this.app;122123  switch (typeof chunk) {124    // string defaulting to html125    case 'string':126      if (!this.get('Content-Type')) {127        this.type('html');128      }129      break;130    case 'boolean':131    case 'number':132    case 'object':133      if (chunk === null) {134        chunk = '';135      } else if (Buffer.isBuffer(chunk)) {136        if (!this.get('Content-Type')) {137          this.type('bin');138        }139      } else {140        return this.json(chunk);141      }142      break;143  }144145  // write strings in utf-8146  if (typeof chunk === 'string') {147    encoding = 'utf8';148    type = this.get('Content-Type');149150    // reflect this in content-type151    if (typeof type === 'string') {152      this.set('Content-Type', setCharset(type, 'utf-8'));153    }154  }155156  // determine if ETag should be generated157  var etagFn = app.get('etag fn')158  var generateETag = !this.get('ETag') && typeof etagFn === 'function'159160  // populate Content-Length161  var len162  if (chunk !== undefined) {163    if (Buffer.isBuffer(chunk)) {164      // get length of Buffer165      len = chunk.length166    } else if (!generateETag && chunk.length < 1000) {167      // just calculate length when no ETag + small chunk168      len = Buffer.byteLength(chunk, encoding)169    } else {170      // convert chunk to Buffer and calculate171      chunk = Buffer.from(chunk, encoding)172      encoding = undefined;173      len = chunk.length174    }175176    this.set('Content-Length', len);177  }178179  // populate ETag180  var etag;181  if (generateETag && len !== undefined) {182    if ((etag = etagFn(chunk, encoding))) {183      this.set('ETag', etag);184    }185  }186187  // freshness188  if (req.fresh) this.status(304);189190  // strip irrelevant headers191  if (204 === this.statusCode || 304 === this.statusCode) {192    this.removeHeader('Content-Type');193    this.removeHeader('Content-Length');194    this.removeHeader('Transfer-Encoding');195    chunk = '';196  }197198  // alter headers for 205199  if (this.statusCode === 205) {200    this.set('Content-Length', '0')201    this.removeHeader('Transfer-Encoding')202    chunk = ''203  }204205  if (req.method === 'HEAD') {206    // skip body for HEAD207    this.end();208  } else {209    // respond210    this.end(chunk, encoding);211  }212213  return this;214};215216/**217 * Send JSON response.218 *219 * Examples:220 *221 *     res.json(null);222 *     res.json({ user: 'tj' });223 *224 * @param {string|number|boolean|object} obj225 * @public226 */227228res.json = function json(obj) {229  // settings230  var app = this.app;231  var escape = app.get('json escape')232  var replacer = app.get('json replacer');233  var spaces = app.get('json spaces');234  var body = stringify(obj, replacer, spaces, escape)235236  // content-type237  if (!this.get('Content-Type')) {238    this.set('Content-Type', 'application/json');239  }240241  return this.send(body);242};243244/**245 * Send JSON response with JSONP callback support.246 *247 * Examples:248 *249 *     res.jsonp(null);250 *     res.jsonp({ user: 'tj' });251 *252 * @param {string|number|boolean|object} obj253 * @public254 */255256res.jsonp = function jsonp(obj) {257  // settings258  var app = this.app;259  var escape = app.get('json escape')260  var replacer = app.get('json replacer');261  var spaces = app.get('json spaces');262  var body = stringify(obj, replacer, spaces, escape)263  var callback = this.req.query[app.get('jsonp callback name')];264265  // content-type266  if (!this.get('Content-Type')) {267    this.set('X-Content-Type-Options', 'nosniff');268    this.set('Content-Type', 'application/json');269  }270271  // fixup callback272  if (Array.isArray(callback)) {273    callback = callback[0];274  }275276  // jsonp277  if (typeof callback === 'string' && callback.length !== 0) {278    this.set('X-Content-Type-Options', 'nosniff');279    this.set('Content-Type', 'text/javascript');280281    // restrict callback charset282    callback = callback.replace(/[^\[\]\w$.]/g, '');283284    if (body === undefined) {285      // empty argument286      body = ''287    } else if (typeof body === 'string') {288      // replace chars not allowed in JavaScript that are in JSON289      body = body290        .replace(/\u2028/g, '\\u2028')291        .replace(/\u2029/g, '\\u2029')292    }293294    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"295    // the typeof check is just to reduce client error noise296    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';297  }298299  return this.send(body);300};301302/**303 * Send given HTTP status code.304 *305 * Sets the response status to `statusCode` and the body of the306 * response to the standard description from node's http.STATUS_CODES307 * or the statusCode number if no description.308 *309 * Examples:310 *311 *     res.sendStatus(200);312 *313 * @param {number} statusCode314 * @public315 */316317res.sendStatus = function sendStatus(statusCode) {318  var body = statuses.message[statusCode] || String(statusCode)319320  this.status(statusCode);321  this.type('txt');322323  return this.send(body);324};325326/**327 * Transfer the file at the given `path`.328 *329 * Automatically sets the _Content-Type_ response header field.330 * The callback `callback(err)` is invoked when the transfer is complete331 * or when an error occurs. Be sure to check `res.headersSent`332 * if you wish to attempt responding, as the header and some data333 * may have already been transferred.334 *335 * Options:336 *337 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)338 *   - `root`     root directory for relative filenames339 *   - `headers`  object of headers to serve with file340 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them341 *342 * Other options are passed along to `send`.343 *344 * Examples:345 *346 *  The following example illustrates how `res.sendFile()` may347 *  be used as an alternative for the `static()` middleware for348 *  dynamic situations. The code backing `res.sendFile()` is actually349 *  the same code, so HTTP cache support etc is identical.350 *351 *     app.get('/user/:uid/photos/:file', function(req, res){352 *       var uid = req.params.uid353 *         , file = req.params.file;354 *355 *       req.user.mayViewFilesFrom(uid, function(yes){356 *         if (yes) {357 *           res.sendFile('/uploads/' + uid + '/' + file);358 *         } else {359 *           res.send(403, 'Sorry! you cant see that.');360 *         }361 *       });362 *     });363 *364 * @public365 */366367res.sendFile = function sendFile(path, options, callback) {368  var done = callback;369  var req = this.req;370  var res = this;371  var next = req.next;372  var opts = options || {};373374  if (!path) {375    throw new TypeError('path argument is required to res.sendFile');376  }377378  if (typeof path !== 'string') {379    throw new TypeError('path must be a string to res.sendFile')380  }381382  // support function as second arg383  if (typeof options === 'function') {384    done = options;385    opts = {};386  }387388  if (!opts.root && !pathIsAbsolute(path)) {389    throw new TypeError('path must be absolute or specify root to res.sendFile');390  }391392  // create file stream393  var pathname = encodeURI(path);394  var file = send(req, pathname, opts);395396  // transfer397  sendfile(res, file, opts, function (err) {398    if (done) return done(err);399    if (err && err.code === 'EISDIR') return next();400401    // next() all but write errors402    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {403      next(err);404    }405  });406};407408/**409 * Transfer the file at the given `path` as an attachment.410 *411 * Optionally providing an alternate attachment `filename`,412 * and optional callback `callback(err)`. The callback is invoked413 * when the data transfer is complete, or when an error has414 * occurred. Be sure to check `res.headersSent` if you plan to respond.415 *416 * Optionally providing an `options` object to use with `res.sendFile()`.417 * This function will set the `Content-Disposition` header, overriding418 * any `Content-Disposition` header passed as header options in order419 * to set the attachment and filename.420 *421 * This method uses `res.sendFile()`.422 *423 * @public424 */425426res.download = function download (path, filename, options, callback) {427  var done = callback;428  var name = filename;429  var opts = options || null430431  // support function as second or third arg432  if (typeof filename === 'function') {433    done = filename;434    name = null;435    opts = null436  } else if (typeof options === 'function') {437    done = options438    opts = null439  }440441  // support optional filename, where options may be in it's place442  if (typeof filename === 'object' &&443    (typeof options === 'function' || options === undefined)) {444    name = null445    opts = filename446  }447448  // set Content-Disposition when file is sent449  var headers = {450    'Content-Disposition': contentDisposition(name || path)451  };452453  // merge user-provided headers454  if (opts && opts.headers) {455    var keys = Object.keys(opts.headers)456    for (var i = 0; i < keys.length; i++) {457      var key = keys[i]458      if (key.toLowerCase() !== 'content-disposition') {459        headers[key] = opts.headers[key]460      }461    }462  }463464  // merge user-provided options465  opts = Object.create(opts)466  opts.headers = headers467468  // Resolve the full path for sendFile469  var fullPath = !opts.root470    ? resolve(path)471    : path472473  // send file474  return this.sendFile(fullPath, opts, done)475};476477/**478 * Set _Content-Type_ response header with `type` through `mime.contentType()`479 * when it does not contain "/", or set the Content-Type to `type` otherwise.480 * When no mapping is found though `mime.contentType()`, the type is set to481 * "application/octet-stream".482 *483 * Examples:484 *485 *     res.type('.html');486 *     res.type('html');487 *     res.type('json');488 *     res.type('application/json');489 *     res.type('png');490 *491 * @param {String} type492 * @return {ServerResponse} for chaining493 * @public494 */495496res.contentType =497res.type = function contentType(type) {498  var ct = type.indexOf('/') === -1499    ? (mime.contentType(type) || 'application/octet-stream')500    : type;501502  return this.set('Content-Type', ct);503};504505/**506 * Respond to the Acceptable formats using an `obj`507 * of mime-type callbacks.508 *509 * This method uses `req.accepted`, an array of510 * acceptable types ordered by their quality values.511 * When "Accept" is not present the _first_ callback512 * is invoked, otherwise the first match is used. When513 * no match is performed the server responds with514 * 406 "Not Acceptable".515 *516 * Content-Type is set for you, however if you choose517 * you may alter this within the callback using `res.type()`518 * or `res.set('Content-Type', ...)`.519 *520 *    res.format({521 *      'text/plain': function(){522 *        res.send('hey');523 *      },524 *525 *      'text/html': function(){526 *        res.send('<p>hey</p>');527 *      },528 *529 *      'application/json': function () {530 *        res.send({ message: 'hey' });531 *      }532 *    });533 *534 * In addition to canonicalized MIME types you may535 * also use extnames mapped to these types:536 *537 *    res.format({538 *      text: function(){539 *        res.send('hey');540 *      },541 *542 *      html: function(){543 *        res.send('<p>hey</p>');544 *      },545 *546 *      json: function(){547 *        res.send({ message: 'hey' });548 *      }549 *    });550 *551 * By default Express passes an `Error`552 * with a `.status` of 406 to `next(err)`553 * if a match is not made. If you provide554 * a `.default` callback it will be invoked555 * instead.556 *557 * @param {Object} obj558 * @return {ServerResponse} for chaining559 * @public560 */561562res.format = function(obj){563  var req = this.req;564  var next = req.next;565566  var keys = Object.keys(obj)567    .filter(function (v) { return v !== 'default' })568569  var key = keys.length > 0570    ? req.accepts(keys)571    : false;572573  this.vary("Accept");574575  if (key) {576    this.set('Content-Type', normalizeType(key).value);577    obj[key](req, this, next);578  } else if (obj.default) {579    obj.default(req, this, next)580  } else {581    next(createError(406, {582      types: normalizeTypes(keys).map(function (o) { return o.value })583    }))584  }585586  return this;587};588589/**590 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.591 *592 * @param {String} filename593 * @return {ServerResponse}594 * @public595 */596597res.attachment = function attachment(filename) {598  if (filename) {599    this.type(extname(filename));600  }601602  this.set('Content-Disposition', contentDisposition(filename));603604  return this;605};606607/**608 * Append additional header `field` with value `val`.609 *610 * Example:611 *612 *    res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);613 *    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');614 *    res.append('Warning', '199 Miscellaneous warning');615 *616 * @param {String} field617 * @param {String|Array} val618 * @return {ServerResponse} for chaining619 * @public620 */621622res.append = function append(field, val) {623  var prev = this.get(field);624  var value = val;625626  if (prev) {627    // concat the new and prev vals628    value = Array.isArray(prev) ? prev.concat(val)629      : Array.isArray(val) ? [prev].concat(val)630        : [prev, val]631  }632633  return this.set(field, value);634};635636/**637 * Set header `field` to `val`, or pass638 * an object of header fields.639 *640 * Examples:641 *642 *    res.set('Foo', ['bar', 'baz']);643 *    res.set('Accept', 'application/json');644 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });645 *646 * Aliased as `res.header()`.647 *648 * When the set header is "Content-Type", the type is expanded to include649 * the charset if not present using `mime.contentType()`.650 *651 * @param {String|Object} field652 * @param {String|Array} val653 * @return {ServerResponse} for chaining654 * @public655 */656657res.set =658res.header = function header(field, val) {659  if (arguments.length === 2) {660    var value = Array.isArray(val)661      ? val.map(String)662      : String(val);663664    // add charset to content-type665    if (field.toLowerCase() === 'content-type') {666      if (Array.isArray(value)) {667        throw new TypeError('Content-Type cannot be set to an Array');668      }669      value = mime.contentType(value)670    }671672    this.setHeader(field, value);673  } else {674    for (var key in field) {675      this.set(key, field[key]);676    }677  }678  return this;679};680681/**682 * Get value for header `field`.683 *684 * @param {String} field685 * @return {String}686 * @public687 */688689res.get = function(field){690  return this.getHeader(field);691};692693/**694 * Clear cookie `name`.695 *696 * @param {String} name697 * @param {Object} [options]698 * @return {ServerResponse} for chaining699 * @public700 */701702res.clearCookie = function clearCookie(name, options) {703  // Force cookie expiration by setting expires to the past704  const opts = { path: '/', ...options, expires: new Date(1)};705  // ensure maxAge is not passed706  delete opts.maxAge707708  return this.cookie(name, '', opts);709};710711/**712 * Set cookie `name` to `value`, with the given `options`.713 *714 * Options:715 *716 *    - `maxAge`   max-age in milliseconds, converted to `expires`717 *    - `signed`   sign the cookie718 *    - `path`     defaults to "/"719 *720 * Examples:721 *722 *    // "Remember Me" for 15 minutes723 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });724 *725 *    // same as above726 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })727 *728 * @param {String} name729 * @param {String|Object} value730 * @param {Object} [options]731 * @return {ServerResponse} for chaining732 * @public733 */734735res.cookie = function (name, value, options) {736  var opts = merge({}, options);737  var secret = this.req.secret;738  var signed = opts.signed;739740  if (signed && !secret) {741    throw new Error('cookieParser("secret") required for signed cookies');742  }743744  var val = typeof value === 'object'745    ? 'j:' + JSON.stringify(value)746    : String(value);747748  if (signed) {749    val = 's:' + sign(val, secret);750  }751752  if (opts.maxAge != null) {753    var maxAge = opts.maxAge - 0754755    if (!isNaN(maxAge)) {756      opts.expires = new Date(Date.now() + maxAge)757      opts.maxAge = Math.floor(maxAge / 1000)758    }759  }760761  if (opts.path == null) {762    opts.path = '/';763  }764765  this.append('Set-Cookie', cookie.serialize(name, String(val), opts));766767  return this;768};769770/**771 * Set the location header to `url`.772 *773 * The given `url` can also be "back", which redirects774 * to the _Referrer_ or _Referer_ headers or "/".775 *776 * Examples:777 *778 *    res.location('/foo/bar').;779 *    res.location('http://example.com');780 *    res.location('../login');781 *782 * @param {String} url783 * @return {ServerResponse} for chaining784 * @public785 */786787res.location = function location(url) {788  return this.set('Location', encodeUrl(url));789};790791/**792 * Redirect to the given `url` with optional response `status`793 * defaulting to 302.794 *795 * Examples:796 *797 *    res.redirect('/foo/bar');798 *    res.redirect('http://example.com');799 *    res.redirect(301, 'http://example.com');800 *    res.redirect('../login'); // /blog/post/1 -> /blog/login801 *802 * @public803 */804805res.redirect = function redirect(url) {806  var address = url;807  var body;808  var status = 302;809810  // allow status / url811  if (arguments.length === 2) {812    status = arguments[0]813    address = arguments[1]814  }815816  // Set location header817  address = this.location(address).get('Location');818819  // Support text/{plain,html} by default820  this.format({821    text: function(){822      body = statuses.message[status] + '. Redirecting to ' + address823    },824825    html: function(){826      var u = escapeHtml(address);827      body = '<p>' + statuses.message[status] + '. Redirecting to ' + u + '</p>'828    },829830    default: function(){831      body = '';832    }833  });834835  // Respond836  this.status(status);837  this.set('Content-Length', Buffer.byteLength(body));838839  if (this.req.method === 'HEAD') {840    this.end();841  } else {842    this.end(body);843  }844};845846/**847 * Add `field` to Vary. If already present in the Vary set, then848 * this call is simply ignored.849 *850 * @param {Array|String} field851 * @return {ServerResponse} for chaining852 * @public853 */854855res.vary = function(field){856  vary(this, field);857858  return this;859};860861/**862 * Render `view` with the given `options` and optional callback `fn`.863 * When a callback function is given a response will _not_ be made864 * automatically, otherwise a response of _200_ and _text/html_ is given.865 *866 * Options:867 *868 *  - `cache`     boolean hinting to the engine it should cache869 *  - `filename`  filename of the view being rendered870 *871 * @public872 */873874res.render = function render(view, options, callback) {875  var app = this.req.app;876  var done = callback;877  var opts = options || {};878  var req = this.req;879  var self = this;880881  // support callback function as second arg882  if (typeof options === 'function') {883    done = options;884    opts = {};885  }886887  // merge res.locals888  opts._locals = self.locals;889890  // default callback to respond891  done = done || function (err, str) {892    if (err) return req.next(err);893    self.send(str);894  };895896  // render897  app.render(view, opts, done);898};899900// pipe the send file stream901function sendfile(res, file, options, callback) {902  var done = false;903  var streaming;904905  // request aborted906  function onaborted() {907    if (done) return;908    done = true;909910    var err = new Error('Request aborted');911    err.code = 'ECONNABORTED';912    callback(err);913  }914915  // directory916  function ondirectory() {917    if (done) return;918    done = true;919920    var err = new Error('EISDIR, read');921    err.code = 'EISDIR';922    callback(err);923  }924925  // errors926  function onerror(err) {927    if (done) return;928    done = true;929    callback(err);930  }931932  // ended933  function onend() {934    if (done) return;935    done = true;936    callback();937  }938939  // file940  function onfile() {941    streaming = false;942  }943944  // finished945  function onfinish(err) {946    if (err && err.code === 'ECONNRESET') return onaborted();947    if (err) return onerror(err);948    if (done) return;949950    setImmediate(function () {951      if (streaming !== false && !done) {952        onaborted();953        return;954      }955956      if (done) return;957      done = true;958      callback();959    });960  }961962  // streaming963  function onstream() {964    streaming = true;965  }966967  file.on('directory', ondirectory);968  file.on('end', onend);969  file.on('error', onerror);970  file.on('file', onfile);971  file.on('stream', onstream);972  onFinished(res, onfinish);973974  if (options.headers) {975    // set headers on successful transfer976    file.on('headers', function headers(res) {977      var obj = options.headers;978      var keys = Object.keys(obj);979980      for (var i = 0; i < keys.length; i++) {981        var k = keys[i];982        res.setHeader(k, obj[k]);983      }984    });985  }986987  // pipe988  file.pipe(res);989}990991/**992 * Stringify JSON, like JSON.stringify, but v8 optimized, with the993 * ability to escape characters that can trigger HTML sniffing.994 *995 * @param {*} value996 * @param {function} replacer997 * @param {number} spaces998 * @param {boolean} escape999 * @returns {string}1000 * @private1001 */10021003function stringify (value, replacer, spaces, escape) {1004  // v8 checks arguments.length for optimizing simple call1005  // https://bugs.chromium.org/p/v8/issues/detail?id=47301006  var json = replacer || spaces1007    ? JSON.stringify(value, replacer, spaces)1008    : JSON.stringify(value);10091010  if (escape && typeof json === 'string') {1011    json = json.replace(/[<>&]/g, function (c) {1012      switch (c.charCodeAt(0)) {1013        case 0x3c:1014          return '\\u003c'1015        case 0x3e:1016          return '\\u003e'1017        case 0x26:1018          return '\\u0026'1019        /* istanbul ignore next: unreachable default */1020        default:1021          return c1022      }1023    })1024  }10251026  return json1027}