response.js
This file
Path
lib/response.js
778 lines · 18.1 KiB · JavaScript
Last changed by
add deprecation message to res.vary()Douglas Christopher Wilsonbefore adoption381b3b0
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 path = require('path');9var mixin = require('utils-merge');10var sign = require('cookie-signature').sign;11var normalizeType = require('./utils').normalizeType;12var normalizeTypes = require('./utils').normalizeTypes;13var setCharset = require('./utils').setCharset;14var contentDisposition = require('./utils').contentDisposition;15var statusCodes = http.STATUS_CODES;16var cookie = require('cookie');17var send = require('send');18var basename = path.basename;19var extname = path.extname;20var mime = send.mime;21var vary = require('vary');2223/**24 * Response prototype.25 */2627var res = module.exports = {28 __proto__: http.ServerResponse.prototype29};3031/**32 * Set status `code`.33 *34 * @param {Number} code35 * @return {ServerResponse}36 * @api public37 */3839res.status = function(code){40 this.statusCode = code;41 return this;42};4344/**45 * Set Link header field with the given `links`.46 *47 * Examples:48 *49 * res.links({50 * next: 'http://api.example.com/users?page=2',51 * last: 'http://api.example.com/users?page=5'52 * });53 *54 * @param {Object} links55 * @return {ServerResponse}56 * @api public57 */5859res.links = function(links){60 var link = this.get('Link') || '';61 if (link) link += ', ';62 return this.set('Link', link + Object.keys(links).map(function(rel){63 return '<' + links[rel] + '>; rel="' + rel + '"';64 }).join(', '));65};6667/**68 * Send a response.69 *70 * Examples:71 *72 * res.send(new Buffer('wahoo'));73 * res.send({ some: 'json' });74 * res.send('<p>some html</p>');75 * res.send(404, 'Sorry, cant find that');76 * res.send(404);77 *78 * @api public79 */8081res.send = function(body){82 var req = this.req;83 var head = 'HEAD' == req.method;84 var type;85 var encoding;86 var len;8788 // settings89 var app = this.app;9091 // allow status / body92 if (2 == arguments.length) {93 // res.send(body, status) backwards compat94 if ('number' != typeof body && 'number' == typeof arguments[1]) {95 deprecate('res.send(body, status): Use res.send(status, body) instead');96 this.statusCode = arguments[1];97 } else {98 this.statusCode = body;99 body = arguments[1];100 }101 }102103 switch (typeof body) {104 // response status105 case 'number':106 this.get('Content-Type') || this.type('txt');107 this.statusCode = body;108 body = http.STATUS_CODES[body];109 break;110 // string defaulting to html111 case 'string':112 if (!this.get('Content-Type')) this.type('html');113 break;114 case 'boolean':115 case 'object':116 if (null == body) {117 body = '';118 } else if (Buffer.isBuffer(body)) {119 this.get('Content-Type') || this.type('bin');120 } else {121 return this.json(body);122 }123 break;124 }125126 // write strings in utf-8127 if ('string' === typeof body) {128 encoding = 'utf8';129 type = this.get('Content-Type');130131 // reflect this in content-type132 if ('string' === typeof type) {133 this.set('Content-Type', setCharset(type, 'utf-8'));134 }135 }136137 // populate Content-Length138 if (undefined !== body && !this.get('Content-Length')) {139 len = Buffer.isBuffer(body)140 ? body.length141 : Buffer.byteLength(body, encoding);142 this.set('Content-Length', len);143 }144145 // ETag support146 var etag = len !== undefined && app.get('etag fn');147 if (etag && ('GET' === req.method || 'HEAD' === req.method)) {148 if (!this.get('ETag')) {149 etag = etag(body, encoding);150 etag && this.set('ETag', etag);151 }152 }153154 // freshness155 if (req.fresh) this.statusCode = 304;156157 // strip irrelevant headers158 if (204 == this.statusCode || 304 == this.statusCode) {159 this.removeHeader('Content-Type');160 this.removeHeader('Content-Length');161 this.removeHeader('Transfer-Encoding');162 body = '';163 }164165 // respond166 this.end((head ? null : body), encoding);167168 return this;169};170171/**172 * Send JSON response.173 *174 * Examples:175 *176 * res.json(null);177 * res.json({ user: 'tj' });178 * res.json(500, 'oh noes!');179 * res.json(404, 'I dont have that');180 *181 * @api public182 */183184res.json = function(obj){185 // allow status / body186 if (2 == arguments.length) {187 // res.json(body, status) backwards compat188 if ('number' == typeof arguments[1]) {189 this.statusCode = arguments[1];190 if (typeof obj === 'number') {191 deprecate('res.json(obj, status): Use res.json(status, obj) instead');192 } else {193 deprecate('res.json(num, status): Use res.status(status).json(num) instead');194 }195 } else {196 this.statusCode = obj;197 obj = arguments[1];198 }199 }200201 // settings202 var app = this.app;203 var replacer = app.get('json replacer');204 var spaces = app.get('json spaces');205 var body = JSON.stringify(obj, replacer, spaces);206207 // content-type208 this.get('Content-Type') || this.set('Content-Type', 'application/json');209210 return this.send(body);211};212213/**214 * Send JSON response with JSONP callback support.215 *216 * Examples:217 *218 * res.jsonp(null);219 * res.jsonp({ user: 'tj' });220 * res.jsonp(500, 'oh noes!');221 * res.jsonp(404, 'I dont have that');222 *223 * @api public224 */225226res.jsonp = function(obj){227 // allow status / body228 if (2 == arguments.length) {229 // res.json(body, status) backwards compat230 if ('number' == typeof arguments[1]) {231 this.statusCode = arguments[1];232 if (typeof obj === 'number') {233 deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');234 } else {235 deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');236 }237 } else {238 this.statusCode = obj;239 obj = arguments[1];240 }241 }242243 // settings244 var app = this.app;245 var replacer = app.get('json replacer');246 var spaces = app.get('json spaces');247 var body = JSON.stringify(obj, replacer, spaces)248 .replace(/\u2028/g, '\\u2028')249 .replace(/\u2029/g, '\\u2029');250 var callback = this.req.query[app.get('jsonp callback name')];251252 // content-type253 this.get('Content-Type') || this.set('Content-Type', 'application/json');254255 // fixup callback256 if (Array.isArray(callback)) {257 callback = callback[0];258 }259260 // jsonp261 if (callback && 'string' === typeof callback) {262 this.set('Content-Type', 'text/javascript');263 var cb = callback.replace(/[^\[\]\w$.]/g, '');264 body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';265 }266267 return this.send(body);268};269270/**271 * Transfer the file at the given `path`.272 *273 * Automatically sets the _Content-Type_ response header field.274 * The callback `fn(err)` is invoked when the transfer is complete275 * or when an error occurs. Be sure to check `res.sentHeader`276 * if you wish to attempt responding, as the header and some data277 * may have already been transferred.278 *279 * Options:280 *281 * - `maxAge` defaulting to 0282 * - `root` root directory for relative filenames283 * - `hidden` serve hidden files, defaulting to false284 *285 * Other options are passed along to `send`.286 *287 * Examples:288 *289 * The following example illustrates how `res.sendfile()` may290 * be used as an alternative for the `static()` middleware for291 * dynamic situations. The code backing `res.sendfile()` is actually292 * the same code, so HTTP cache support etc is identical.293 *294 * app.get('/user/:uid/photos/:file', function(req, res){295 * var uid = req.params.uid296 * , file = req.params.file;297 *298 * req.user.mayViewFilesFrom(uid, function(yes){299 * if (yes) {300 * res.sendfile('/uploads/' + uid + '/' + file);301 * } else {302 * res.send(403, 'Sorry! you cant see that.');303 * }304 * });305 * });306 *307 * @api public308 */309310res.sendfile = function(path, options, fn){311 options = options || {};312 var self = this;313 var req = self.req;314 var next = this.req.next;315 var done;316317318 // support function as second arg319 if ('function' == typeof options) {320 fn = options;321 options = {};322 }323324 // socket errors325 req.socket.on('error', error);326327 // errors328 function error(err) {329 if (done) return;330 done = true;331332 // clean up333 cleanup();334 if (!self.headersSent) self.removeHeader('Content-Disposition');335336 // callback available337 if (fn) return fn(err);338339 // list in limbo if there's no callback340 if (self.headersSent) return;341342 // delegate343 next(err);344 }345346 // streaming347 function stream(stream) {348 if (done) return;349 cleanup();350 if (fn) stream.on('end', fn);351 }352353 // cleanup354 function cleanup() {355 req.socket.removeListener('error', error);356 }357358 // Back-compat359 options.maxage = options.maxage || options.maxAge || 0;360361 // transfer362 var file = send(req, path, options);363 file.on('error', error);364 file.on('directory', next);365 file.on('stream', stream);366 file.pipe(this);367 this.on('finish', cleanup);368};369370/**371 * Transfer the file at the given `path` as an attachment.372 *373 * Optionally providing an alternate attachment `filename`,374 * and optional callback `fn(err)`. The callback is invoked375 * when the data transfer is complete, or when an error has376 * ocurred. Be sure to check `res.headersSent` if you plan to respond.377 *378 * This method uses `res.sendfile()`.379 *380 * @api public381 */382383res.download = function(path, filename, fn){384 // support function as second arg385 if ('function' == typeof filename) {386 fn = filename;387 filename = null;388 }389390 filename = filename || path;391 this.set('Content-Disposition', contentDisposition(filename));392 return this.sendfile(path, fn);393};394395/**396 * Set _Content-Type_ response header with `type` through `mime.lookup()`397 * when it does not contain "/", or set the Content-Type to `type` otherwise.398 *399 * Examples:400 *401 * res.type('.html');402 * res.type('html');403 * res.type('json');404 * res.type('application/json');405 * res.type('png');406 *407 * @param {String} type408 * @return {ServerResponse} for chaining409 * @api public410 */411412res.contentType =413res.type = function(type){414 return this.set('Content-Type', ~type.indexOf('/')415 ? type416 : mime.lookup(type));417};418419/**420 * Respond to the Acceptable formats using an `obj`421 * of mime-type callbacks.422 *423 * This method uses `req.accepted`, an array of424 * acceptable types ordered by their quality values.425 * When "Accept" is not present the _first_ callback426 * is invoked, otherwise the first match is used. When427 * no match is performed the server responds with428 * 406 "Not Acceptable".429 *430 * Content-Type is set for you, however if you choose431 * you may alter this within the callback using `res.type()`432 * or `res.set('Content-Type', ...)`.433 *434 * res.format({435 * 'text/plain': function(){436 * res.send('hey');437 * },438 *439 * 'text/html': function(){440 * res.send('<p>hey</p>');441 * },442 *443 * 'appliation/json': function(){444 * res.send({ message: 'hey' });445 * }446 * });447 *448 * In addition to canonicalized MIME types you may449 * also use extnames mapped to these types:450 *451 * res.format({452 * text: function(){453 * res.send('hey');454 * },455 *456 * html: function(){457 * res.send('<p>hey</p>');458 * },459 *460 * json: function(){461 * res.send({ message: 'hey' });462 * }463 * });464 *465 * By default Express passes an `Error`466 * with a `.status` of 406 to `next(err)`467 * if a match is not made. If you provide468 * a `.default` callback it will be invoked469 * instead.470 *471 * @param {Object} obj472 * @return {ServerResponse} for chaining473 * @api public474 */475476res.format = function(obj){477 var req = this.req;478 var next = req.next;479480 var fn = obj.default;481 if (fn) delete obj.default;482 var keys = Object.keys(obj);483484 var key = req.accepts(keys);485486 this.vary("Accept");487488 if (key) {489 this.set('Content-Type', normalizeType(key).value);490 obj[key](req, this, next);491 } else if (fn) {492 fn();493 } else {494 var err = new Error('Not Acceptable');495 err.status = 406;496 err.types = normalizeTypes(keys).map(function(o){ return o.value });497 next(err);498 }499500 return this;501};502503/**504 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.505 *506 * @param {String} filename507 * @return {ServerResponse}508 * @api public509 */510511res.attachment = function(filename){512 if (filename) this.type(extname(filename));513 this.set('Content-Disposition', contentDisposition(filename));514 return this;515};516517/**518 * Set header `field` to `val`, or pass519 * an object of header fields.520 *521 * Examples:522 *523 * res.set('Foo', ['bar', 'baz']);524 * res.set('Accept', 'application/json');525 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });526 *527 * Aliased as `res.header()`.528 *529 * @param {String|Object|Array} field530 * @param {String} val531 * @return {ServerResponse} for chaining532 * @api public533 */534535res.set =536res.header = function(field, val){537 if (2 == arguments.length) {538 if (Array.isArray(val)) val = val.map(String);539 else val = String(val);540 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {541 var charset = mime.charsets.lookup(val.split(';')[0]);542 if (charset) val += '; charset=' + charset.toLowerCase();543 }544 this.setHeader(field, val);545 } else {546 for (var key in field) {547 this.set(key, field[key]);548 }549 }550 return this;551};552553/**554 * Get value for header `field`.555 *556 * @param {String} field557 * @return {String}558 * @api public559 */560561res.get = function(field){562 return this.getHeader(field);563};564565/**566 * Clear cookie `name`.567 *568 * @param {String} name569 * @param {Object} options570 * @param {ServerResponse} for chaining571 * @api public572 */573574res.clearCookie = function(name, options){575 var opts = { expires: new Date(1), path: '/' };576 return this.cookie(name, '', options577 ? mixin(opts, options)578 : opts);579};580581/**582 * Set cookie `name` to `val`, with the given `options`.583 *584 * Options:585 *586 * - `maxAge` max-age in milliseconds, converted to `expires`587 * - `signed` sign the cookie588 * - `path` defaults to "/"589 *590 * Examples:591 *592 * // "Remember Me" for 15 minutes593 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });594 *595 * // save as above596 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })597 *598 * @param {String} name599 * @param {String|Object} val600 * @param {Options} options601 * @api public602 */603604res.cookie = function(name, val, options){605 options = mixin({}, options);606 var secret = this.req.secret;607 var signed = options.signed;608 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');609 if ('number' == typeof val) val = val.toString();610 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);611 if (signed) val = 's:' + sign(val, secret);612 if ('maxAge' in options) {613 options.expires = new Date(Date.now() + options.maxAge);614 options.maxAge /= 1000;615 }616 if (null == options.path) options.path = '/';617 var headerVal = cookie.serialize(name, String(val), options);618619 // supports multiple 'res.cookie' calls by getting previous value620 var prev = this.get('Set-Cookie');621 if (prev) {622 if (Array.isArray(prev)) {623 headerVal = prev.concat(headerVal);624 } else {625 headerVal = [prev, headerVal];626 }627 }628 this.set('Set-Cookie', headerVal);629 return this;630};631632633/**634 * Set the location header to `url`.635 *636 * The given `url` can also be "back", which redirects637 * to the _Referrer_ or _Referer_ headers or "/".638 *639 * Examples:640 *641 * res.location('/foo/bar').;642 * res.location('http://example.com');643 * res.location('../login');644 *645 * @param {String} url646 * @api public647 */648649res.location = function(url){650 var req = this.req;651652 // "back" is an alias for the referrer653 if ('back' == url) url = req.get('Referrer') || '/';654655 // Respond656 this.set('Location', url);657 return this;658};659660/**661 * Redirect to the given `url` with optional response `status`662 * defaulting to 302.663 *664 * The resulting `url` is determined by `res.location()`, so665 * it will play nicely with mounted apps, relative paths,666 * `"back"` etc.667 *668 * Examples:669 *670 * res.redirect('/foo/bar');671 * res.redirect('http://example.com');672 * res.redirect(301, 'http://example.com');673 * res.redirect('http://example.com', 301);674 * res.redirect('../login'); // /blog/post/1 -> /blog/login675 *676 * @param {String} url677 * @param {Number} code678 * @api public679 */680681res.redirect = function(url){682 var head = 'HEAD' == this.req.method;683 var status = 302;684 var body;685686 // allow status / url687 if (2 == arguments.length) {688 if ('number' == typeof url) {689 status = url;690 url = arguments[1];691 } else {692 status = arguments[1];693 }694 }695696 // Set location header697 this.location(url);698 url = this.get('Location');699700 // Support text/{plain,html} by default701 this.format({702 text: function(){703 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);704 },705706 html: function(){707 var u = escapeHtml(url);708 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';709 },710711 default: function(){712 body = '';713 }714 });715716 // Respond717 this.statusCode = status;718 this.set('Content-Length', Buffer.byteLength(body));719 this.end(head ? null : body);720};721722/**723 * Add `field` to Vary. If already present in the Vary set, then724 * this call is simply ignored.725 *726 * @param {Array|String} field727 * @param {ServerResponse} for chaining728 * @api public729 */730731res.vary = function(field){732 // checks for back-compat733 if (!field || (Array.isArray(field) && !field.length)) {734 deprecate('res.vary(): Provide a field name');735 return this;736 }737738 vary(this, field);739740 return this;741};742743/**744 * Render `view` with the given `options` and optional callback `fn`.745 * When a callback function is given a response will _not_ be made746 * automatically, otherwise a response of _200_ and _text/html_ is given.747 *748 * Options:749 *750 * - `cache` boolean hinting to the engine it should cache751 * - `filename` filename of the view being rendered752 *753 * @api public754 */755756res.render = function(view, options, fn){757 options = options || {};758 var self = this;759 var req = this.req;760 var app = req.app;761762 // support callback function as second arg763 if ('function' == typeof options) {764 fn = options, options = {};765 }766767 // merge res.locals768 options._locals = self.locals;769770 // default callback to respond771 fn = fn || function(err, str){772 if (err) return req.next(err);773 self.send(str);774 };775776 // render777 app.render(view, options, fn);778};