Skip to content
Myr

response.js

This file

Path

lib/response.js

846 lines · 19.9 KiB · JavaScript

Last changed by

Generate ETags for all request responsesDouglas Christopher Wilsonbefore adoptioneaf3318

History of this file

Take it

The walk stopped after 200 commits: lines older than 9f4968a point at it.

Generate ETags for all request responsesDouglas Christopher Wilsonbefore adoptioneaf3318

lines 1–7why, one step back
1/*!
2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */7

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 8–9why, one step back
8/**
9 * Module dependencies.

Generate ETags for all request responsesDouglas Christopher Wilsonbefore adoptioneaf3318

line 10why, one step back
10 * @api private

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 11–12why, one step back
11 */
12

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption0e56133

line 13why, one step back
13var contentDisposition = require('content-disposition');

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 14–15why, one step back
14var deprecate = require('depd')('express');
15var escapeHtml = require('escape-html');

Fix internal utils.merge deprecation warningsDouglas Christopher Wilsonbefore adoptionaf10438

line 16why, one step back
16var merge = require('utils-merge');

Fix original URL parsing in res.locationDouglas Christopher Wilsonbefore adoptiona57efea

line 17why, one step back
17var parseUrl = require('parseurl');

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 18–162why, one step back
18var vary = require('vary');
19var http = require('http')20 , path = require('path')21 , connect = require('connect')22 , sign = require('cookie-signature').sign23 , normalizeType = require('./utils').normalizeType24 , normalizeTypes = require('./utils').normalizeTypes25 , setCharset = require('./utils').setCharset26 , statusCodes = http.STATUS_CODES27 , cookie = require('cookie')28 , send = require('send')29 , mime = connect.mime30 , resolve = require('url').resolve31 , basename = path.basename32 , extname = path.extname;3334/**35 * Response prototype.36 */3738var res = module.exports = {39 __proto__: http.ServerResponse.prototype40};4142/**43 * Set status `code`.44 *45 * @param {Number} code46 * @return {ServerResponse}47 * @api public48 */4950res.status = function(code){51 this.statusCode = code;52 return this;53};5455/**56 * Set Link header field with the given `links`.57 *58 * Examples:59 *60 * res.links({61 * next: 'http://api.example.com/users?page=2',62 * last: 'http://api.example.com/users?page=5'63 * });64 *65 * @param {Object} links66 * @return {ServerResponse}67 * @api public68 */6970res.links = function(links){71 var link = this.get('Link') || '';72 if (link) link += ', ';73 return this.set('Link', link + Object.keys(links).map(function(rel){74 return '<' + links[rel] + '>; rel="' + rel + '"';75 }).join(', '));76};7778/**79 * Send a response.80 *81 * Examples:82 *83 * res.send(new Buffer('wahoo'));84 * res.send({ some: 'json' });85 * res.send('<p>some html</p>');86 * res.send(404, 'Sorry, cant find that');87 * res.send(404);88 *89 * @param {Mixed} body or status90 * @param {Mixed} body91 * @return {ServerResponse}92 * @api public93 */9495res.send = function(body){96 var req = this.req;97 var type;98 var encoding;99 var len;100101 // settings102 var app = this.app;103104 // allow status / body105 if (2 == arguments.length) {106 // res.send(body, status) backwards compat107 if ('number' != typeof body && 'number' == typeof arguments[1]) {108 this.statusCode = arguments[1];109 } else {110 this.statusCode = body;111 body = arguments[1];112 }113 }114115 // disambiguate res.send(status) and res.send(status, num)116 if (typeof body === 'number' && arguments.length === 1) {117 // res.send(status) will set status message as text string118 this.get('Content-Type') || this.type('txt');119 this.statusCode = body;120 body = http.STATUS_CODES[body];121 }122123 switch (typeof body) {124 // string defaulting to html125 case 'string':126 if (!this.get('Content-Type')) {127 this.charset = this.charset || 'utf-8';128 this.type('html');129 }130 break;131 case 'boolean':132 case 'number':133 case 'object':134 if (null == body) {135 body = '';136 } else if (Buffer.isBuffer(body)) {137 this.get('Content-Type') || this.type('bin');138 } else {139 return this.json(body);140 }141 break;142 }143144 // write strings in utf-8145 if ('string' === typeof body) {146 encoding = 'utf8';147 type = this.get('Content-Type');148149 // reflect this in content-type150 if ('string' === typeof type) {151 this.set('Content-Type', setCharset(type, 'utf-8'));152 }153 }154155 // populate Content-Length156 if (undefined !== body && !this.get('Content-Length')) {157 len = Buffer.isBuffer(body)158 ? body.length159 : Buffer.byteLength(body, encoding);160 this.set('Content-Length', len);161 }162

Generate ETags for all request responsesDouglas Christopher Wilsonbefore adoptioneaf3318

lines 163–168why, one step back
163 // populate ETag
164 var etag;165 var generateETag = len !== undefined && app.get('etag fn');166 if (typeof generateETag === 'function' && !this.get('ETag')) {167 if ((etag = generateETag(body, encoding))) {168 this.set('ETag', etag);

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 169–182why, one step back
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 body = '';181 }182

Generate ETags for all request responsesDouglas Christopher Wilsonbefore adoptioneaf3318

lines 183–189why, one step back
183 if (req.method === 'HEAD') {
184 // skip body for HEAD185 this.end();186 } else {187 // respond188 this.end(body, encoding);189 }

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 190–428why, one step back
190
191 return this;192};193194/**195 * Send JSON response.196 *197 * Examples:198 *199 * res.json(null);200 * res.json({ user: 'tj' });201 * res.json(500, 'oh noes!');202 * res.json(404, 'I dont have that');203 *204 * @param {Mixed} obj or status205 * @param {Mixed} obj206 * @return {ServerResponse}207 * @api public208 */209210res.json = function(obj){211 // allow status / body212 if (2 == arguments.length) {213 // res.json(body, status) backwards compat214 if ('number' == typeof arguments[1]) {215 this.statusCode = arguments[1];216 if (typeof obj === 'number') {217 deprecate('res.json(obj, status): Use res.json(status, obj) instead');218 } else {219 deprecate('res.json(num, status): Use res.status(status).json(num) instead');220 }221 } else {222 this.statusCode = obj;223 obj = arguments[1];224 }225 }226227 // settings228 var app = this.app;229 var replacer = app.get('json replacer');230 var spaces = app.get('json spaces');231 var body = JSON.stringify(obj, replacer, spaces);232233 // content-type234 this.charset = this.charset || 'utf-8';235 this.get('Content-Type') || this.set('Content-Type', 'application/json');236237 return this.send(body);238};239240/**241 * Send JSON response with JSONP callback support.242 *243 * Examples:244 *245 * res.jsonp(null);246 * res.jsonp({ user: 'tj' });247 * res.jsonp(500, 'oh noes!');248 * res.jsonp(404, 'I dont have that');249 *250 * @param {Mixed} obj or status251 * @param {Mixed} obj252 * @return {ServerResponse}253 * @api public254 */255256res.jsonp = function(obj){257 // allow status / body258 if (2 == arguments.length) {259 // res.json(body, status) backwards compat260 if ('number' == typeof arguments[1]) {261 this.statusCode = arguments[1];262 if (typeof obj === 'number') {263 deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');264 } else {265 deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');266 }267 } else {268 this.statusCode = obj;269 obj = arguments[1];270 }271 }272273 // settings274 var app = this.app;275 var replacer = app.get('json replacer');276 var spaces = app.get('json spaces');277 var body = JSON.stringify(obj, replacer, spaces);278 var callback = this.req.query[app.get('jsonp callback name')];279280 // content-type281 if (!this.get('Content-Type')) {282 this.charset = 'utf-8';283 this.set('X-Content-Type-Options', 'nosniff');284 this.set('Content-Type', 'application/json');285 }286287 // fixup callback288 if (Array.isArray(callback)) {289 callback = callback[0];290 }291292 // jsonp293 if (typeof callback === 'string' && callback.length !== 0) {294 this.charset = 'utf-8';295 this.set('X-Content-Type-Options', 'nosniff');296 this.set('Content-Type', 'text/javascript');297298 // restrict callback charset299 callback = callback.replace(/[^\[\]\w$.]/g, '');300301 // replace chars not allowed in JavaScript that are in JSON302 body = body303 .replace(/\u2028/g, '\\u2028')304 .replace(/\u2029/g, '\\u2029');305306 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"307 // the typeof check is just to reduce client error noise308 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';309 }310311 return this.send(body);312};313314/**315 * Transfer the file at the given `path`.316 *317 * Automatically sets the _Content-Type_ response header field.318 * The callback `fn(err)` is invoked when the transfer is complete319 * or when an error occurs. Be sure to check `res.sentHeader`320 * if you wish to attempt responding, as the header and some data321 * may have already been transferred.322 *323 * Options:324 *325 * - `maxAge` defaulting to 0326 * - `root` root directory for relative filenames327 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them328 *329 * Other options are passed along to `send`.330 *331 * Examples:332 *333 * The following example illustrates how `res.sendfile()` may334 * be used as an alternative for the `static()` middleware for335 * dynamic situations. The code backing `res.sendfile()` is actually336 * the same code, so HTTP cache support etc is identical.337 *338 * app.get('/user/:uid/photos/:file', function(req, res){339 * var uid = req.params.uid340 * , file = req.params.file;341 *342 * req.user.mayViewFilesFrom(uid, function(yes){343 * if (yes) {344 * res.sendfile('/uploads/' + uid + '/' + file);345 * } else {346 * res.send(403, 'Sorry! you cant see that.');347 * }348 * });349 * });350 *351 * @param {String} path352 * @param {Object|Function} options or fn353 * @param {Function} fn354 * @api public355 */356357res.sendfile = function(path, options, fn){358 var self = this359 , req = self.req360 , next = this.req.next361 , options = options || {}362 , done;363364 // support function as second arg365 if ('function' == typeof options) {366 fn = options;367 options = {};368 }369370 // socket errors371 req.socket.on('error', error);372373 // errors374 function error(err) {375 if (done) return;376 done = true;377378 // clean up379 cleanup();380 if (!self.headersSent) self.removeHeader('Content-Disposition');381382 // callback available383 if (fn) return fn(err);384385 // list in limbo if there's no callback386 if (self.headersSent) return;387388 // delegate389 next(err);390 }391392 // streaming393 function stream(stream) {394 if (done) return;395 cleanup();396 if (fn) stream.on('end', fn);397 }398399 // cleanup400 function cleanup() {401 req.socket.removeListener('error', error);402 }403404 // transfer405 var file = send(req, path, options);406 file.on('error', error);407 file.on('directory', next);408 file.on('stream', stream);409 file.pipe(this);410 this.on('finish', cleanup);411};412413/**414 * Transfer the file at the given `path` as an attachment.415 *416 * Optionally providing an alternate attachment `filename`,417 * and optional callback `fn(err)`. The callback is invoked418 * when the data transfer is complete, or when an error has419 * ocurred. Be sure to check `res.headersSent` if you plan to respond.420 *421 * This method uses `res.sendfile()`.422 *423 * @param {String} path424 * @param {String|Function} filename or fn425 * @param {Function} fn426 * @api public427 */428

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption0e56133

line 429why, one step back
429res.download = function download(path, filename, fn) {

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

line 430why, one step back
430 // support function as second arg

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption0e56133

line 431why, one step back
431 if (typeof filename === 'function') {

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 432–436why, one step back
432 fn = filename;
433 filename = null;434 }435436 filename = filename || path;

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption0e56133

lines 437–439why, one step back
437
438 this.set('Content-Disposition', contentDisposition(filename));439

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 440–561why, one step back
440 return this.sendfile(path, fn);
441};442443/**444 * Set _Content-Type_ response header with `type` through `mime.lookup()`445 * when it does not contain "/", or set the Content-Type to `type` otherwise.446 *447 * Examples:448 *449 * res.type('.html');450 * res.type('html');451 * res.type('json');452 * res.type('application/json');453 * res.type('png');454 *455 * @param {String} type456 * @return {ServerResponse} for chaining457 * @api public458 */459460res.contentType =461res.type = function(type){462 return this.set('Content-Type', ~type.indexOf('/')463 ? type464 : mime.lookup(type));465};466467/**468 * Respond to the Acceptable formats using an `obj`469 * of mime-type callbacks.470 *471 * This method uses `req.accepted`, an array of472 * acceptable types ordered by their quality values.473 * When "Accept" is not present the _first_ callback474 * is invoked, otherwise the first match is used. When475 * no match is performed the server responds with476 * 406 "Not Acceptable".477 *478 * Content-Type is set for you, however if you choose479 * you may alter this within the callback using `res.type()`480 * or `res.set('Content-Type', ...)`.481 *482 * res.format({483 * 'text/plain': function(){484 * res.send('hey');485 * },486 *487 * 'text/html': function(){488 * res.send('<p>hey</p>');489 * },490 *491 * 'appliation/json': function(){492 * res.send({ message: 'hey' });493 * }494 * });495 *496 * In addition to canonicalized MIME types you may497 * also use extnames mapped to these types:498 *499 * res.format({500 * text: function(){501 * res.send('hey');502 * },503 *504 * html: function(){505 * res.send('<p>hey</p>');506 * },507 *508 * json: function(){509 * res.send({ message: 'hey' });510 * }511 * });512 *513 * By default Express passes an `Error`514 * with a `.status` of 406 to `next(err)`515 * if a match is not made. If you provide516 * a `.default` callback it will be invoked517 * instead.518 *519 * @param {Object} obj520 * @return {ServerResponse} for chaining521 * @api public522 */523524res.format = function(obj){525 var req = this.req526 , next = req.next;527528 var fn = obj.default;529 if (fn) delete obj.default;530 var keys = Object.keys(obj);531532 var key = req.accepts(keys);533534 this.vary("Accept");535536 if (key) {537 var type = normalizeType(key).value;538 var charset = mime.charsets.lookup(type);539 if (charset) type += '; charset=' + charset;540 this.set('Content-Type', type);541 obj[key](req, this, next);542 } else if (fn) {543 fn();544 } else {545 var err = new Error('Not Acceptable');546 err.status = 406;547 err.types = normalizeTypes(keys).map(function(o){ return o.value });548 next(err);549 }550551 return this;552};553554/**555 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.556 *557 * @param {String} filename558 * @return {ServerResponse}559 * @api public560 */561

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption0e56133

lines 562–568why, one step back
562res.attachment = function attachment(filename) {
563 if (filename) {564 this.type(extname(filename));565 }566567 this.set('Content-Disposition', contentDisposition(filename));568

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 569–627why, one step back
569 return this;
570};571572/**573 * Set header `field` to `val`, or pass574 * an object of header fields.575 *576 * Examples:577 *578 * res.set('Foo', ['bar', 'baz']);579 * res.set('Accept', 'application/json');580 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });581 *582 * Aliased as `res.header()`.583 *584 * @param {String|Object|Array} field585 * @param {String} val586 * @return {ServerResponse} for chaining587 * @api public588 */589590res.set =591res.header = function(field, val){592 if (2 == arguments.length) {593 if (Array.isArray(val)) val = val.map(String);594 else val = String(val);595 this.setHeader(field, val);596 } else {597 for (var key in field) {598 this.set(key, field[key]);599 }600 }601 return this;602};603604/**605 * Get value for header `field`.606 *607 * @param {String} field608 * @return {String}609 * @api public610 */611612res.get = function(field){613 return this.getHeader(field);614};615616/**617 * Clear cookie `name`.618 *619 * @param {String} name620 * @param {Object} options621 * @param {ServerResponse} for chaining622 * @api public623 */624625res.clearCookie = function(name, options){626 var opts = { expires: new Date(1), path: '/' };627 return this.cookie(name, '', options

Fix internal utils.merge deprecation warningsDouglas Christopher Wilsonbefore adoptionaf10438

line 628why, one step back
628 ? merge(opts, options)

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 629–655why, one step back
629 : opts);
630};631632/**633 * Set cookie `name` to `val`, with the given `options`.634 *635 * Options:636 *637 * - `maxAge` max-age in milliseconds, converted to `expires`638 * - `signed` sign the cookie639 * - `path` defaults to "/"640 *641 * Examples:642 *643 * // "Remember Me" for 15 minutes644 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });645 *646 * // save as above647 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })648 *649 * @param {String} name650 * @param {String|Object} val651 * @param {Options} options652 * @api public653 */654655res.cookie = function(name, val, options){

Fix internal utils.merge deprecation warningsDouglas Christopher Wilsonbefore adoptionaf10438

line 656why, one step back
656 options = merge({}, options);

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 657–713why, one step back
657 var secret = this.req.secret;
658 var signed = options.signed;659 if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');660 if ('number' == typeof val) val = val.toString();661 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);662 if (signed) val = 's:' + sign(val, secret);663 if ('maxAge' in options) {664 options.expires = new Date(Date.now() + options.maxAge);665 options.maxAge /= 1000;666 }667 if (null == options.path) options.path = '/';668 this.set('Set-Cookie', cookie.serialize(name, String(val), options));669 return this;670};671672673/**674 * Set the location header to `url`.675 *676 * The given `url` can also be "back", which redirects677 * to the _Referrer_ or _Referer_ headers or "/".678 *679 * Examples:680 *681 * res.location('/foo/bar').;682 * res.location('http://example.com');683 * res.location('../login'); // /blog/post/1 -> /blog/login684 *685 * Mounting:686 *687 * When an application is mounted and `res.location()`688 * is given a path that does _not_ lead with "/" it becomes689 * relative to the mount-point. For example if the application690 * is mounted at "/blog", the following would become "/blog/login".691 *692 * res.location('login');693 *694 * While the leading slash would result in a location of "/login":695 *696 * res.location('/login');697 *698 * @param {String} url699 * @api public700 */701702res.location = function(url){703 var app = this.app704 , req = this.req705 , path;706707 // "back" is an alias for the referrer708 if ('back' == url) url = req.get('Referrer') || '/';709710 // relative711 if (!~url.indexOf('://') && 0 != url.indexOf('//')) {712 // relative to path713 if ('.' == url[0]) {

Fix original URL parsing in res.locationDouglas Christopher Wilsonbefore adoptiona57efea

line 714why, one step back
714 path = parseUrl.original(req).pathname;

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 715–757why, one step back
715 path = path + ('/' == path[path.length - 1] ? '' : '/');
716 url = resolve(path, url);717 // relative to mount-point718 } else if ('/' != url[0]) {719 path = app.path();720 url = path + '/' + url;721 }722 }723724 // Respond725 this.set('Location', url);726 return this;727};728729/**730 * Redirect to the given `url` with optional response `status`731 * defaulting to 302.732 *733 * The resulting `url` is determined by `res.location()`, so734 * it will play nicely with mounted apps, relative paths,735 * `"back"` etc.736 *737 * Examples:738 *739 * res.redirect('/foo/bar');740 * res.redirect('http://example.com');741 * res.redirect(301, 'http://example.com');742 * res.redirect('../login'); // /blog/post/1 -> /blog/login743 *744 * @api public745 */746747res.redirect = function(url){748 var head = 'HEAD' == this.req.method749 , status = 302750 , body;751752 // allow status / url753 if (2 == arguments.length) {754 if ('number' == typeof url) {755 status = url;756 url = arguments[1];757 } else {

Fix typo in res.redirect deprecationBessie Chanbefore adoptionbe478d3

line 758why, one step back
758 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');

3.15.1Douglas Christopher Wilsonbefore adoption9f4968a

lines 759–846why, one step back
759 status = arguments[1];
760 }761 }762763 // Set location header764 this.location(url);765 url = this.get('Location');766767 // Support text/{plain,html} by default768 this.format({769 text: function(){770 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);771 },772773 html: function(){774 var u = escapeHtml(url);775 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';776 },777778 default: function(){779 body = '';780 }781 });782783 // Respond784 this.statusCode = status;785 this.set('Content-Length', Buffer.byteLength(body));786 this.end(head ? null : body);787};788789/**790 * Add `field` to Vary. If already present in the Vary set, then791 * this call is simply ignored.792 *793 * @param {Array|String} field794 * @param {ServerResponse} for chaining795 * @api public796 */797798res.vary = function(field){799 // checks for back-compat800 if (!field) return this;801 if (Array.isArray(field) && !field.length) return this;802803 vary(this, field);804805 return this;806};807808/**809 * Render `view` with the given `options` and optional callback `fn`.810 * When a callback function is given a response will _not_ be made811 * automatically, otherwise a response of _200_ and _text/html_ is given.812 *813 * Options:814 *815 * - `cache` boolean hinting to the engine it should cache816 * - `filename` filename of the view being rendered817 *818 * @param {String} view819 * @param {Object|Function} options or callback function820 * @param {Function} fn821 * @api public822 */823824res.render = function(view, options, fn){825 var self = this826 , options = options || {}827 , req = this.req828 , app = req.app;829830 // support callback function as second arg831 if ('function' == typeof options) {832 fn = options, options = {};833 }834835 // merge res.locals836 options._locals = self.locals;837838 // default callback to respond839 fn = fn || function(err, str){840 if (err) return req.next(err);841 self.send(str);842 };843844 // render845 app.render(view, options, fn);846};