response.js
This file
Path
lib/response.js
1,039 lines · 24.0 KiB · JavaScript
Last changed by
feat: Extend res.links() to allow adding multiple links with the same rel (closes #2729) (#4885)Andrea Polverinobefore adoptioncaa4f68
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 * pages: [85 * 'http://api.example.com/users?page=1',86 * 'http://api.example.com/users?page=2'87 * ]88 * });89 *90 * @param {Object} links91 * @return {ServerResponse}92 * @public93 */9495res.links = function(links) {96 var link = this.get('Link') || '';97 if (link) link += ', ';98 return this.set('Link', link + Object.keys(links).map(function(rel) {99 // Allow multiple links if links[rel] is an array100 if (Array.isArray(links[rel])) {101 return links[rel].map(function (singleLink) {102 return `<${singleLink}>; rel="${rel}"`;103 }).join(', ');104 } else {105 return `<${links[rel]}>; rel="${rel}"`;106 }107 }).join(', '));108};109110/**111 * Send a response.112 *113 * Examples:114 *115 * res.send(Buffer.from('wahoo'));116 * res.send({ some: 'json' });117 * res.send('<p>some html</p>');118 *119 * @param {string|number|boolean|object|Buffer} body120 * @public121 */122123res.send = function send(body) {124 var chunk = body;125 var encoding;126 var req = this.req;127 var type;128129 // settings130 var app = this.app;131132 switch (typeof chunk) {133 // string defaulting to html134 case 'string':135 if (!this.get('Content-Type')) {136 this.type('html');137 }138 break;139 case 'boolean':140 case 'number':141 case 'object':142 if (chunk === null) {143 chunk = '';144 } else if (ArrayBuffer.isView(chunk)) {145 if (!this.get('Content-Type')) {146 this.type('bin');147 }148 } else {149 return this.json(chunk);150 }151 break;152 }153154 // write strings in utf-8155 if (typeof chunk === 'string') {156 encoding = 'utf8';157 type = this.get('Content-Type');158159 // reflect this in content-type160 if (typeof type === 'string') {161 this.set('Content-Type', setCharset(type, 'utf-8'));162 }163 }164165 // determine if ETag should be generated166 var etagFn = app.get('etag fn')167 var generateETag = !this.get('ETag') && typeof etagFn === 'function'168169 // populate Content-Length170 var len171 if (chunk !== undefined) {172 if (Buffer.isBuffer(chunk)) {173 // get length of Buffer174 len = chunk.length175 } else if (!generateETag && chunk.length < 1000) {176 // just calculate length when no ETag + small chunk177 len = Buffer.byteLength(chunk, encoding)178 } else {179 // convert chunk to Buffer and calculate180 chunk = Buffer.from(chunk, encoding)181 encoding = undefined;182 len = chunk.length183 }184185 this.set('Content-Length', len);186 }187188 // populate ETag189 var etag;190 if (generateETag && len !== undefined) {191 if ((etag = etagFn(chunk, encoding))) {192 this.set('ETag', etag);193 }194 }195196 // freshness197 if (req.fresh) this.status(304);198199 // strip irrelevant headers200 if (204 === this.statusCode || 304 === this.statusCode) {201 this.removeHeader('Content-Type');202 this.removeHeader('Content-Length');203 this.removeHeader('Transfer-Encoding');204 chunk = '';205 }206207 // alter headers for 205208 if (this.statusCode === 205) {209 this.set('Content-Length', '0')210 this.removeHeader('Transfer-Encoding')211 chunk = ''212 }213214 if (req.method === 'HEAD') {215 // skip body for HEAD216 this.end();217 } else {218 // respond219 this.end(chunk, encoding);220 }221222 return this;223};224225/**226 * Send JSON response.227 *228 * Examples:229 *230 * res.json(null);231 * res.json({ user: 'tj' });232 *233 * @param {string|number|boolean|object} obj234 * @public235 */236237res.json = function json(obj) {238 // settings239 var app = this.app;240 var escape = app.get('json escape')241 var replacer = app.get('json replacer');242 var spaces = app.get('json spaces');243 var body = stringify(obj, replacer, spaces, escape)244245 // content-type246 if (!this.get('Content-Type')) {247 this.set('Content-Type', 'application/json');248 }249250 return this.send(body);251};252253/**254 * Send JSON response with JSONP callback support.255 *256 * Examples:257 *258 * res.jsonp(null);259 * res.jsonp({ user: 'tj' });260 *261 * @param {string|number|boolean|object} obj262 * @public263 */264265res.jsonp = function jsonp(obj) {266 // settings267 var app = this.app;268 var escape = app.get('json escape')269 var replacer = app.get('json replacer');270 var spaces = app.get('json spaces');271 var body = stringify(obj, replacer, spaces, escape)272 var callback = this.req.query[app.get('jsonp callback name')];273274 // content-type275 if (!this.get('Content-Type')) {276 this.set('X-Content-Type-Options', 'nosniff');277 this.set('Content-Type', 'application/json');278 }279280 // fixup callback281 if (Array.isArray(callback)) {282 callback = callback[0];283 }284285 // jsonp286 if (typeof callback === 'string' && callback.length !== 0) {287 this.set('X-Content-Type-Options', 'nosniff');288 this.set('Content-Type', 'text/javascript');289290 // restrict callback charset291 callback = callback.replace(/[^\[\]\w$.]/g, '');292293 if (body === undefined) {294 // empty argument295 body = ''296 } else if (typeof body === 'string') {297 // replace chars not allowed in JavaScript that are in JSON298 body = body299 .replace(/\u2028/g, '\\u2028')300 .replace(/\u2029/g, '\\u2029')301 }302303 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"304 // the typeof check is just to reduce client error noise305 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';306 }307308 return this.send(body);309};310311/**312 * Send given HTTP status code.313 *314 * Sets the response status to `statusCode` and the body of the315 * response to the standard description from node's http.STATUS_CODES316 * or the statusCode number if no description.317 *318 * Examples:319 *320 * res.sendStatus(200);321 *322 * @param {number} statusCode323 * @public324 */325326res.sendStatus = function sendStatus(statusCode) {327 var body = statuses.message[statusCode] || String(statusCode)328329 this.status(statusCode);330 this.type('txt');331332 return this.send(body);333};334335/**336 * Transfer the file at the given `path`.337 *338 * Automatically sets the _Content-Type_ response header field.339 * The callback `callback(err)` is invoked when the transfer is complete340 * or when an error occurs. Be sure to check `res.headersSent`341 * if you wish to attempt responding, as the header and some data342 * may have already been transferred.343 *344 * Options:345 *346 * - `maxAge` defaulting to 0 (can be string converted by `ms`)347 * - `root` root directory for relative filenames348 * - `headers` object of headers to serve with file349 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them350 *351 * Other options are passed along to `send`.352 *353 * Examples:354 *355 * The following example illustrates how `res.sendFile()` may356 * be used as an alternative for the `static()` middleware for357 * dynamic situations. The code backing `res.sendFile()` is actually358 * the same code, so HTTP cache support etc is identical.359 *360 * app.get('/user/:uid/photos/:file', function(req, res){361 * var uid = req.params.uid362 * , file = req.params.file;363 *364 * req.user.mayViewFilesFrom(uid, function(yes){365 * if (yes) {366 * res.sendFile('/uploads/' + uid + '/' + file);367 * } else {368 * res.send(403, 'Sorry! you cant see that.');369 * }370 * });371 * });372 *373 * @public374 */375376res.sendFile = function sendFile(path, options, callback) {377 var done = callback;378 var req = this.req;379 var res = this;380 var next = req.next;381 var opts = options || {};382383 if (!path) {384 throw new TypeError('path argument is required to res.sendFile');385 }386387 if (typeof path !== 'string') {388 throw new TypeError('path must be a string to res.sendFile')389 }390391 // support function as second arg392 if (typeof options === 'function') {393 done = options;394 opts = {};395 }396397 if (!opts.root && !pathIsAbsolute(path)) {398 throw new TypeError('path must be absolute or specify root to res.sendFile');399 }400401 // create file stream402 var pathname = encodeURI(path);403404 // wire application etag option to send405 opts.etag = this.app.enabled('etag');406 var file = send(req, pathname, opts);407408 // transfer409 sendfile(res, file, opts, function (err) {410 if (done) return done(err);411 if (err && err.code === 'EISDIR') return next();412413 // next() all but write errors414 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {415 next(err);416 }417 });418};419420/**421 * Transfer the file at the given `path` as an attachment.422 *423 * Optionally providing an alternate attachment `filename`,424 * and optional callback `callback(err)`. The callback is invoked425 * when the data transfer is complete, or when an error has426 * occurred. Be sure to check `res.headersSent` if you plan to respond.427 *428 * Optionally providing an `options` object to use with `res.sendFile()`.429 * This function will set the `Content-Disposition` header, overriding430 * any `Content-Disposition` header passed as header options in order431 * to set the attachment and filename.432 *433 * This method uses `res.sendFile()`.434 *435 * @public436 */437438res.download = function download (path, filename, options, callback) {439 var done = callback;440 var name = filename;441 var opts = options || null442443 // support function as second or third arg444 if (typeof filename === 'function') {445 done = filename;446 name = null;447 opts = null448 } else if (typeof options === 'function') {449 done = options450 opts = null451 }452453 // support optional filename, where options may be in it's place454 if (typeof filename === 'object' &&455 (typeof options === 'function' || options === undefined)) {456 name = null457 opts = filename458 }459460 // set Content-Disposition when file is sent461 var headers = {462 'Content-Disposition': contentDisposition(name || path)463 };464465 // merge user-provided headers466 if (opts && opts.headers) {467 var keys = Object.keys(opts.headers)468 for (var i = 0; i < keys.length; i++) {469 var key = keys[i]470 if (key.toLowerCase() !== 'content-disposition') {471 headers[key] = opts.headers[key]472 }473 }474 }475476 // merge user-provided options477 opts = Object.create(opts)478 opts.headers = headers479480 // Resolve the full path for sendFile481 var fullPath = !opts.root482 ? resolve(path)483 : path484485 // send file486 return this.sendFile(fullPath, opts, done)487};488489/**490 * Set _Content-Type_ response header with `type` through `mime.contentType()`491 * when it does not contain "/", or set the Content-Type to `type` otherwise.492 * When no mapping is found though `mime.contentType()`, the type is set to493 * "application/octet-stream".494 *495 * Examples:496 *497 * res.type('.html');498 * res.type('html');499 * res.type('json');500 * res.type('application/json');501 * res.type('png');502 *503 * @param {String} type504 * @return {ServerResponse} for chaining505 * @public506 */507508res.contentType =509res.type = function contentType(type) {510 var ct = type.indexOf('/') === -1511 ? (mime.contentType(type) || 'application/octet-stream')512 : type;513514 return this.set('Content-Type', ct);515};516517/**518 * Respond to the Acceptable formats using an `obj`519 * of mime-type callbacks.520 *521 * This method uses `req.accepted`, an array of522 * acceptable types ordered by their quality values.523 * When "Accept" is not present the _first_ callback524 * is invoked, otherwise the first match is used. When525 * no match is performed the server responds with526 * 406 "Not Acceptable".527 *528 * Content-Type is set for you, however if you choose529 * you may alter this within the callback using `res.type()`530 * or `res.set('Content-Type', ...)`.531 *532 * res.format({533 * 'text/plain': function(){534 * res.send('hey');535 * },536 *537 * 'text/html': function(){538 * res.send('<p>hey</p>');539 * },540 *541 * 'application/json': function () {542 * res.send({ message: 'hey' });543 * }544 * });545 *546 * In addition to canonicalized MIME types you may547 * also use extnames mapped to these types:548 *549 * res.format({550 * text: function(){551 * res.send('hey');552 * },553 *554 * html: function(){555 * res.send('<p>hey</p>');556 * },557 *558 * json: function(){559 * res.send({ message: 'hey' });560 * }561 * });562 *563 * By default Express passes an `Error`564 * with a `.status` of 406 to `next(err)`565 * if a match is not made. If you provide566 * a `.default` callback it will be invoked567 * instead.568 *569 * @param {Object} obj570 * @return {ServerResponse} for chaining571 * @public572 */573574res.format = function(obj){575 var req = this.req;576 var next = req.next;577578 var keys = Object.keys(obj)579 .filter(function (v) { return v !== 'default' })580581 var key = keys.length > 0582 ? req.accepts(keys)583 : false;584585 this.vary("Accept");586587 if (key) {588 this.set('Content-Type', normalizeType(key).value);589 obj[key](req, this, next);590 } else if (obj.default) {591 obj.default(req, this, next)592 } else {593 next(createError(406, {594 types: normalizeTypes(keys).map(function (o) { return o.value })595 }))596 }597598 return this;599};600601/**602 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.603 *604 * @param {String} filename605 * @return {ServerResponse}606 * @public607 */608609res.attachment = function attachment(filename) {610 if (filename) {611 this.type(extname(filename));612 }613614 this.set('Content-Disposition', contentDisposition(filename));615616 return this;617};618619/**620 * Append additional header `field` with value `val`.621 *622 * Example:623 *624 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);625 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');626 * res.append('Warning', '199 Miscellaneous warning');627 *628 * @param {String} field629 * @param {String|Array} val630 * @return {ServerResponse} for chaining631 * @public632 */633634res.append = function append(field, val) {635 var prev = this.get(field);636 var value = val;637638 if (prev) {639 // concat the new and prev vals640 value = Array.isArray(prev) ? prev.concat(val)641 : Array.isArray(val) ? [prev].concat(val)642 : [prev, val]643 }644645 return this.set(field, value);646};647648/**649 * Set header `field` to `val`, or pass650 * an object of header fields.651 *652 * Examples:653 *654 * res.set('Foo', ['bar', 'baz']);655 * res.set('Accept', 'application/json');656 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });657 *658 * Aliased as `res.header()`.659 *660 * When the set header is "Content-Type", the type is expanded to include661 * the charset if not present using `mime.contentType()`.662 *663 * @param {String|Object} field664 * @param {String|Array} val665 * @return {ServerResponse} for chaining666 * @public667 */668669res.set =670res.header = function header(field, val) {671 if (arguments.length === 2) {672 var value = Array.isArray(val)673 ? val.map(String)674 : String(val);675676 // add charset to content-type677 if (field.toLowerCase() === 'content-type') {678 if (Array.isArray(value)) {679 throw new TypeError('Content-Type cannot be set to an Array');680 }681 value = mime.contentType(value)682 }683684 this.setHeader(field, value);685 } else {686 for (var key in field) {687 this.set(key, field[key]);688 }689 }690 return this;691};692693/**694 * Get value for header `field`.695 *696 * @param {String} field697 * @return {String}698 * @public699 */700701res.get = function(field){702 return this.getHeader(field);703};704705/**706 * Clear cookie `name`.707 *708 * @param {String} name709 * @param {Object} [options]710 * @return {ServerResponse} for chaining711 * @public712 */713714res.clearCookie = function clearCookie(name, options) {715 // Force cookie expiration by setting expires to the past716 const opts = { path: '/', ...options, expires: new Date(1)};717 // ensure maxAge is not passed718 delete opts.maxAge719720 return this.cookie(name, '', opts);721};722723/**724 * Set cookie `name` to `value`, with the given `options`.725 *726 * Options:727 *728 * - `maxAge` max-age in milliseconds, converted to `expires`729 * - `signed` sign the cookie730 * - `path` defaults to "/"731 *732 * Examples:733 *734 * // "Remember Me" for 15 minutes735 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });736 *737 * // same as above738 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })739 *740 * @param {String} name741 * @param {String|Object} value742 * @param {Object} [options]743 * @return {ServerResponse} for chaining744 * @public745 */746747res.cookie = function (name, value, options) {748 var opts = { ...options };749 var secret = this.req.secret;750 var signed = opts.signed;751752 if (signed && !secret) {753 throw new Error('cookieParser("secret") required for signed cookies');754 }755756 var val = typeof value === 'object'757 ? 'j:' + JSON.stringify(value)758 : String(value);759760 if (signed) {761 val = 's:' + sign(val, secret);762 }763764 if (opts.maxAge != null) {765 var maxAge = opts.maxAge - 0766767 if (!isNaN(maxAge)) {768 opts.expires = new Date(Date.now() + maxAge)769 opts.maxAge = Math.floor(maxAge / 1000)770 }771 }772773 if (opts.path == null) {774 opts.path = '/';775 }776777 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));778779 return this;780};781782/**783 * Set the location header to `url`.784 *785 * The given `url` can also be "back", which redirects786 * to the _Referrer_ or _Referer_ headers or "/".787 *788 * Examples:789 *790 * res.location('/foo/bar').;791 * res.location('http://example.com');792 * res.location('../login');793 *794 * @param {String} url795 * @return {ServerResponse} for chaining796 * @public797 */798799res.location = function location(url) {800 return this.set('Location', encodeUrl(url));801};802803/**804 * Redirect to the given `url` with optional response `status`805 * defaulting to 302.806 *807 * Examples:808 *809 * res.redirect('/foo/bar');810 * res.redirect('http://example.com');811 * res.redirect(301, 'http://example.com');812 * res.redirect('../login'); // /blog/post/1 -> /blog/login813 *814 * @public815 */816817res.redirect = function redirect(url) {818 var address = url;819 var body;820 var status = 302;821822 // allow status / url823 if (arguments.length === 2) {824 status = arguments[0]825 address = arguments[1]826 }827828 // Set location header829 address = this.location(address).get('Location');830831 // Support text/{plain,html} by default832 this.format({833 text: function(){834 body = statuses.message[status] + '. Redirecting to ' + address835 },836837 html: function(){838 var u = escapeHtml(address);839 body = '<p>' + statuses.message[status] + '. Redirecting to ' + u + '</p>'840 },841842 default: function(){843 body = '';844 }845 });846847 // Respond848 this.status(status);849 this.set('Content-Length', Buffer.byteLength(body));850851 if (this.req.method === 'HEAD') {852 this.end();853 } else {854 this.end(body);855 }856};857858/**859 * Add `field` to Vary. If already present in the Vary set, then860 * this call is simply ignored.861 *862 * @param {Array|String} field863 * @return {ServerResponse} for chaining864 * @public865 */866867res.vary = function(field){868 vary(this, field);869870 return this;871};872873/**874 * Render `view` with the given `options` and optional callback `fn`.875 * When a callback function is given a response will _not_ be made876 * automatically, otherwise a response of _200_ and _text/html_ is given.877 *878 * Options:879 *880 * - `cache` boolean hinting to the engine it should cache881 * - `filename` filename of the view being rendered882 *883 * @public884 */885886res.render = function render(view, options, callback) {887 var app = this.req.app;888 var done = callback;889 var opts = options || {};890 var req = this.req;891 var self = this;892893 // support callback function as second arg894 if (typeof options === 'function') {895 done = options;896 opts = {};897 }898899 // merge res.locals900 opts._locals = self.locals;901902 // default callback to respond903 done = done || function (err, str) {904 if (err) return req.next(err);905 self.send(str);906 };907908 // render909 app.render(view, opts, done);910};911912// pipe the send file stream913function sendfile(res, file, options, callback) {914 var done = false;915 var streaming;916917 // request aborted918 function onaborted() {919 if (done) return;920 done = true;921922 var err = new Error('Request aborted');923 err.code = 'ECONNABORTED';924 callback(err);925 }926927 // directory928 function ondirectory() {929 if (done) return;930 done = true;931932 var err = new Error('EISDIR, read');933 err.code = 'EISDIR';934 callback(err);935 }936937 // errors938 function onerror(err) {939 if (done) return;940 done = true;941 callback(err);942 }943944 // ended945 function onend() {946 if (done) return;947 done = true;948 callback();949 }950951 // file952 function onfile() {953 streaming = false;954 }955956 // finished957 function onfinish(err) {958 if (err && err.code === 'ECONNRESET') return onaborted();959 if (err) return onerror(err);960 if (done) return;961962 setImmediate(function () {963 if (streaming !== false && !done) {964 onaborted();965 return;966 }967968 if (done) return;969 done = true;970 callback();971 });972 }973974 // streaming975 function onstream() {976 streaming = true;977 }978979 file.on('directory', ondirectory);980 file.on('end', onend);981 file.on('error', onerror);982 file.on('file', onfile);983 file.on('stream', onstream);984 onFinished(res, onfinish);985986 if (options.headers) {987 // set headers on successful transfer988 file.on('headers', function headers(res) {989 var obj = options.headers;990 var keys = Object.keys(obj);991992 for (var i = 0; i < keys.length; i++) {993 var k = keys[i];994 res.setHeader(k, obj[k]);995 }996 });997 }998999 // pipe1000 file.pipe(res);1001}10021003/**1004 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1005 * ability to escape characters that can trigger HTML sniffing.1006 *1007 * @param {*} value1008 * @param {function} replacer1009 * @param {number} spaces1010 * @param {boolean} escape1011 * @returns {string}1012 * @private1013 */10141015function stringify (value, replacer, spaces, escape) {1016 // v8 checks arguments.length for optimizing simple call1017 // https://bugs.chromium.org/p/v8/issues/detail?id=47301018 var json = replacer || spaces1019 ? JSON.stringify(value, replacer, spaces)1020 : JSON.stringify(value);10211022 if (escape && typeof json === 'string') {1023 json = json.replace(/[<>&]/g, function (c) {1024 switch (c.charCodeAt(0)) {1025 case 0x3c:1026 return '\\u003c'1027 case 0x3e:1028 return '\\u003e'1029 case 0x26:1030 return '\\u0026'1031 /* istanbul ignore next: unreachable default */1032 default:1033 return c1034 }1035 })1036 }10371038 return json1039}