response.js
This file
Path
lib/response.js
1,003 lines · 22.5 KiB · JavaScript
Last changed by
Use mime-types for file to content type mappingDouglas Christopher Wilsonbefore adoptiona0276c6
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 encodeUrl = require('encodeurl');18var escapeHtml = require('escape-html');19var http = require('http');20var onFinished = require('on-finished');21var mime = require('mime-types')22var path = require('path');23var pathIsAbsolute = require('path-is-absolute');24var statuses = require('statuses')25var merge = require('utils-merge');26var sign = require('cookie-signature').sign;27var normalizeType = require('./utils').normalizeType;28var normalizeTypes = require('./utils').normalizeTypes;29var setCharset = require('./utils').setCharset;30var cookie = require('cookie');31var send = require('send');32var extname = path.extname;33var resolve = path.resolve;34var vary = require('vary');3536/**37 * Response prototype.38 * @public39 */4041var res = Object.create(http.ServerResponse.prototype)4243/**44 * Module exports.45 * @public46 */4748module.exports = res4950/**51 * Set status `code`.52 *53 * @param {Number} code54 * @return {ServerResponse}55 * @public56 */5758res.status = function status(code) {59 this.statusCode = code;60 return this;61};6263/**64 * Set Link header field with the given `links`.65 *66 * Examples:67 *68 * res.links({69 * next: 'http://api.example.com/users?page=2',70 * last: 'http://api.example.com/users?page=5'71 * });72 *73 * @param {Object} links74 * @return {ServerResponse}75 * @public76 */7778res.links = function(links){79 var link = this.get('Link') || '';80 if (link) link += ', ';81 return this.set('Link', link + Object.keys(links).map(function(rel){82 return '<' + links[rel] + '>; rel="' + rel + '"';83 }).join(', '));84};8586/**87 * Send a response.88 *89 * Examples:90 *91 * res.send(Buffer.from('wahoo'));92 * res.send({ some: 'json' });93 * res.send('<p>some html</p>');94 *95 * @param {string|number|boolean|object|Buffer} body96 * @public97 */9899res.send = function send(body) {100 var chunk = body;101 var encoding;102 var req = this.req;103 var type;104105 // settings106 var app = this.app;107108 switch (typeof chunk) {109 // string defaulting to html110 case 'string':111 if (!this.get('Content-Type')) {112 this.type('html');113 }114 break;115 case 'boolean':116 case 'number':117 case 'object':118 if (chunk === null) {119 chunk = '';120 } else if (Buffer.isBuffer(chunk)) {121 if (!this.get('Content-Type')) {122 this.type('bin');123 }124 } else {125 return this.json(chunk);126 }127 break;128 }129130 // write strings in utf-8131 if (typeof chunk === 'string') {132 encoding = 'utf8';133 type = this.get('Content-Type');134135 // reflect this in content-type136 if (typeof type === 'string') {137 this.set('Content-Type', setCharset(type, 'utf-8'));138 }139 }140141 // determine if ETag should be generated142 var etagFn = app.get('etag fn')143 var generateETag = !this.get('ETag') && typeof etagFn === 'function'144145 // populate Content-Length146 var len147 if (chunk !== undefined) {148 if (Buffer.isBuffer(chunk)) {149 // get length of Buffer150 len = chunk.length151 } else if (!generateETag && chunk.length < 1000) {152 // just calculate length when no ETag + small chunk153 len = Buffer.byteLength(chunk, encoding)154 } else {155 // convert chunk to Buffer and calculate156 chunk = Buffer.from(chunk, encoding)157 encoding = undefined;158 len = chunk.length159 }160161 this.set('Content-Length', len);162 }163164 // populate ETag165 var etag;166 if (generateETag && len !== undefined) {167 if ((etag = etagFn(chunk, encoding))) {168 this.set('ETag', etag);169 }170 }171172 // freshness173 if (req.fresh) this.statusCode = 304;174175 // strip irrelevant headers176 if (204 === this.statusCode || 304 === this.statusCode) {177 this.removeHeader('Content-Type');178 this.removeHeader('Content-Length');179 this.removeHeader('Transfer-Encoding');180 chunk = '';181 }182183 if (req.method === 'HEAD') {184 // skip body for HEAD185 this.end();186 } else {187 // respond188 this.end(chunk, encoding);189 }190191 return this;192};193194/**195 * Send JSON response.196 *197 * Examples:198 *199 * res.json(null);200 * res.json({ user: 'tj' });201 *202 * @param {string|number|boolean|object} obj203 * @public204 */205206res.json = function json(obj) {207 // settings208 var app = this.app;209 var escape = app.get('json escape')210 var replacer = app.get('json replacer');211 var spaces = app.get('json spaces');212 var body = stringify(obj, replacer, spaces, escape)213214 // content-type215 if (!this.get('Content-Type')) {216 this.set('Content-Type', 'application/json');217 }218219 return this.send(body);220};221222/**223 * Send JSON response with JSONP callback support.224 *225 * Examples:226 *227 * res.jsonp(null);228 * res.jsonp({ user: 'tj' });229 *230 * @param {string|number|boolean|object} obj231 * @public232 */233234res.jsonp = function jsonp(obj) {235 // settings236 var app = this.app;237 var escape = app.get('json escape')238 var replacer = app.get('json replacer');239 var spaces = app.get('json spaces');240 var body = stringify(obj, replacer, spaces, escape)241 var callback = this.req.query[app.get('jsonp callback name')];242243 // content-type244 if (!this.get('Content-Type')) {245 this.set('X-Content-Type-Options', 'nosniff');246 this.set('Content-Type', 'application/json');247 }248249 // fixup callback250 if (Array.isArray(callback)) {251 callback = callback[0];252 }253254 // jsonp255 if (typeof callback === 'string' && callback.length !== 0) {256 this.set('X-Content-Type-Options', 'nosniff');257 this.set('Content-Type', 'text/javascript');258259 // restrict callback charset260 callback = callback.replace(/[^\[\]\w$.]/g, '');261262 if (body === undefined) {263 // empty argument264 body = ''265 } else if (typeof body === 'string') {266 // replace chars not allowed in JavaScript that are in JSON267 body = body268 .replace(/\u2028/g, '\\u2028')269 .replace(/\u2029/g, '\\u2029')270 }271272 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"273 // the typeof check is just to reduce client error noise274 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';275 }276277 return this.send(body);278};279280/**281 * Send given HTTP status code.282 *283 * Sets the response status to `statusCode` and the body of the284 * response to the standard description from node's http.STATUS_CODES285 * or the statusCode number if no description.286 *287 * Examples:288 *289 * res.sendStatus(200);290 *291 * @param {number} statusCode292 * @public293 */294295res.sendStatus = function sendStatus(statusCode) {296 var body = statuses[statusCode] || String(statusCode)297298 this.statusCode = statusCode;299 this.type('txt');300301 return this.send(body);302};303304/**305 * Transfer the file at the given `path`.306 *307 * Automatically sets the _Content-Type_ response header field.308 * The callback `callback(err)` is invoked when the transfer is complete309 * or when an error occurs. Be sure to check `res.headersSent`310 * if you wish to attempt responding, as the header and some data311 * may have already been transferred.312 *313 * Options:314 *315 * - `maxAge` defaulting to 0 (can be string converted by `ms`)316 * - `root` root directory for relative filenames317 * - `headers` object of headers to serve with file318 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them319 *320 * Other options are passed along to `send`.321 *322 * Examples:323 *324 * The following example illustrates how `res.sendFile()` may325 * be used as an alternative for the `static()` middleware for326 * dynamic situations. The code backing `res.sendFile()` is actually327 * the same code, so HTTP cache support etc is identical.328 *329 * app.get('/user/:uid/photos/:file', function(req, res){330 * var uid = req.params.uid331 * , file = req.params.file;332 *333 * req.user.mayViewFilesFrom(uid, function(yes){334 * if (yes) {335 * res.sendFile('/uploads/' + uid + '/' + file);336 * } else {337 * res.send(403, 'Sorry! you cant see that.');338 * }339 * });340 * });341 *342 * @public343 */344345res.sendFile = function sendFile(path, options, callback) {346 var done = callback;347 var req = this.req;348 var res = this;349 var next = req.next;350 var opts = options || {};351352 if (!path) {353 throw new TypeError('path argument is required to res.sendFile');354 }355356 if (typeof path !== 'string') {357 throw new TypeError('path must be a string to res.sendFile')358 }359360 // support function as second arg361 if (typeof options === 'function') {362 done = options;363 opts = {};364 }365366 if (!opts.root && !pathIsAbsolute(path)) {367 throw new TypeError('path must be absolute or specify root to res.sendFile');368 }369370 // create file stream371 var pathname = encodeURI(path);372 var file = send(req, pathname, opts);373374 // transfer375 sendfile(res, file, opts, function (err) {376 if (done) return done(err);377 if (err && err.code === 'EISDIR') return next();378379 // next() all but write errors380 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {381 next(err);382 }383 });384};385386/**387 * Transfer the file at the given `path` as an attachment.388 *389 * Optionally providing an alternate attachment `filename`,390 * and optional callback `callback(err)`. The callback is invoked391 * when the data transfer is complete, or when an error has392 * ocurred. Be sure to check `res.headersSent` if you plan to respond.393 *394 * Optionally providing an `options` object to use with `res.sendFile()`.395 * This function will set the `Content-Disposition` header, overriding396 * any `Content-Disposition` header passed as header options in order397 * to set the attachment and filename.398 *399 * This method uses `res.sendFile()`.400 *401 * @public402 */403404res.download = function download (path, filename, options, callback) {405 var done = callback;406 var name = filename;407 var opts = options || null408409 // support function as second or third arg410 if (typeof filename === 'function') {411 done = filename;412 name = null;413 opts = null414 } else if (typeof options === 'function') {415 done = options416 opts = null417 }418419 // set Content-Disposition when file is sent420 var headers = {421 'Content-Disposition': contentDisposition(name || path)422 };423424 // merge user-provided headers425 if (opts && opts.headers) {426 var keys = Object.keys(opts.headers)427 for (var i = 0; i < keys.length; i++) {428 var key = keys[i]429 if (key.toLowerCase() !== 'content-disposition') {430 headers[key] = opts.headers[key]431 }432 }433 }434435 // merge user-provided options436 opts = Object.create(opts)437 opts.headers = headers438439 // Resolve the full path for sendFile440 var fullPath = resolve(path);441442 // send file443 return this.sendFile(fullPath, opts, done)444};445446/**447 * Set _Content-Type_ response header with `type` through `mime.contentType()`448 * when it does not contain "/", or set the Content-Type to `type` otherwise.449 * When no mapping is found though `mime.contentType()`, the type is set to450 * "application/octet-stream".451 *452 * Examples:453 *454 * res.type('.html');455 * res.type('html');456 * res.type('json');457 * res.type('application/json');458 * res.type('png');459 *460 * @param {String} type461 * @return {ServerResponse} for chaining462 * @public463 */464465res.contentType =466res.type = function contentType(type) {467 var ct = type.indexOf('/') === -1468 ? (mime.contentType(type) || 'application/octet-stream')469 : type;470471 return this.set('Content-Type', ct);472};473474/**475 * Respond to the Acceptable formats using an `obj`476 * of mime-type callbacks.477 *478 * This method uses `req.accepted`, an array of479 * acceptable types ordered by their quality values.480 * When "Accept" is not present the _first_ callback481 * is invoked, otherwise the first match is used. When482 * no match is performed the server responds with483 * 406 "Not Acceptable".484 *485 * Content-Type is set for you, however if you choose486 * you may alter this within the callback using `res.type()`487 * or `res.set('Content-Type', ...)`.488 *489 * res.format({490 * 'text/plain': function(){491 * res.send('hey');492 * },493 *494 * 'text/html': function(){495 * res.send('<p>hey</p>');496 * },497 *498 * 'application/json': function () {499 * res.send({ message: 'hey' });500 * }501 * });502 *503 * In addition to canonicalized MIME types you may504 * also use extnames mapped to these types:505 *506 * res.format({507 * text: function(){508 * res.send('hey');509 * },510 *511 * html: function(){512 * res.send('<p>hey</p>');513 * },514 *515 * json: function(){516 * res.send({ message: 'hey' });517 * }518 * });519 *520 * By default Express passes an `Error`521 * with a `.status` of 406 to `next(err)`522 * if a match is not made. If you provide523 * a `.default` callback it will be invoked524 * instead.525 *526 * @param {Object} obj527 * @return {ServerResponse} for chaining528 * @public529 */530531res.format = function(obj){532 var req = this.req;533 var next = req.next;534535 var fn = obj.default;536 if (fn) delete obj.default;537 var keys = Object.keys(obj);538539 var key = keys.length > 0540 ? req.accepts(keys)541 : false;542543 this.vary("Accept");544545 if (key) {546 this.set('Content-Type', normalizeType(key).value);547 obj[key](req, this, next);548 } else if (fn) {549 fn();550 } else {551 var err = new Error('Not Acceptable');552 err.status = err.statusCode = 406;553 err.types = normalizeTypes(keys).map(function(o){ return o.value });554 next(err);555 }556557 return this;558};559560/**561 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.562 *563 * @param {String} filename564 * @return {ServerResponse}565 * @public566 */567568res.attachment = function attachment(filename) {569 if (filename) {570 this.type(extname(filename));571 }572573 this.set('Content-Disposition', contentDisposition(filename));574575 return this;576};577578/**579 * Append additional header `field` with value `val`.580 *581 * Example:582 *583 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);584 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');585 * res.append('Warning', '199 Miscellaneous warning');586 *587 * @param {String} field588 * @param {String|Array} val589 * @return {ServerResponse} for chaining590 * @public591 */592593res.append = function append(field, val) {594 var prev = this.get(field);595 var value = val;596597 if (prev) {598 // concat the new and prev vals599 value = Array.isArray(prev) ? prev.concat(val)600 : Array.isArray(val) ? [prev].concat(val)601 : [prev, val]602 }603604 return this.set(field, value);605};606607/**608 * Set header `field` to `val`, or pass609 * an object of header fields.610 *611 * Examples:612 *613 * res.set('Foo', ['bar', 'baz']);614 * res.set('Accept', 'application/json');615 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });616 *617 * Aliased as `res.header()`.618 *619 * When the set header is "Content-Type", the type is expanded to include620 * the charset if not present using `mime.contentType()`.621 *622 * @param {String|Object} field623 * @param {String|Array} val624 * @return {ServerResponse} for chaining625 * @public626 */627628res.set =629res.header = function header(field, val) {630 if (arguments.length === 2) {631 var value = Array.isArray(val)632 ? val.map(String)633 : String(val);634635 // add charset to content-type636 if (field.toLowerCase() === 'content-type') {637 if (Array.isArray(value)) {638 throw new TypeError('Content-Type cannot be set to an Array');639 }640 value = mime.contentType(value)641 }642643 this.setHeader(field, value);644 } else {645 for (var key in field) {646 this.set(key, field[key]);647 }648 }649 return this;650};651652/**653 * Get value for header `field`.654 *655 * @param {String} field656 * @return {String}657 * @public658 */659660res.get = function(field){661 return this.getHeader(field);662};663664/**665 * Clear cookie `name`.666 *667 * @param {String} name668 * @param {Object} [options]669 * @return {ServerResponse} for chaining670 * @public671 */672673res.clearCookie = function clearCookie(name, options) {674 var opts = merge({ expires: new Date(1), path: '/' }, options);675676 return this.cookie(name, '', opts);677};678679/**680 * Set cookie `name` to `value`, with the given `options`.681 *682 * Options:683 *684 * - `maxAge` max-age in milliseconds, converted to `expires`685 * - `signed` sign the cookie686 * - `path` defaults to "/"687 *688 * Examples:689 *690 * // "Remember Me" for 15 minutes691 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });692 *693 * // same as above694 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })695 *696 * @param {String} name697 * @param {String|Object} value698 * @param {Object} [options]699 * @return {ServerResponse} for chaining700 * @public701 */702703res.cookie = function (name, value, options) {704 var opts = merge({}, options);705 var secret = this.req.secret;706 var signed = opts.signed;707708 if (signed && !secret) {709 throw new Error('cookieParser("secret") required for signed cookies');710 }711712 var val = typeof value === 'object'713 ? 'j:' + JSON.stringify(value)714 : String(value);715716 if (signed) {717 val = 's:' + sign(val, secret);718 }719720 if ('maxAge' in opts) {721 opts.expires = new Date(Date.now() + opts.maxAge);722 opts.maxAge /= 1000;723 }724725 if (opts.path == null) {726 opts.path = '/';727 }728729 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));730731 return this;732};733734/**735 * Set the location header to `url`.736 *737 * The given `url` can also be "back", which redirects738 * to the _Referrer_ or _Referer_ headers or "/".739 *740 * Examples:741 *742 * res.location('/foo/bar').;743 * res.location('http://example.com');744 * res.location('../login');745 *746 * @param {String} url747 * @return {ServerResponse} for chaining748 * @public749 */750751res.location = function location(url) {752 var loc = url;753754 // "back" is an alias for the referrer755 if (url === 'back') {756 loc = this.req.get('Referrer') || '/';757 }758759 // set location760 return this.set('Location', encodeUrl(loc));761};762763/**764 * Redirect to the given `url` with optional response `status`765 * defaulting to 302.766 *767 * The resulting `url` is determined by `res.location()`, so768 * it will play nicely with mounted apps, relative paths,769 * `"back"` etc.770 *771 * Examples:772 *773 * res.redirect('/foo/bar');774 * res.redirect('http://example.com');775 * res.redirect(301, 'http://example.com');776 * res.redirect('../login'); // /blog/post/1 -> /blog/login777 *778 * @public779 */780781res.redirect = function redirect(url) {782 var address = url;783 var body;784 var status = 302;785786 // allow status / url787 if (arguments.length === 2) {788 status = arguments[0]789 address = arguments[1]790 }791792 // Set location header793 address = this.location(address).get('Location');794795 // Support text/{plain,html} by default796 this.format({797 text: function(){798 body = statuses[status] + '. Redirecting to ' + address799 },800801 html: function(){802 var u = escapeHtml(address);803 body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'804 },805806 default: function(){807 body = '';808 }809 });810811 // Respond812 this.statusCode = status;813 this.set('Content-Length', Buffer.byteLength(body));814815 if (this.req.method === 'HEAD') {816 this.end();817 } else {818 this.end(body);819 }820};821822/**823 * Add `field` to Vary. If already present in the Vary set, then824 * this call is simply ignored.825 *826 * @param {Array|String} field827 * @return {ServerResponse} for chaining828 * @public829 */830831res.vary = function(field){832 vary(this, field);833834 return this;835};836837/**838 * Render `view` with the given `options` and optional callback `fn`.839 * When a callback function is given a response will _not_ be made840 * automatically, otherwise a response of _200_ and _text/html_ is given.841 *842 * Options:843 *844 * - `cache` boolean hinting to the engine it should cache845 * - `filename` filename of the view being rendered846 *847 * @public848 */849850res.render = function render(view, options, callback) {851 var app = this.req.app;852 var done = callback;853 var opts = options || {};854 var req = this.req;855 var self = this;856857 // support callback function as second arg858 if (typeof options === 'function') {859 done = options;860 opts = {};861 }862863 // merge res.locals864 opts._locals = self.locals;865866 // default callback to respond867 done = done || function (err, str) {868 if (err) return req.next(err);869 self.send(str);870 };871872 // render873 app.render(view, opts, done);874};875876// pipe the send file stream877function sendfile(res, file, options, callback) {878 var done = false;879 var streaming;880881 // request aborted882 function onaborted() {883 if (done) return;884 done = true;885886 var err = new Error('Request aborted');887 err.code = 'ECONNABORTED';888 callback(err);889 }890891 // directory892 function ondirectory() {893 if (done) return;894 done = true;895896 var err = new Error('EISDIR, read');897 err.code = 'EISDIR';898 callback(err);899 }900901 // errors902 function onerror(err) {903 if (done) return;904 done = true;905 callback(err);906 }907908 // ended909 function onend() {910 if (done) return;911 done = true;912 callback();913 }914915 // file916 function onfile() {917 streaming = false;918 }919920 // finished921 function onfinish(err) {922 if (err && err.code === 'ECONNRESET') return onaborted();923 if (err) return onerror(err);924 if (done) return;925926 setImmediate(function () {927 if (streaming !== false && !done) {928 onaborted();929 return;930 }931932 if (done) return;933 done = true;934 callback();935 });936 }937938 // streaming939 function onstream() {940 streaming = true;941 }942943 file.on('directory', ondirectory);944 file.on('end', onend);945 file.on('error', onerror);946 file.on('file', onfile);947 file.on('stream', onstream);948 onFinished(res, onfinish);949950 if (options.headers) {951 // set headers on successful transfer952 file.on('headers', function headers(res) {953 var obj = options.headers;954 var keys = Object.keys(obj);955956 for (var i = 0; i < keys.length; i++) {957 var k = keys[i];958 res.setHeader(k, obj[k]);959 }960 });961 }962963 // pipe964 file.pipe(res);965}966967/**968 * Stringify JSON, like JSON.stringify, but v8 optimized, with the969 * ability to escape characters that can trigger HTML sniffing.970 *971 * @param {*} value972 * @param {function} replaces973 * @param {number} spaces974 * @param {boolean} escape975 * @returns {string}976 * @private977 */978979function stringify (value, replacer, spaces, escape) {980 // v8 checks arguments.length for optimizing simple call981 // https://bugs.chromium.org/p/v8/issues/detail?id=4730982 var json = replacer || spaces983 ? JSON.stringify(value, replacer, spaces)984 : JSON.stringify(value);985986 if (escape && typeof json === 'string') {987 json = json.replace(/[<>&]/g, function (c) {988 switch (c.charCodeAt(0)) {989 case 0x3c:990 return '\\u003c'991 case 0x3e:992 return '\\u003e'993 case 0x26:994 return '\\u0026'995 /* istanbul ignore next: unreachable default */996 default:997 return c998 }999 })1000 }10011002 return json1003}