response.js
This file
Path
lib/response.js
1,044 lines · 23.9 KiB · JavaScript
Last changed by
Merge tag '4.19.1' into 5.xWes Toddbefore adoption60fb1d2
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 Buffer = require('safe-buffer').Buffer16var contentDisposition = require('content-disposition');17var createError = require('http-errors')18var deprecate = require('depd')('express');19var encodeUrl = require('encodeurl');20var escapeHtml = require('escape-html');21var http = require('http');22var onFinished = require('on-finished');23var mime = require('mime-types')24var path = require('path');25var pathIsAbsolute = require('path-is-absolute');26var statuses = require('statuses')27var merge = require('utils-merge');28var sign = require('cookie-signature').sign;29var normalizeType = require('./utils').normalizeType;30var normalizeTypes = require('./utils').normalizeTypes;31var setCharset = require('./utils').setCharset;32var cookie = require('cookie');33var send = require('send');34var extname = path.extname;35var resolve = path.resolve;36var vary = require('vary');37var urlParse = require('url').parse;3839/**40 * Response prototype.41 * @public42 */4344var res = Object.create(http.ServerResponse.prototype)4546/**47 * Module exports.48 * @public49 */5051module.exports = res5253/**54 * Set status `code`.55 *56 * @param {Number} code57 * @return {ServerResponse}58 * @public59 */6061res.status = function status(code) {62 if ((typeof code === 'string' || Math.floor(code) !== code) && code > 99 && code < 1000) {63 deprecate('res.status(' + JSON.stringify(code) + '): use res.status(' + Math.floor(code) + ') instead')64 }65 this.statusCode = code;66 return this;67};6869/**70 * Set Link header field with the given `links`.71 *72 * Examples:73 *74 * res.links({75 * next: 'http://api.example.com/users?page=2',76 * last: 'http://api.example.com/users?page=5'77 * });78 *79 * @param {Object} links80 * @return {ServerResponse}81 * @public82 */8384res.links = function(links){85 var link = this.get('Link') || '';86 if (link) link += ', ';87 return this.set('Link', link + Object.keys(links).map(function(rel){88 return '<' + links[rel] + '>; rel="' + rel + '"';89 }).join(', '));90};9192/**93 * Send a response.94 *95 * Examples:96 *97 * res.send(Buffer.from('wahoo'));98 * res.send({ some: 'json' });99 * res.send('<p>some html</p>');100 *101 * @param {string|number|boolean|object|Buffer} body102 * @public103 */104105res.send = function send(body) {106 var chunk = body;107 var encoding;108 var req = this.req;109 var type;110111 // settings112 var app = this.app;113114 switch (typeof chunk) {115 // string defaulting to html116 case 'string':117 if (!this.get('Content-Type')) {118 this.type('html');119 }120 break;121 case 'boolean':122 case 'number':123 case 'object':124 if (chunk === null) {125 chunk = '';126 } else if (Buffer.isBuffer(chunk)) {127 if (!this.get('Content-Type')) {128 this.type('bin');129 }130 } else {131 return this.json(chunk);132 }133 break;134 }135136 // write strings in utf-8137 if (typeof chunk === 'string') {138 encoding = 'utf8';139 type = this.get('Content-Type');140141 // reflect this in content-type142 if (typeof type === 'string') {143 this.set('Content-Type', setCharset(type, 'utf-8'));144 }145 }146147 // determine if ETag should be generated148 var etagFn = app.get('etag fn')149 var generateETag = !this.get('ETag') && typeof etagFn === 'function'150151 // populate Content-Length152 var len153 if (chunk !== undefined) {154 if (Buffer.isBuffer(chunk)) {155 // get length of Buffer156 len = chunk.length157 } else if (!generateETag && chunk.length < 1000) {158 // just calculate length when no ETag + small chunk159 len = Buffer.byteLength(chunk, encoding)160 } else {161 // convert chunk to Buffer and calculate162 chunk = Buffer.from(chunk, encoding)163 encoding = undefined;164 len = chunk.length165 }166167 this.set('Content-Length', len);168 }169170 // populate ETag171 var etag;172 if (generateETag && len !== undefined) {173 if ((etag = etagFn(chunk, encoding))) {174 this.set('ETag', etag);175 }176 }177178 // freshness179 if (req.fresh) this.statusCode = 304;180181 // strip irrelevant headers182 if (204 === this.statusCode || 304 === this.statusCode) {183 this.removeHeader('Content-Type');184 this.removeHeader('Content-Length');185 this.removeHeader('Transfer-Encoding');186 chunk = '';187 }188189 // alter headers for 205190 if (this.statusCode === 205) {191 this.set('Content-Length', '0')192 this.removeHeader('Transfer-Encoding')193 chunk = ''194 }195196 if (req.method === 'HEAD') {197 // skip body for HEAD198 this.end();199 } else {200 // respond201 this.end(chunk, encoding);202 }203204 return this;205};206207/**208 * Send JSON response.209 *210 * Examples:211 *212 * res.json(null);213 * res.json({ user: 'tj' });214 *215 * @param {string|number|boolean|object} obj216 * @public217 */218219res.json = function json(obj) {220 // settings221 var app = this.app;222 var escape = app.get('json escape')223 var replacer = app.get('json replacer');224 var spaces = app.get('json spaces');225 var body = stringify(obj, replacer, spaces, escape)226227 // content-type228 if (!this.get('Content-Type')) {229 this.set('Content-Type', 'application/json');230 }231232 return this.send(body);233};234235/**236 * Send JSON response with JSONP callback support.237 *238 * Examples:239 *240 * res.jsonp(null);241 * res.jsonp({ user: 'tj' });242 *243 * @param {string|number|boolean|object} obj244 * @public245 */246247res.jsonp = function jsonp(obj) {248 // settings249 var app = this.app;250 var escape = app.get('json escape')251 var replacer = app.get('json replacer');252 var spaces = app.get('json spaces');253 var body = stringify(obj, replacer, spaces, escape)254 var callback = this.req.query[app.get('jsonp callback name')];255256 // content-type257 if (!this.get('Content-Type')) {258 this.set('X-Content-Type-Options', 'nosniff');259 this.set('Content-Type', 'application/json');260 }261262 // fixup callback263 if (Array.isArray(callback)) {264 callback = callback[0];265 }266267 // jsonp268 if (typeof callback === 'string' && callback.length !== 0) {269 this.set('X-Content-Type-Options', 'nosniff');270 this.set('Content-Type', 'text/javascript');271272 // restrict callback charset273 callback = callback.replace(/[^\[\]\w$.]/g, '');274275 if (body === undefined) {276 // empty argument277 body = ''278 } else if (typeof body === 'string') {279 // replace chars not allowed in JavaScript that are in JSON280 body = body281 .replace(/\u2028/g, '\\u2028')282 .replace(/\u2029/g, '\\u2029')283 }284285 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"286 // the typeof check is just to reduce client error noise287 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';288 }289290 return this.send(body);291};292293/**294 * Send given HTTP status code.295 *296 * Sets the response status to `statusCode` and the body of the297 * response to the standard description from node's http.STATUS_CODES298 * or the statusCode number if no description.299 *300 * Examples:301 *302 * res.sendStatus(200);303 *304 * @param {number} statusCode305 * @public306 */307308res.sendStatus = function sendStatus(statusCode) {309 var body = statuses.message[statusCode] || String(statusCode)310311 this.statusCode = statusCode;312 this.type('txt');313314 return this.send(body);315};316317/**318 * Transfer the file at the given `path`.319 *320 * Automatically sets the _Content-Type_ response header field.321 * The callback `callback(err)` is invoked when the transfer is complete322 * or when an error occurs. Be sure to check `res.headersSent`323 * if you wish to attempt responding, as the header and some data324 * may have already been transferred.325 *326 * Options:327 *328 * - `maxAge` defaulting to 0 (can be string converted by `ms`)329 * - `root` root directory for relative filenames330 * - `headers` object of headers to serve with file331 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them332 *333 * Other options are passed along to `send`.334 *335 * Examples:336 *337 * The following example illustrates how `res.sendFile()` may338 * be used as an alternative for the `static()` middleware for339 * dynamic situations. The code backing `res.sendFile()` is actually340 * the same code, so HTTP cache support etc is identical.341 *342 * app.get('/user/:uid/photos/:file', function(req, res){343 * var uid = req.params.uid344 * , file = req.params.file;345 *346 * req.user.mayViewFilesFrom(uid, function(yes){347 * if (yes) {348 * res.sendFile('/uploads/' + uid + '/' + file);349 * } else {350 * res.send(403, 'Sorry! you cant see that.');351 * }352 * });353 * });354 *355 * @public356 */357358res.sendFile = function sendFile(path, options, callback) {359 var done = callback;360 var req = this.req;361 var res = this;362 var next = req.next;363 var opts = options || {};364365 if (!path) {366 throw new TypeError('path argument is required to res.sendFile');367 }368369 if (typeof path !== 'string') {370 throw new TypeError('path must be a string to res.sendFile')371 }372373 // support function as second arg374 if (typeof options === 'function') {375 done = options;376 opts = {};377 }378379 if (!opts.root && !pathIsAbsolute(path)) {380 throw new TypeError('path must be absolute or specify root to res.sendFile');381 }382383 // create file stream384 var pathname = encodeURI(path);385 var file = send(req, pathname, opts);386387 // transfer388 sendfile(res, file, opts, function (err) {389 if (done) return done(err);390 if (err && err.code === 'EISDIR') return next();391392 // next() all but write errors393 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {394 next(err);395 }396 });397};398399/**400 * Transfer the file at the given `path` as an attachment.401 *402 * Optionally providing an alternate attachment `filename`,403 * and optional callback `callback(err)`. The callback is invoked404 * when the data transfer is complete, or when an error has405 * occurred. Be sure to check `res.headersSent` if you plan to respond.406 *407 * Optionally providing an `options` object to use with `res.sendFile()`.408 * This function will set the `Content-Disposition` header, overriding409 * any `Content-Disposition` header passed as header options in order410 * to set the attachment and filename.411 *412 * This method uses `res.sendFile()`.413 *414 * @public415 */416417res.download = function download (path, filename, options, callback) {418 var done = callback;419 var name = filename;420 var opts = options || null421422 // support function as second or third arg423 if (typeof filename === 'function') {424 done = filename;425 name = null;426 opts = null427 } else if (typeof options === 'function') {428 done = options429 opts = null430 }431432 // support optional filename, where options may be in it's place433 if (typeof filename === 'object' &&434 (typeof options === 'function' || options === undefined)) {435 name = null436 opts = filename437 }438439 // set Content-Disposition when file is sent440 var headers = {441 'Content-Disposition': contentDisposition(name || path)442 };443444 // merge user-provided headers445 if (opts && opts.headers) {446 var keys = Object.keys(opts.headers)447 for (var i = 0; i < keys.length; i++) {448 var key = keys[i]449 if (key.toLowerCase() !== 'content-disposition') {450 headers[key] = opts.headers[key]451 }452 }453 }454455 // merge user-provided options456 opts = Object.create(opts)457 opts.headers = headers458459 // Resolve the full path for sendFile460 var fullPath = !opts.root461 ? resolve(path)462 : path463464 // send file465 return this.sendFile(fullPath, opts, done)466};467468/**469 * Set _Content-Type_ response header with `type` through `mime.contentType()`470 * when it does not contain "/", or set the Content-Type to `type` otherwise.471 * When no mapping is found though `mime.contentType()`, the type is set to472 * "application/octet-stream".473 *474 * Examples:475 *476 * res.type('.html');477 * res.type('html');478 * res.type('json');479 * res.type('application/json');480 * res.type('png');481 *482 * @param {String} type483 * @return {ServerResponse} for chaining484 * @public485 */486487res.contentType =488res.type = function contentType(type) {489 var ct = type.indexOf('/') === -1490 ? (mime.contentType(type) || 'application/octet-stream')491 : type;492493 return this.set('Content-Type', ct);494};495496/**497 * Respond to the Acceptable formats using an `obj`498 * of mime-type callbacks.499 *500 * This method uses `req.accepted`, an array of501 * acceptable types ordered by their quality values.502 * When "Accept" is not present the _first_ callback503 * is invoked, otherwise the first match is used. When504 * no match is performed the server responds with505 * 406 "Not Acceptable".506 *507 * Content-Type is set for you, however if you choose508 * you may alter this within the callback using `res.type()`509 * or `res.set('Content-Type', ...)`.510 *511 * res.format({512 * 'text/plain': function(){513 * res.send('hey');514 * },515 *516 * 'text/html': function(){517 * res.send('<p>hey</p>');518 * },519 *520 * 'application/json': function () {521 * res.send({ message: 'hey' });522 * }523 * });524 *525 * In addition to canonicalized MIME types you may526 * also use extnames mapped to these types:527 *528 * res.format({529 * text: function(){530 * res.send('hey');531 * },532 *533 * html: function(){534 * res.send('<p>hey</p>');535 * },536 *537 * json: function(){538 * res.send({ message: 'hey' });539 * }540 * });541 *542 * By default Express passes an `Error`543 * with a `.status` of 406 to `next(err)`544 * if a match is not made. If you provide545 * a `.default` callback it will be invoked546 * instead.547 *548 * @param {Object} obj549 * @return {ServerResponse} for chaining550 * @public551 */552553res.format = function(obj){554 var req = this.req;555 var next = req.next;556557 var keys = Object.keys(obj)558 .filter(function (v) { return v !== 'default' })559560 var key = keys.length > 0561 ? req.accepts(keys)562 : false;563564 this.vary("Accept");565566 if (key) {567 this.set('Content-Type', normalizeType(key).value);568 obj[key](req, this, next);569 } else if (obj.default) {570 obj.default(req, this, next)571 } else {572 next(createError(406, {573 types: normalizeTypes(keys).map(function (o) { return o.value })574 }))575 }576577 return this;578};579580/**581 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.582 *583 * @param {String} filename584 * @return {ServerResponse}585 * @public586 */587588res.attachment = function attachment(filename) {589 if (filename) {590 this.type(extname(filename));591 }592593 this.set('Content-Disposition', contentDisposition(filename));594595 return this;596};597598/**599 * Append additional header `field` with value `val`.600 *601 * Example:602 *603 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);604 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');605 * res.append('Warning', '199 Miscellaneous warning');606 *607 * @param {String} field608 * @param {String|Array} val609 * @return {ServerResponse} for chaining610 * @public611 */612613res.append = function append(field, val) {614 var prev = this.get(field);615 var value = val;616617 if (prev) {618 // concat the new and prev vals619 value = Array.isArray(prev) ? prev.concat(val)620 : Array.isArray(val) ? [prev].concat(val)621 : [prev, val]622 }623624 return this.set(field, value);625};626627/**628 * Set header `field` to `val`, or pass629 * an object of header fields.630 *631 * Examples:632 *633 * res.set('Foo', ['bar', 'baz']);634 * res.set('Accept', 'application/json');635 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });636 *637 * Aliased as `res.header()`.638 *639 * When the set header is "Content-Type", the type is expanded to include640 * the charset if not present using `mime.contentType()`.641 *642 * @param {String|Object} field643 * @param {String|Array} val644 * @return {ServerResponse} for chaining645 * @public646 */647648res.set =649res.header = function header(field, val) {650 if (arguments.length === 2) {651 var value = Array.isArray(val)652 ? val.map(String)653 : String(val);654655 // add charset to content-type656 if (field.toLowerCase() === 'content-type') {657 if (Array.isArray(value)) {658 throw new TypeError('Content-Type cannot be set to an Array');659 }660 value = mime.contentType(value)661 }662663 this.setHeader(field, value);664 } else {665 for (var key in field) {666 this.set(key, field[key]);667 }668 }669 return this;670};671672/**673 * Get value for header `field`.674 *675 * @param {String} field676 * @return {String}677 * @public678 */679680res.get = function(field){681 return this.getHeader(field);682};683684/**685 * Clear cookie `name`.686 *687 * @param {String} name688 * @param {Object} [options]689 * @return {ServerResponse} for chaining690 * @public691 */692693res.clearCookie = function clearCookie(name, options) {694 var opts = merge({ expires: new Date(1), path: '/' }, options);695696 return this.cookie(name, '', opts);697};698699/**700 * Set cookie `name` to `value`, with the given `options`.701 *702 * Options:703 *704 * - `maxAge` max-age in milliseconds, converted to `expires`705 * - `signed` sign the cookie706 * - `path` defaults to "/"707 *708 * Examples:709 *710 * // "Remember Me" for 15 minutes711 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });712 *713 * // same as above714 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })715 *716 * @param {String} name717 * @param {String|Object} value718 * @param {Object} [options]719 * @return {ServerResponse} for chaining720 * @public721 */722723res.cookie = function (name, value, options) {724 var opts = merge({}, options);725 var secret = this.req.secret;726 var signed = opts.signed;727728 if (signed && !secret) {729 throw new Error('cookieParser("secret") required for signed cookies');730 }731732 var val = typeof value === 'object'733 ? 'j:' + JSON.stringify(value)734 : String(value);735736 if (signed) {737 val = 's:' + sign(val, secret);738 }739740 if (opts.maxAge != null) {741 var maxAge = opts.maxAge - 0742743 if (!isNaN(maxAge)) {744 opts.expires = new Date(Date.now() + maxAge)745 opts.maxAge = Math.floor(maxAge / 1000)746 }747 }748749 if (opts.path == null) {750 opts.path = '/';751 }752753 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));754755 return this;756};757758/**759 * Set the location header to `url`.760 *761 * The given `url` can also be "back", which redirects762 * to the _Referrer_ or _Referer_ headers or "/".763 *764 * Examples:765 *766 * res.location('/foo/bar').;767 * res.location('http://example.com');768 * res.location('../login');769 *770 * @param {String} url771 * @return {ServerResponse} for chaining772 * @public773 */774775res.location = function location(url) {776 var loc = String(url);777778 // "back" is an alias for the referrer779 if (url === 'back') {780 loc = this.req.get('Referrer') || '/';781 }782783 var lowerLoc = loc.toLowerCase();784 var encodedUrl = encodeUrl(loc);785 if (lowerLoc.indexOf('https://') === 0 || lowerLoc.indexOf('http://') === 0) {786 try {787 var parsedUrl = urlParse(loc);788 var parsedEncodedUrl = urlParse(encodedUrl);789 // Because this can encode the host, check that we did not change the host790 if (parsedUrl.host !== parsedEncodedUrl.host) {791 // If the host changes after encodeUrl, return the original url792 return this.set('Location', loc);793 }794 } catch (e) {795 // If parse fails, return the original url796 return this.set('Location', loc);797 }798 }799800 // set location801 return this.set('Location', encodedUrl);802};803804/**805 * Redirect to the given `url` with optional response `status`806 * defaulting to 302.807 *808 * The resulting `url` is determined by `res.location()`, so809 * it will play nicely with mounted apps, relative paths,810 * `"back"` etc.811 *812 * Examples:813 *814 * res.redirect('/foo/bar');815 * res.redirect('http://example.com');816 * res.redirect(301, 'http://example.com');817 * res.redirect('../login'); // /blog/post/1 -> /blog/login818 *819 * @public820 */821822res.redirect = function redirect(url) {823 var address = url;824 var body;825 var status = 302;826827 // allow status / url828 if (arguments.length === 2) {829 status = arguments[0]830 address = arguments[1]831 }832833 // Set location header834 address = this.location(address).get('Location');835836 // Support text/{plain,html} by default837 this.format({838 text: function(){839 body = statuses.message[status] + '. Redirecting to ' + address840 },841842 html: function(){843 var u = escapeHtml(address);844 body = '<p>' + statuses.message[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'845 },846847 default: function(){848 body = '';849 }850 });851852 // Respond853 this.statusCode = status;854 this.set('Content-Length', Buffer.byteLength(body));855856 if (this.req.method === 'HEAD') {857 this.end();858 } else {859 this.end(body);860 }861};862863/**864 * Add `field` to Vary. If already present in the Vary set, then865 * this call is simply ignored.866 *867 * @param {Array|String} field868 * @return {ServerResponse} for chaining869 * @public870 */871872res.vary = function(field){873 vary(this, field);874875 return this;876};877878/**879 * Render `view` with the given `options` and optional callback `fn`.880 * When a callback function is given a response will _not_ be made881 * automatically, otherwise a response of _200_ and _text/html_ is given.882 *883 * Options:884 *885 * - `cache` boolean hinting to the engine it should cache886 * - `filename` filename of the view being rendered887 *888 * @public889 */890891res.render = function render(view, options, callback) {892 var app = this.req.app;893 var done = callback;894 var opts = options || {};895 var req = this.req;896 var self = this;897898 // support callback function as second arg899 if (typeof options === 'function') {900 done = options;901 opts = {};902 }903904 // merge res.locals905 opts._locals = self.locals;906907 // default callback to respond908 done = done || function (err, str) {909 if (err) return req.next(err);910 self.send(str);911 };912913 // render914 app.render(view, opts, done);915};916917// pipe the send file stream918function sendfile(res, file, options, callback) {919 var done = false;920 var streaming;921922 // request aborted923 function onaborted() {924 if (done) return;925 done = true;926927 var err = new Error('Request aborted');928 err.code = 'ECONNABORTED';929 callback(err);930 }931932 // directory933 function ondirectory() {934 if (done) return;935 done = true;936937 var err = new Error('EISDIR, read');938 err.code = 'EISDIR';939 callback(err);940 }941942 // errors943 function onerror(err) {944 if (done) return;945 done = true;946 callback(err);947 }948949 // ended950 function onend() {951 if (done) return;952 done = true;953 callback();954 }955956 // file957 function onfile() {958 streaming = false;959 }960961 // finished962 function onfinish(err) {963 if (err && err.code === 'ECONNRESET') return onaborted();964 if (err) return onerror(err);965 if (done) return;966967 setImmediate(function () {968 if (streaming !== false && !done) {969 onaborted();970 return;971 }972973 if (done) return;974 done = true;975 callback();976 });977 }978979 // streaming980 function onstream() {981 streaming = true;982 }983984 file.on('directory', ondirectory);985 file.on('end', onend);986 file.on('error', onerror);987 file.on('file', onfile);988 file.on('stream', onstream);989 onFinished(res, onfinish);990991 if (options.headers) {992 // set headers on successful transfer993 file.on('headers', function headers(res) {994 var obj = options.headers;995 var keys = Object.keys(obj);996997 for (var i = 0; i < keys.length; i++) {998 var k = keys[i];999 res.setHeader(k, obj[k]);1000 }1001 });1002 }10031004 // pipe1005 file.pipe(res);1006}10071008/**1009 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1010 * ability to escape characters that can trigger HTML sniffing.1011 *1012 * @param {*} value1013 * @param {function} replacer1014 * @param {number} spaces1015 * @param {boolean} escape1016 * @returns {string}1017 * @private1018 */10191020function stringify (value, replacer, spaces, escape) {1021 // v8 checks arguments.length for optimizing simple call1022 // https://bugs.chromium.org/p/v8/issues/detail?id=47301023 var json = replacer || spaces1024 ? JSON.stringify(value, replacer, spaces)1025 : JSON.stringify(value);10261027 if (escape && typeof json === 'string') {1028 json = json.replace(/[<>&]/g, function (c) {1029 switch (c.charCodeAt(0)) {1030 case 0x3c:1031 return '\\u003c'1032 case 0x3e:1033 return '\\u003e'1034 case 0x26:1035 return '\\u0026'1036 /* istanbul ignore next: unreachable default */1037 default:1038 return c1039 }1040 })1041 }10421043 return json1044}