response.js
This file
Path
lib/response.js
1,025 lines · 23.6 KiB · JavaScript
Last changed by
feat: Added check to support Uint8Array in response sending (#6285)Alexander Ceruttibefore adoption55869f4
History of this fileTake 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 contentDisposition = require('content-disposition');16var createError = require('http-errors')17var encodeUrl = require('encodeurl');18var escapeHtml = require('escape-html');19var http = require('node:http');20var onFinished = require('on-finished');21var mime = require('mime-types')22var path = require('node:path');23var pathIsAbsolute = require('node:path').isAbsolute;24var statuses = require('statuses')25var sign = require('cookie-signature').sign;26var normalizeType = require('./utils').normalizeType;27var normalizeTypes = require('./utils').normalizeTypes;28var setCharset = require('./utils').setCharset;29var cookie = require('cookie');30var send = require('send');31var extname = path.extname;32var resolve = path.resolve;33var vary = require('vary');3435/**36 * Response prototype.37 * @public38 */3940var res = Object.create(http.ServerResponse.prototype)4142/**43 * Module exports.44 * @public45 */4647module.exports = res4849/**50 * Set the HTTP status code for the response.51 *52 * Expects an integer value between 100 and 999 inclusive.53 * Throws an error if the provided status code is not an integer or if it's outside the allowable range.54 *55 * @param {number} code - The HTTP status code to set.56 * @return {ServerResponse} - Returns itself for chaining methods.57 * @throws {TypeError} If `code` is not an integer.58 * @throws {RangeError} If `code` is outside the range 100 to 999.59 * @public60 */6162res.status = function status(code) {63 // Check if the status code is not an integer64 if (!Number.isInteger(code)) {65 throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`);66 }67 // Check if the status code is outside of Node's valid range68 if (code < 100 || code > 999) {69 throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`);70 }7172 this.statusCode = code;73 return this;74};7576/**77 * Set Link header field with the given `links`.78 *79 * Examples:80 *81 * res.links({82 * next: 'http://api.example.com/users?page=2',83 * last: 'http://api.example.com/users?page=5'84 * });85 *86 * @param {Object} links87 * @return {ServerResponse}88 * @public89 */9091res.links = function(links){92 var link = this.get('Link') || '';93 if (link) link += ', ';94 return this.set('Link', link + Object.keys(links).map(function(rel){95 return '<' + links[rel] + '>; rel="' + rel + '"';96 }).join(', '));97};9899/**100 * Send a response.101 *102 * Examples:103 *104 * res.send(Buffer.from('wahoo'));105 * res.send({ some: 'json' });106 * res.send('<p>some html</p>');107 *108 * @param {string|number|boolean|object|Buffer} body109 * @public110 */111112res.send = function send(body) {113 var chunk = body;114 var encoding;115 var req = this.req;116 var type;117118 // settings119 var app = this.app;120121 switch (typeof chunk) {122 // string defaulting to html123 case 'string':124 if (!this.get('Content-Type')) {125 this.type('html');126 }127 break;128 case 'boolean':129 case 'number':130 case 'object':131 if (chunk === null) {132 chunk = '';133 } else if (ArrayBuffer.isView(chunk)) {134 if (!this.get('Content-Type')) {135 this.type('bin');136 }137 } else {138 return this.json(chunk);139 }140 break;141 }142143 // write strings in utf-8144 if (typeof chunk === 'string') {145 encoding = 'utf8';146 type = this.get('Content-Type');147148 // reflect this in content-type149 if (typeof type === 'string') {150 this.set('Content-Type', setCharset(type, 'utf-8'));151 }152 }153154 // determine if ETag should be generated155 var etagFn = app.get('etag fn')156 var generateETag = !this.get('ETag') && typeof etagFn === 'function'157158 // populate Content-Length159 var len160 if (chunk !== undefined) {161 if (Buffer.isBuffer(chunk)) {162 // get length of Buffer163 len = chunk.length164 } else if (!generateETag && chunk.length < 1000) {165 // just calculate length when no ETag + small chunk166 len = Buffer.byteLength(chunk, encoding)167 } else {168 // convert chunk to Buffer and calculate169 chunk = Buffer.from(chunk, encoding)170 encoding = undefined;171 len = chunk.length172 }173174 this.set('Content-Length', len);175 }176177 // populate ETag178 var etag;179 if (generateETag && len !== undefined) {180 if ((etag = etagFn(chunk, encoding))) {181 this.set('ETag', etag);182 }183 }184185 // freshness186 if (req.fresh) this.status(304);187188 // strip irrelevant headers189 if (204 === this.statusCode || 304 === this.statusCode) {190 this.removeHeader('Content-Type');191 this.removeHeader('Content-Length');192 this.removeHeader('Transfer-Encoding');193 chunk = '';194 }195196 // alter headers for 205197 if (this.statusCode === 205) {198 this.set('Content-Length', '0')199 this.removeHeader('Transfer-Encoding')200 chunk = ''201 }202203 if (req.method === 'HEAD') {204 // skip body for HEAD205 this.end();206 } else {207 // respond208 this.end(chunk, encoding);209 }210211 return this;212};213214/**215 * Send JSON response.216 *217 * Examples:218 *219 * res.json(null);220 * res.json({ user: 'tj' });221 *222 * @param {string|number|boolean|object} obj223 * @public224 */225226res.json = function json(obj) {227 // settings228 var app = this.app;229 var escape = app.get('json escape')230 var replacer = app.get('json replacer');231 var spaces = app.get('json spaces');232 var body = stringify(obj, replacer, spaces, escape)233234 // content-type235 if (!this.get('Content-Type')) {236 this.set('Content-Type', 'application/json');237 }238239 return this.send(body);240};241242/**243 * Send JSON response with JSONP callback support.244 *245 * Examples:246 *247 * res.jsonp(null);248 * res.jsonp({ user: 'tj' });249 *250 * @param {string|number|boolean|object} obj251 * @public252 */253254res.jsonp = function jsonp(obj) {255 // settings256 var app = this.app;257 var escape = app.get('json escape')258 var replacer = app.get('json replacer');259 var spaces = app.get('json spaces');260 var body = stringify(obj, replacer, spaces, escape)261 var callback = this.req.query[app.get('jsonp callback name')];262263 // content-type264 if (!this.get('Content-Type')) {265 this.set('X-Content-Type-Options', 'nosniff');266 this.set('Content-Type', 'application/json');267 }268269 // fixup callback270 if (Array.isArray(callback)) {271 callback = callback[0];272 }273274 // jsonp275 if (typeof callback === 'string' && callback.length !== 0) {276 this.set('X-Content-Type-Options', 'nosniff');277 this.set('Content-Type', 'text/javascript');278279 // restrict callback charset280 callback = callback.replace(/[^\[\]\w$.]/g, '');281282 if (body === undefined) {283 // empty argument284 body = ''285 } else if (typeof body === 'string') {286 // replace chars not allowed in JavaScript that are in JSON287 body = body288 .replace(/\u2028/g, '\\u2028')289 .replace(/\u2029/g, '\\u2029')290 }291292 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"293 // the typeof check is just to reduce client error noise294 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';295 }296297 return this.send(body);298};299300/**301 * Send given HTTP status code.302 *303 * Sets the response status to `statusCode` and the body of the304 * response to the standard description from node's http.STATUS_CODES305 * or the statusCode number if no description.306 *307 * Examples:308 *309 * res.sendStatus(200);310 *311 * @param {number} statusCode312 * @public313 */314315res.sendStatus = function sendStatus(statusCode) {316 var body = statuses.message[statusCode] || String(statusCode)317318 this.status(statusCode);319 this.type('txt');320321 return this.send(body);322};323324/**325 * Transfer the file at the given `path`.326 *327 * Automatically sets the _Content-Type_ response header field.328 * The callback `callback(err)` is invoked when the transfer is complete329 * or when an error occurs. Be sure to check `res.headersSent`330 * if you wish to attempt responding, as the header and some data331 * may have already been transferred.332 *333 * Options:334 *335 * - `maxAge` defaulting to 0 (can be string converted by `ms`)336 * - `root` root directory for relative filenames337 * - `headers` object of headers to serve with file338 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them339 *340 * Other options are passed along to `send`.341 *342 * Examples:343 *344 * The following example illustrates how `res.sendFile()` may345 * be used as an alternative for the `static()` middleware for346 * dynamic situations. The code backing `res.sendFile()` is actually347 * the same code, so HTTP cache support etc is identical.348 *349 * app.get('/user/:uid/photos/:file', function(req, res){350 * var uid = req.params.uid351 * , file = req.params.file;352 *353 * req.user.mayViewFilesFrom(uid, function(yes){354 * if (yes) {355 * res.sendFile('/uploads/' + uid + '/' + file);356 * } else {357 * res.send(403, 'Sorry! you cant see that.');358 * }359 * });360 * });361 *362 * @public363 */364365res.sendFile = function sendFile(path, options, callback) {366 var done = callback;367 var req = this.req;368 var res = this;369 var next = req.next;370 var opts = options || {};371372 if (!path) {373 throw new TypeError('path argument is required to res.sendFile');374 }375376 if (typeof path !== 'string') {377 throw new TypeError('path must be a string to res.sendFile')378 }379380 // support function as second arg381 if (typeof options === 'function') {382 done = options;383 opts = {};384 }385386 if (!opts.root && !pathIsAbsolute(path)) {387 throw new TypeError('path must be absolute or specify root to res.sendFile');388 }389390 // create file stream391 var pathname = encodeURI(path);392 var file = send(req, pathname, opts);393394 // transfer395 sendfile(res, file, opts, function (err) {396 if (done) return done(err);397 if (err && err.code === 'EISDIR') return next();398399 // next() all but write errors400 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {401 next(err);402 }403 });404};405406/**407 * Transfer the file at the given `path` as an attachment.408 *409 * Optionally providing an alternate attachment `filename`,410 * and optional callback `callback(err)`. The callback is invoked411 * when the data transfer is complete, or when an error has412 * occurred. Be sure to check `res.headersSent` if you plan to respond.413 *414 * Optionally providing an `options` object to use with `res.sendFile()`.415 * This function will set the `Content-Disposition` header, overriding416 * any `Content-Disposition` header passed as header options in order417 * to set the attachment and filename.418 *419 * This method uses `res.sendFile()`.420 *421 * @public422 */423424res.download = function download (path, filename, options, callback) {425 var done = callback;426 var name = filename;427 var opts = options || null428429 // support function as second or third arg430 if (typeof filename === 'function') {431 done = filename;432 name = null;433 opts = null434 } else if (typeof options === 'function') {435 done = options436 opts = null437 }438439 // support optional filename, where options may be in it's place440 if (typeof filename === 'object' &&441 (typeof options === 'function' || options === undefined)) {442 name = null443 opts = filename444 }445446 // set Content-Disposition when file is sent447 var headers = {448 'Content-Disposition': contentDisposition(name || path)449 };450451 // merge user-provided headers452 if (opts && opts.headers) {453 var keys = Object.keys(opts.headers)454 for (var i = 0; i < keys.length; i++) {455 var key = keys[i]456 if (key.toLowerCase() !== 'content-disposition') {457 headers[key] = opts.headers[key]458 }459 }460 }461462 // merge user-provided options463 opts = Object.create(opts)464 opts.headers = headers465466 // Resolve the full path for sendFile467 var fullPath = !opts.root468 ? resolve(path)469 : path470471 // send file472 return this.sendFile(fullPath, opts, done)473};474475/**476 * Set _Content-Type_ response header with `type` through `mime.contentType()`477 * when it does not contain "/", or set the Content-Type to `type` otherwise.478 * When no mapping is found though `mime.contentType()`, the type is set to479 * "application/octet-stream".480 *481 * Examples:482 *483 * res.type('.html');484 * res.type('html');485 * res.type('json');486 * res.type('application/json');487 * res.type('png');488 *489 * @param {String} type490 * @return {ServerResponse} for chaining491 * @public492 */493494res.contentType =495res.type = function contentType(type) {496 var ct = type.indexOf('/') === -1497 ? (mime.contentType(type) || 'application/octet-stream')498 : type;499500 return this.set('Content-Type', ct);501};502503/**504 * Respond to the Acceptable formats using an `obj`505 * of mime-type callbacks.506 *507 * This method uses `req.accepted`, an array of508 * acceptable types ordered by their quality values.509 * When "Accept" is not present the _first_ callback510 * is invoked, otherwise the first match is used. When511 * no match is performed the server responds with512 * 406 "Not Acceptable".513 *514 * Content-Type is set for you, however if you choose515 * you may alter this within the callback using `res.type()`516 * or `res.set('Content-Type', ...)`.517 *518 * res.format({519 * 'text/plain': function(){520 * res.send('hey');521 * },522 *523 * 'text/html': function(){524 * res.send('<p>hey</p>');525 * },526 *527 * 'application/json': function () {528 * res.send({ message: 'hey' });529 * }530 * });531 *532 * In addition to canonicalized MIME types you may533 * also use extnames mapped to these types:534 *535 * res.format({536 * text: function(){537 * res.send('hey');538 * },539 *540 * html: function(){541 * res.send('<p>hey</p>');542 * },543 *544 * json: function(){545 * res.send({ message: 'hey' });546 * }547 * });548 *549 * By default Express passes an `Error`550 * with a `.status` of 406 to `next(err)`551 * if a match is not made. If you provide552 * a `.default` callback it will be invoked553 * instead.554 *555 * @param {Object} obj556 * @return {ServerResponse} for chaining557 * @public558 */559560res.format = function(obj){561 var req = this.req;562 var next = req.next;563564 var keys = Object.keys(obj)565 .filter(function (v) { return v !== 'default' })566567 var key = keys.length > 0568 ? req.accepts(keys)569 : false;570571 this.vary("Accept");572573 if (key) {574 this.set('Content-Type', normalizeType(key).value);575 obj[key](req, this, next);576 } else if (obj.default) {577 obj.default(req, this, next)578 } else {579 next(createError(406, {580 types: normalizeTypes(keys).map(function (o) { return o.value })581 }))582 }583584 return this;585};586587/**588 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.589 *590 * @param {String} filename591 * @return {ServerResponse}592 * @public593 */594595res.attachment = function attachment(filename) {596 if (filename) {597 this.type(extname(filename));598 }599600 this.set('Content-Disposition', contentDisposition(filename));601602 return this;603};604605/**606 * Append additional header `field` with value `val`.607 *608 * Example:609 *610 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);611 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');612 * res.append('Warning', '199 Miscellaneous warning');613 *614 * @param {String} field615 * @param {String|Array} val616 * @return {ServerResponse} for chaining617 * @public618 */619620res.append = function append(field, val) {621 var prev = this.get(field);622 var value = val;623624 if (prev) {625 // concat the new and prev vals626 value = Array.isArray(prev) ? prev.concat(val)627 : Array.isArray(val) ? [prev].concat(val)628 : [prev, val]629 }630631 return this.set(field, value);632};633634/**635 * Set header `field` to `val`, or pass636 * an object of header fields.637 *638 * Examples:639 *640 * res.set('Foo', ['bar', 'baz']);641 * res.set('Accept', 'application/json');642 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });643 *644 * Aliased as `res.header()`.645 *646 * When the set header is "Content-Type", the type is expanded to include647 * the charset if not present using `mime.contentType()`.648 *649 * @param {String|Object} field650 * @param {String|Array} val651 * @return {ServerResponse} for chaining652 * @public653 */654655res.set =656res.header = function header(field, val) {657 if (arguments.length === 2) {658 var value = Array.isArray(val)659 ? val.map(String)660 : String(val);661662 // add charset to content-type663 if (field.toLowerCase() === 'content-type') {664 if (Array.isArray(value)) {665 throw new TypeError('Content-Type cannot be set to an Array');666 }667 value = mime.contentType(value)668 }669670 this.setHeader(field, value);671 } else {672 for (var key in field) {673 this.set(key, field[key]);674 }675 }676 return this;677};678679/**680 * Get value for header `field`.681 *682 * @param {String} field683 * @return {String}684 * @public685 */686687res.get = function(field){688 return this.getHeader(field);689};690691/**692 * Clear cookie `name`.693 *694 * @param {String} name695 * @param {Object} [options]696 * @return {ServerResponse} for chaining697 * @public698 */699700res.clearCookie = function clearCookie(name, options) {701 // Force cookie expiration by setting expires to the past702 const opts = { path: '/', ...options, expires: new Date(1)};703 // ensure maxAge is not passed704 delete opts.maxAge705706 return this.cookie(name, '', opts);707};708709/**710 * Set cookie `name` to `value`, with the given `options`.711 *712 * Options:713 *714 * - `maxAge` max-age in milliseconds, converted to `expires`715 * - `signed` sign the cookie716 * - `path` defaults to "/"717 *718 * Examples:719 *720 * // "Remember Me" for 15 minutes721 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });722 *723 * // same as above724 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })725 *726 * @param {String} name727 * @param {String|Object} value728 * @param {Object} [options]729 * @return {ServerResponse} for chaining730 * @public731 */732733res.cookie = function (name, value, options) {734 var opts = { ...options };735 var secret = this.req.secret;736 var signed = opts.signed;737738 if (signed && !secret) {739 throw new Error('cookieParser("secret") required for signed cookies');740 }741742 var val = typeof value === 'object'743 ? 'j:' + JSON.stringify(value)744 : String(value);745746 if (signed) {747 val = 's:' + sign(val, secret);748 }749750 if (opts.maxAge != null) {751 var maxAge = opts.maxAge - 0752753 if (!isNaN(maxAge)) {754 opts.expires = new Date(Date.now() + maxAge)755 opts.maxAge = Math.floor(maxAge / 1000)756 }757 }758759 if (opts.path == null) {760 opts.path = '/';761 }762763 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));764765 return this;766};767768/**769 * Set the location header to `url`.770 *771 * The given `url` can also be "back", which redirects772 * to the _Referrer_ or _Referer_ headers or "/".773 *774 * Examples:775 *776 * res.location('/foo/bar').;777 * res.location('http://example.com');778 * res.location('../login');779 *780 * @param {String} url781 * @return {ServerResponse} for chaining782 * @public783 */784785res.location = function location(url) {786 return this.set('Location', encodeUrl(url));787};788789/**790 * Redirect to the given `url` with optional response `status`791 * defaulting to 302.792 *793 * Examples:794 *795 * res.redirect('/foo/bar');796 * res.redirect('http://example.com');797 * res.redirect(301, 'http://example.com');798 * res.redirect('../login'); // /blog/post/1 -> /blog/login799 *800 * @public801 */802803res.redirect = function redirect(url) {804 var address = url;805 var body;806 var status = 302;807808 // allow status / url809 if (arguments.length === 2) {810 status = arguments[0]811 address = arguments[1]812 }813814 // Set location header815 address = this.location(address).get('Location');816817 // Support text/{plain,html} by default818 this.format({819 text: function(){820 body = statuses.message[status] + '. Redirecting to ' + address821 },822823 html: function(){824 var u = escapeHtml(address);825 body = '<p>' + statuses.message[status] + '. Redirecting to ' + u + '</p>'826 },827828 default: function(){829 body = '';830 }831 });832833 // Respond834 this.status(status);835 this.set('Content-Length', Buffer.byteLength(body));836837 if (this.req.method === 'HEAD') {838 this.end();839 } else {840 this.end(body);841 }842};843844/**845 * Add `field` to Vary. If already present in the Vary set, then846 * this call is simply ignored.847 *848 * @param {Array|String} field849 * @return {ServerResponse} for chaining850 * @public851 */852853res.vary = function(field){854 vary(this, field);855856 return this;857};858859/**860 * Render `view` with the given `options` and optional callback `fn`.861 * When a callback function is given a response will _not_ be made862 * automatically, otherwise a response of _200_ and _text/html_ is given.863 *864 * Options:865 *866 * - `cache` boolean hinting to the engine it should cache867 * - `filename` filename of the view being rendered868 *869 * @public870 */871872res.render = function render(view, options, callback) {873 var app = this.req.app;874 var done = callback;875 var opts = options || {};876 var req = this.req;877 var self = this;878879 // support callback function as second arg880 if (typeof options === 'function') {881 done = options;882 opts = {};883 }884885 // merge res.locals886 opts._locals = self.locals;887888 // default callback to respond889 done = done || function (err, str) {890 if (err) return req.next(err);891 self.send(str);892 };893894 // render895 app.render(view, opts, done);896};897898// pipe the send file stream899function sendfile(res, file, options, callback) {900 var done = false;901 var streaming;902903 // request aborted904 function onaborted() {905 if (done) return;906 done = true;907908 var err = new Error('Request aborted');909 err.code = 'ECONNABORTED';910 callback(err);911 }912913 // directory914 function ondirectory() {915 if (done) return;916 done = true;917918 var err = new Error('EISDIR, read');919 err.code = 'EISDIR';920 callback(err);921 }922923 // errors924 function onerror(err) {925 if (done) return;926 done = true;927 callback(err);928 }929930 // ended931 function onend() {932 if (done) return;933 done = true;934 callback();935 }936937 // file938 function onfile() {939 streaming = false;940 }941942 // finished943 function onfinish(err) {944 if (err && err.code === 'ECONNRESET') return onaborted();945 if (err) return onerror(err);946 if (done) return;947948 setImmediate(function () {949 if (streaming !== false && !done) {950 onaborted();951 return;952 }953954 if (done) return;955 done = true;956 callback();957 });958 }959960 // streaming961 function onstream() {962 streaming = true;963 }964965 file.on('directory', ondirectory);966 file.on('end', onend);967 file.on('error', onerror);968 file.on('file', onfile);969 file.on('stream', onstream);970 onFinished(res, onfinish);971972 if (options.headers) {973 // set headers on successful transfer974 file.on('headers', function headers(res) {975 var obj = options.headers;976 var keys = Object.keys(obj);977978 for (var i = 0; i < keys.length; i++) {979 var k = keys[i];980 res.setHeader(k, obj[k]);981 }982 });983 }984985 // pipe986 file.pipe(res);987}988989/**990 * Stringify JSON, like JSON.stringify, but v8 optimized, with the991 * ability to escape characters that can trigger HTML sniffing.992 *993 * @param {*} value994 * @param {function} replacer995 * @param {number} spaces996 * @param {boolean} escape997 * @returns {string}998 * @private999 */10001001function stringify (value, replacer, spaces, escape) {1002 // v8 checks arguments.length for optimizing simple call1003 // https://bugs.chromium.org/p/v8/issues/detail?id=47301004 var json = replacer || spaces1005 ? JSON.stringify(value, replacer, spaces)1006 : JSON.stringify(value);10071008 if (escape && typeof json === 'string') {1009 json = json.replace(/[<>&]/g, function (c) {1010 switch (c.charCodeAt(0)) {1011 case 0x3c:1012 return '\\u003c'1013 case 0x3e:1014 return '\\u003e'1015 case 0x26:1016 return '\\u0026'1017 /* istanbul ignore next: unreachable default */1018 default:1019 return c1020 }1021 })1022 }10231024 return json1025}