response.js
This file
Path
lib/response.js
956 lines · 22.4 KiB · JavaScript
Last changed by
Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
History of this fileTake it
1/**2 * Module dependencies.3 */45var deprecate = require('depd')('express');6var escapeHtml = require('escape-html');7var http = require('http');8var isAbsolute = require('./utils').isAbsolute;9var path = require('path');10var mixin = require('utils-merge');11var sign = require('cookie-signature').sign;12var normalizeType = require('./utils').normalizeType;13var normalizeTypes = require('./utils').normalizeTypes;14var setCharset = require('./utils').setCharset;15var contentDisposition = require('./utils').contentDisposition;16var statusCodes = http.STATUS_CODES;17var cookie = require('cookie');18var send = require('send');19var basename = path.basename;20var extname = path.extname;21var mime = send.mime;22var resolve = path.resolve;23var vary = require('vary');2425/**26 * Response prototype.27 */2829var res = module.exports = {30 __proto__: http.ServerResponse.prototype31};3233/**34 * Set status `code`.35 *36 * @param {Number} code37 * @return {ServerResponse}38 * @api public39 */4041res.status = function(code){42 this.statusCode = code;43 return this;44};4546/**47 * Set Link header field with the given `links`.48 *49 * Examples:50 *51 * res.links({52 * next: 'http://api.example.com/users?page=2',53 * last: 'http://api.example.com/users?page=5'54 * });55 *56 * @param {Object} links57 * @return {ServerResponse}58 * @api public59 */6061res.links = function(links){62 var link = this.get('Link') || '';63 if (link) link += ', ';64 return this.set('Link', link + Object.keys(links).map(function(rel){65 return '<' + links[rel] + '>; rel="' + rel + '"';66 }).join(', '));67};6869/**70 * Send a response.71 *72 * Examples:73 *74 * res.send(new Buffer('wahoo'));75 * res.send({ some: 'json' });76 * res.send('<p>some html</p>');77 *78 * @param {string|number|boolean|object|Buffer} body79 * @api public80 */8182res.send = function send(body) {83 var chunk = body;84 var encoding;85 var len;86 var req = this.req;87 var type;8889 // settings90 var app = this.app;9192 // allow status / body93 if (arguments.length === 2) {94 // res.send(body, status) backwards compat95 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {96 deprecate('res.send(body, status): Use res.status(status).send(body) instead');97 this.statusCode = arguments[1];98 } else {99 deprecate('res.send(status, body): Use res.status(status).send(body) instead');100 this.statusCode = arguments[0];101 chunk = arguments[1];102 }103 }104105 // disambiguate res.send(status) and res.send(status, num)106 if (typeof chunk === 'number' && arguments.length === 1) {107 // res.send(status) will set status message as text string108 if (!this.get('Content-Type')) {109 this.type('txt');110 }111112 deprecate('res.send(status): Use res.status(status).end() instead');113 this.statusCode = chunk;114 chunk = http.STATUS_CODES[chunk];115 }116117 switch (typeof chunk) {118 // string defaulting to html119 case 'string':120 if (!this.get('Content-Type')) {121 this.type('html');122 }123 break;124 case 'boolean':125 case 'number':126 case 'object':127 if (chunk === null) {128 chunk = '';129 } else if (Buffer.isBuffer(chunk)) {130 if (!this.get('Content-Type')) {131 this.type('bin');132 }133 } else {134 return this.json(chunk);135 }136 break;137 }138139 // write strings in utf-8140 if (typeof chunk === 'string') {141 encoding = 'utf8';142 type = this.get('Content-Type');143144 // reflect this in content-type145 if (typeof type === 'string') {146 this.set('Content-Type', setCharset(type, 'utf-8'));147 }148 }149150 // populate Content-Length151 if (chunk !== undefined) {152 if (!Buffer.isBuffer(chunk)) {153 // convert chunk to Buffer; saves later double conversions154 chunk = new Buffer(chunk, encoding);155 encoding = undefined;156 }157158 len = chunk.length;159 this.set('Content-Length', len);160 }161162 // method check163 var isHead = req.method === 'HEAD';164165 // ETag support166 if (len !== undefined && (isHead || req.method === 'GET')) {167 var etag = app.get('etag fn');168 if (etag && !this.get('ETag')) {169 etag = etag(chunk, encoding);170 etag && this.set('ETag', etag);171 }172 }173174 // freshness175 if (req.fresh) this.statusCode = 304;176177 // strip irrelevant headers178 if (204 == this.statusCode || 304 == this.statusCode) {179 this.removeHeader('Content-Type');180 this.removeHeader('Content-Length');181 this.removeHeader('Transfer-Encoding');182 chunk = '';183 }184185 // skip body for HEAD186 if (isHead) {187 this.end();188 }189190 // respond191 this.end(chunk, encoding);192193 return this;194};195196/**197 * Send JSON response.198 *199 * Examples:200 *201 * res.json(null);202 * res.json({ user: 'tj' });203 *204 * @param {string|number|boolean|object} obj205 * @api public206 */207208res.json = function json(obj) {209 var val = obj;210211 // allow status / body212 if (arguments.length === 2) {213 // res.json(body, status) backwards compat214 if (typeof arguments[1] === 'number') {215 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');216 this.statusCode = arguments[1];217 } else {218 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');219 this.statusCode = arguments[0];220 val = arguments[1];221 }222 }223224 // settings225 var app = this.app;226 var replacer = app.get('json replacer');227 var spaces = app.get('json spaces');228 var body = JSON.stringify(val, replacer, spaces);229230 // content-type231 if (!this.get('Content-Type')) {232 this.set('Content-Type', 'application/json');233 }234235 return this.send(body);236};237238/**239 * Send JSON response with JSONP callback support.240 *241 * Examples:242 *243 * res.jsonp(null);244 * res.jsonp({ user: 'tj' });245 *246 * @param {string|number|boolean|object} obj247 * @api public248 */249250res.jsonp = function jsonp(obj) {251 var val = obj;252253 // allow status / body254 if (arguments.length === 2) {255 // res.json(body, status) backwards compat256 if (typeof arguments[1] === 'number') {257 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');258 this.statusCode = arguments[1];259 } else {260 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');261 this.statusCode = arguments[0];262 val = arguments[1];263 }264 }265266 // settings267 var app = this.app;268 var replacer = app.get('json replacer');269 var spaces = app.get('json spaces');270 var body = JSON.stringify(val, replacer, spaces);271 var callback = this.req.query[app.get('jsonp callback name')];272273 // content-type274 if (!this.get('Content-Type')) {275 this.set('X-Content-Type-Options', 'nosniff');276 this.set('Content-Type', 'application/json');277 }278279 // fixup callback280 if (Array.isArray(callback)) {281 callback = callback[0];282 }283284 // jsonp285 if (typeof callback === 'string' && callback.length !== 0) {286 this.charset = 'utf-8';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 // replace chars not allowed in JavaScript that are in JSON294 body = body295 .replace(/\u2028/g, '\\u2028')296 .replace(/\u2029/g, '\\u2029');297298 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"299 // the typeof check is just to reduce client error noise300 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';301 }302303 return this.send(body);304};305306/**307 * Transfer the file at the given `path`.308 *309 * Automatically sets the _Content-Type_ response header field.310 * The callback `fn(err)` is invoked when the transfer is complete311 * or when an error occurs. Be sure to check `res.sentHeader`312 * if you wish to attempt responding, as the header and some data313 * may have already been transferred.314 *315 * Options:316 *317 * - `maxAge` defaulting to 0 (can be string converted by `ms`)318 * - `root` root directory for relative filenames319 * - `headers` object of headers to serve with file320 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them321 *322 * Other options are passed along to `send`.323 *324 * Examples:325 *326 * The following example illustrates how `res.sendFile()` may327 * be used as an alternative for the `static()` middleware for328 * dynamic situations. The code backing `res.sendFile()` is actually329 * the same code, so HTTP cache support etc is identical.330 *331 * app.get('/user/:uid/photos/:file', function(req, res){332 * var uid = req.params.uid333 * , file = req.params.file;334 *335 * req.user.mayViewFilesFrom(uid, function(yes){336 * if (yes) {337 * res.sendFile('/uploads/' + uid + '/' + file);338 * } else {339 * res.send(403, 'Sorry! you cant see that.');340 * }341 * });342 * });343 *344 * @api public345 */346347res.sendFile = function sendFile(path, options, fn) {348 var done;349 var req = this.req;350 var next = req.next;351352 if (!path) {353 throw new TypeError('path argument is required to res.sendFile');354 }355356 // support function as second arg357 if (typeof options === 'function') {358 fn = options;359 options = {};360 }361362 options = options || {};363364 if (!options.root && !isAbsolute(path)) {365 throw new TypeError('path must be absolute or specify root to res.sendFile');366 }367368 // socket errors369 req.socket.on('error', onerror);370371 // errors372 function onerror(err) {373 if (done) return;374 done = true;375376 // clean up377 cleanup();378379 // callback available380 if (fn) return fn(err);381382 // delegate383 next(err);384 }385386 // streaming387 function onstream(stream) {388 if (done) return;389 cleanup();390 if (fn) stream.on('end', fn);391 }392393 // cleanup394 function cleanup() {395 req.socket.removeListener('error', onerror);396 }397398 // transfer399 var pathname = encodeURI(path);400 var file = send(req, pathname, options);401 file.on('error', onerror);402 file.on('directory', next);403 file.on('stream', onstream);404405 if (options.headers) {406 // set headers on successful transfer407 file.on('headers', function headers(res) {408 var obj = options.headers;409 var keys = Object.keys(obj);410411 for (var i = 0; i < keys.length; i++) {412 var k = keys[i];413 res.setHeader(k, obj[k]);414 }415 });416 }417418 // pipe419 file.pipe(this);420 this.on('finish', cleanup);421};422423/**424 * Transfer the file at the given `path`.425 *426 * Automatically sets the _Content-Type_ response header field.427 * The callback `fn(err)` is invoked when the transfer is complete428 * or when an error occurs. Be sure to check `res.sentHeader`429 * if you wish to attempt responding, as the header and some data430 * may have already been transferred.431 *432 * Options:433 *434 * - `maxAge` defaulting to 0 (can be string converted by `ms`)435 * - `root` root directory for relative filenames436 * - `headers` object of headers to serve with file437 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them438 *439 * Other options are passed along to `send`.440 *441 * Examples:442 *443 * The following example illustrates how `res.sendfile()` may444 * be used as an alternative for the `static()` middleware for445 * dynamic situations. The code backing `res.sendfile()` is actually446 * the same code, so HTTP cache support etc is identical.447 *448 * app.get('/user/:uid/photos/:file', function(req, res){449 * var uid = req.params.uid450 * , file = req.params.file;451 *452 * req.user.mayViewFilesFrom(uid, function(yes){453 * if (yes) {454 * res.sendfile('/uploads/' + uid + '/' + file);455 * } else {456 * res.send(403, 'Sorry! you cant see that.');457 * }458 * });459 * });460 *461 * @api public462 */463464res.sendfile = function(path, options, fn){465 options = options || {};466 var self = this;467 var req = self.req;468 var next = this.req.next;469 var done;470471472 // support function as second arg473 if ('function' == typeof options) {474 fn = options;475 options = {};476 }477478 // socket errors479 req.socket.on('error', error);480481 // errors482 function error(err) {483 if (done) return;484 done = true;485486 // clean up487 cleanup();488489 // callback available490 if (fn) return fn(err);491492 // delegate493 next(err);494 }495496 // streaming497 function stream(stream) {498 if (done) return;499 cleanup();500 if (fn) stream.on('end', fn);501 }502503 // cleanup504 function cleanup() {505 req.socket.removeListener('error', error);506 }507508 // transfer509 var file = send(req, path, options);510 file.on('error', error);511 file.on('directory', next);512 file.on('stream', stream);513514 if (options.headers) {515 // set headers on successful transfer516 file.on('headers', function headers(res) {517 var obj = options.headers;518 var keys = Object.keys(obj);519520 for (var i = 0; i < keys.length; i++) {521 var k = keys[i];522 res.setHeader(k, obj[k]);523 }524 });525 }526527 // pipe528 file.pipe(this);529 this.on('finish', cleanup);530};531532res.sendfile = deprecate.function(res.sendfile,533 'res.sendfile: Use res.sendFile instead');534535/**536 * Transfer the file at the given `path` as an attachment.537 *538 * Optionally providing an alternate attachment `filename`,539 * and optional callback `fn(err)`. The callback is invoked540 * when the data transfer is complete, or when an error has541 * ocurred. Be sure to check `res.headersSent` if you plan to respond.542 *543 * This method uses `res.sendfile()`.544 *545 * @api public546 */547548res.download = function download(path, filename, fn) {549 // support function as second arg550 if (typeof filename === 'function') {551 fn = filename;552 filename = null;553 }554555 filename = filename || path;556557 // set Content-Disposition when file is sent558 var headers = {559 'Content-Disposition': contentDisposition(filename)560 };561562 // Resolve the full path for sendFile563 var fullPath = resolve(path);564565 return this.sendFile(fullPath, { headers: headers }, fn);566};567568/**569 * Set _Content-Type_ response header with `type` through `mime.lookup()`570 * when it does not contain "/", or set the Content-Type to `type` otherwise.571 *572 * Examples:573 *574 * res.type('.html');575 * res.type('html');576 * res.type('json');577 * res.type('application/json');578 * res.type('png');579 *580 * @param {String} type581 * @return {ServerResponse} for chaining582 * @api public583 */584585res.contentType =586res.type = function(type){587 return this.set('Content-Type', ~type.indexOf('/')588 ? type589 : mime.lookup(type));590};591592/**593 * Respond to the Acceptable formats using an `obj`594 * of mime-type callbacks.595 *596 * This method uses `req.accepted`, an array of597 * acceptable types ordered by their quality values.598 * When "Accept" is not present the _first_ callback599 * is invoked, otherwise the first match is used. When600 * no match is performed the server responds with601 * 406 "Not Acceptable".602 *603 * Content-Type is set for you, however if you choose604 * you may alter this within the callback using `res.type()`605 * or `res.set('Content-Type', ...)`.606 *607 * res.format({608 * 'text/plain': function(){609 * res.send('hey');610 * },611 *612 * 'text/html': function(){613 * res.send('<p>hey</p>');614 * },615 *616 * 'appliation/json': function(){617 * res.send({ message: 'hey' });618 * }619 * });620 *621 * In addition to canonicalized MIME types you may622 * also use extnames mapped to these types:623 *624 * res.format({625 * text: function(){626 * res.send('hey');627 * },628 *629 * html: function(){630 * res.send('<p>hey</p>');631 * },632 *633 * json: function(){634 * res.send({ message: 'hey' });635 * }636 * });637 *638 * By default Express passes an `Error`639 * with a `.status` of 406 to `next(err)`640 * if a match is not made. If you provide641 * a `.default` callback it will be invoked642 * instead.643 *644 * @param {Object} obj645 * @return {ServerResponse} for chaining646 * @api public647 */648649res.format = function(obj){650 var req = this.req;651 var next = req.next;652653 var fn = obj.default;654 if (fn) delete obj.default;655 var keys = Object.keys(obj);656657 var key = req.accepts(keys);658659 this.vary("Accept");660661 if (key) {662 this.set('Content-Type', normalizeType(key).value);663 obj[key](req, this, next);664 } else if (fn) {665 fn();666 } else {667 var err = new Error('Not Acceptable');668 err.status = 406;669 err.types = normalizeTypes(keys).map(function(o){ return o.value });670 next(err);671 }672673 return this;674};675676/**677 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.678 *679 * @param {String} filename680 * @return {ServerResponse}681 * @api public682 */683684res.attachment = function(filename){685 if (filename) this.type(extname(filename));686 this.set('Content-Disposition', contentDisposition(filename));687 return this;688};689690/**691 * Set header `field` to `val`, or pass692 * an object of header fields.693 *694 * Examples:695 *696 * res.set('Foo', ['bar', 'baz']);697 * res.set('Accept', 'application/json');698 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });699 *700 * Aliased as `res.header()`.701 *702 * @param {String|Object|Array} field703 * @param {String} val704 * @return {ServerResponse} for chaining705 * @api public706 */707708res.set =709res.header = function header(field, val) {710 if (arguments.length === 2) {711 if (Array.isArray(val)) val = val.map(String);712 else val = String(val);713 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {714 var charset = mime.charsets.lookup(val.split(';')[0]);715 if (charset) val += '; charset=' + charset.toLowerCase();716 }717 this.setHeader(field, val);718 } else {719 for (var key in field) {720 this.set(key, field[key]);721 }722 }723 return this;724};725726/**727 * Get value for header `field`.728 *729 * @param {String} field730 * @return {String}731 * @api public732 */733734res.get = function(field){735 return this.getHeader(field);736};737738/**739 * Clear cookie `name`.740 *741 * @param {String} name742 * @param {Object} options743 * @return {ServerResponse} for chaining744 * @api public745 */746747res.clearCookie = function(name, options){748 var opts = { expires: new Date(1), path: '/' };749 return this.cookie(name, '', options750 ? mixin(opts, options)751 : opts);752};753754/**755 * Set cookie `name` to `val`, with the given `options`.756 *757 * Options:758 *759 * - `maxAge` max-age in milliseconds, converted to `expires`760 * - `signed` sign the cookie761 * - `path` defaults to "/"762 *763 * Examples:764 *765 * // "Remember Me" for 15 minutes766 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });767 *768 * // save as above769 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })770 *771 * @param {String} name772 * @param {String|Object} val773 * @param {Options} options774 * @return {ServerResponse} for chaining775 * @api public776 */777778res.cookie = function(name, val, options){779 options = mixin({}, options);780 var secret = this.req.secret;781 var signed = options.signed;782 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');783 if ('number' == typeof val) val = val.toString();784 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);785 if (signed) val = 's:' + sign(val, secret);786 if ('maxAge' in options) {787 options.expires = new Date(Date.now() + options.maxAge);788 options.maxAge /= 1000;789 }790 if (null == options.path) options.path = '/';791 var headerVal = cookie.serialize(name, String(val), options);792793 // supports multiple 'res.cookie' calls by getting previous value794 var prev = this.get('Set-Cookie');795 if (prev) {796 if (Array.isArray(prev)) {797 headerVal = prev.concat(headerVal);798 } else {799 headerVal = [prev, headerVal];800 }801 }802 this.set('Set-Cookie', headerVal);803 return this;804};805806807/**808 * Set the location header to `url`.809 *810 * The given `url` can also be "back", which redirects811 * to the _Referrer_ or _Referer_ headers or "/".812 *813 * Examples:814 *815 * res.location('/foo/bar').;816 * res.location('http://example.com');817 * res.location('../login');818 *819 * @param {String} url820 * @return {ServerResponse} for chaining821 * @api public822 */823824res.location = function(url){825 var req = this.req;826827 // "back" is an alias for the referrer828 if ('back' == url) url = req.get('Referrer') || '/';829830 // Respond831 this.set('Location', url);832 return this;833};834835/**836 * Redirect to the given `url` with optional response `status`837 * defaulting to 302.838 *839 * The resulting `url` is determined by `res.location()`, so840 * it will play nicely with mounted apps, relative paths,841 * `"back"` etc.842 *843 * Examples:844 *845 * res.redirect('/foo/bar');846 * res.redirect('http://example.com');847 * res.redirect(301, 'http://example.com');848 * res.redirect('../login'); // /blog/post/1 -> /blog/login849 *850 * @api public851 */852853res.redirect = function redirect(url) {854 var address = url;855 var body;856 var status = 302;857858 // allow status / url859 if (arguments.length === 2) {860 if (typeof arguments[0] === 'number') {861 status = arguments[0];862 address = arguments[1];863 } else {864 deprecate('res.redirect(ur, status): Use res.redirect(status, url) instead');865 status = arguments[1];866 }867 }868869 // Set location header870 this.location(address);871 address = this.get('Location');872873 // Support text/{plain,html} by default874 this.format({875 text: function(){876 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);877 },878879 html: function(){880 var u = escapeHtml(url);881 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';882 },883884 default: function(){885 body = '';886 }887 });888889 // Respond890 this.statusCode = status;891 this.set('Content-Length', Buffer.byteLength(body));892893 if (this.req.method === 'HEAD') {894 this.end();895 }896897 this.end(body);898};899900/**901 * Add `field` to Vary. If already present in the Vary set, then902 * this call is simply ignored.903 *904 * @param {Array|String} field905 * @return {ServerResponse} for chaining906 * @api public907 */908909res.vary = function(field){910 // checks for back-compat911 if (!field || (Array.isArray(field) && !field.length)) {912 deprecate('res.vary(): Provide a field name');913 return this;914 }915916 vary(this, field);917918 return this;919};920921/**922 * Render `view` with the given `options` and optional callback `fn`.923 * When a callback function is given a response will _not_ be made924 * automatically, otherwise a response of _200_ and _text/html_ is given.925 *926 * Options:927 *928 * - `cache` boolean hinting to the engine it should cache929 * - `filename` filename of the view being rendered930 *931 * @api public932 */933934res.render = function(view, options, fn){935 options = options || {};936 var self = this;937 var req = this.req;938 var app = req.app;939940 // support callback function as second arg941 if ('function' == typeof options) {942 fn = options, options = {};943 }944945 // merge res.locals946 options._locals = self.locals;947948 // default callback to respond949 fn = fn || function(err, str){950 if (err) return req.next(err);951 self.send(str);952 };953954 // render955 app.render(view, options, fn);956};