response.js
This file
Path
lib/response.js
760 lines · 17.5 KiB · JavaScript
Last changed by
refactorTJ Holowaychukbefore adoption8ad8cb9
History of this fileTake it
1/**2 * Module dependencies.3 */45var http = require('http')6 , path = require('path')7 , connect = require('connect')8 , utils = connect.utils9 , sign = require('cookie-signature').sign10 , normalizeType = require('./utils').normalizeType11 , normalizeTypes = require('./utils').normalizeTypes12 , etag = require('./utils').etag13 , statusCodes = http.STATUS_CODES14 , cookie = require('cookie')15 , send = require('send')16 , mime = connect.mime17 , basename = path.basename18 , extname = path.extname19 , join = path.join;2021/**22 * Response prototype.23 */2425var res = module.exports = {26 __proto__: http.ServerResponse.prototype27};2829/**30 * Set status `code`.31 *32 * @param {Number} code33 * @return {ServerResponse}34 * @api public35 */3637res.status = function(code){38 this.statusCode = code;39 return this;40};4142/**43 * Set Link header field with the given `links`.44 *45 * Examples:46 *47 * res.links({48 * next: 'http://api.example.com/users?page=2',49 * last: 'http://api.example.com/users?page=5'50 * });51 *52 * @param {Object} links53 * @return {ServerResponse}54 * @api public55 */5657res.links = function(links){58 return this.set('Link', Object.keys(links).map(function(rel){59 return '<' + links[rel] + '>; rel="' + rel + '"';60 }).join(', '));61};6263/**64 * Send a response.65 *66 * Examples:67 *68 * res.send(new Buffer('wahoo'));69 * res.send({ some: 'json' });70 * res.send('<p>some html</p>');71 * res.send(404, 'Sorry, cant find that');72 * res.send(404);73 *74 * @param {Mixed} body or status75 * @param {Mixed} body76 * @return {ServerResponse}77 * @api public78 */7980res.send = function(body){81 var req = this.req;82 var head = 'HEAD' == req.method;83 var len;8485 // settings86 var app = this.app;8788 // allow status / body89 if (2 == arguments.length) {90 // res.send(body, status) backwards compat91 if ('number' != typeof body && 'number' == typeof arguments[1]) {92 this.statusCode = arguments[1];93 } else {94 this.statusCode = body;95 body = arguments[1];96 }97 }9899 switch (typeof body) {100 // response status101 case 'number':102 this.get('Content-Type') || this.type('txt');103 this.statusCode = body;104 body = http.STATUS_CODES[body];105 break;106 // string defaulting to html107 case 'string':108 if (!this.get('Content-Type')) {109 this.charset = this.charset || 'utf-8';110 this.type('html');111 }112 break;113 case 'boolean':114 case 'object':115 if (null == body) {116 body = '';117 } else if (Buffer.isBuffer(body)) {118 this.get('Content-Type') || this.type('bin');119 } else {120 return this.json(body);121 }122 break;123 }124125 // populate Content-Length126 if (undefined !== body && !this.get('Content-Length')) {127 this.set('Content-Length', len = Buffer.isBuffer(body)128 ? body.length129 : Buffer.byteLength(body));130 }131132 // ETag support133 // TODO: W/ support134 if (app.settings.etag && len > 1024 && 'GET' == req.method) {135 if (!this.get('ETag')) {136 this.set('ETag', etag(body));137 }138 }139140 // freshness141 if (req.fresh) this.statusCode = 304;142143 // strip irrelevant headers144 if (204 == this.statusCode || 304 == this.statusCode) {145 this.removeHeader('Content-Type');146 this.removeHeader('Content-Length');147 this.removeHeader('Transfer-Encoding');148 body = '';149 }150151 // respond152 this.end(head ? null : body);153 return this;154};155156/**157 * Send JSON response.158 *159 * Examples:160 *161 * res.json(null);162 * res.json({ user: 'tj' });163 * res.json(500, 'oh noes!');164 * res.json(404, 'I dont have that');165 *166 * @param {Mixed} obj or status167 * @param {Mixed} obj168 * @return {ServerResponse}169 * @api public170 */171172res.json = function(obj){173 // allow status / body174 if (2 == arguments.length) {175 // res.json(body, status) backwards compat176 if ('number' == typeof arguments[1]) {177 this.statusCode = arguments[1];178 } else {179 this.statusCode = obj;180 obj = arguments[1];181 }182 }183184 // settings185 var app = this.app;186 var replacer = app.get('json replacer');187 var spaces = app.get('json spaces');188 var body = JSON.stringify(obj, replacer, spaces);189190 // content-type191 this.get('Content-Type') || this.set('Content-Type', 'application/json');192193 return this.send(body);194};195196/**197 * Send JSON response with JSONP callback support.198 *199 * Examples:200 *201 * res.jsonp(null);202 * res.jsonp({ user: 'tj' });203 * res.jsonp(500, 'oh noes!');204 * res.jsonp(404, 'I dont have that');205 *206 * @param {Mixed} obj or status207 * @param {Mixed} obj208 * @return {ServerResponse}209 * @api public210 */211212res.jsonp = function(obj){213 // allow status / body214 if (2 == arguments.length) {215 // res.json(body, status) backwards compat216 if ('number' == typeof arguments[1]) {217 this.statusCode = arguments[1];218 } else {219 this.statusCode = obj;220 obj = 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(obj, replacer, spaces)229 .replace(/\u2028/g, '\\u2028')230 .replace(/\u2029/g, '\\u2029');231 var callback = this.req.query[app.get('jsonp callback name')];232233 // content-type234 this.charset = this.charset || 'utf-8';235 this.set('Content-Type', 'application/json');236237 // jsonp238 if (callback) {239 if (callback instanceof Array) callback = callback[0];240 this.set('Content-Type', 'text/javascript');241 var cb = callback.replace(/[^\[\]\w$.]/g, '');242 body = cb + ' && ' + cb + '(' + body + ');';243 }244245 return this.send(body);246};247248/**249 * Transfer the file at the given `path`.250 *251 * Automatically sets the _Content-Type_ response header field.252 * The callback `fn(err)` is invoked when the transfer is complete253 * or when an error occurs. Be sure to check `res.sentHeader`254 * if you wish to attempt responding, as the header and some data255 * may have already been transferred.256 *257 * Options:258 *259 * - `maxAge` defaulting to 0260 * - `root` root directory for relative filenames261 *262 * Examples:263 *264 * The following example illustrates how `res.sendfile()` may265 * be used as an alternative for the `static()` middleware for266 * dynamic situations. The code backing `res.sendfile()` is actually267 * the same code, so HTTP cache support etc is identical.268 *269 * app.get('/user/:uid/photos/:file', function(req, res){270 * var uid = req.params.uid271 * , file = req.params.file;272 *273 * req.user.mayViewFilesFrom(uid, function(yes){274 * if (yes) {275 * res.sendfile('/uploads/' + uid + '/' + file);276 * } else {277 * res.send(403, 'Sorry! you cant see that.');278 * }279 * });280 * });281 *282 * @param {String} path283 * @param {Object|Function} options or fn284 * @param {Function} fn285 * @api public286 */287288res.sendfile = function(path, options, fn){289 var self = this290 , req = self.req291 , next = this.req.next292 , options = options || {}293 , done;294295 // support function as second arg296 if ('function' == typeof options) {297 fn = options;298 options = {};299 }300301 // socket errors302 req.socket.on('error', error);303304 // errors305 function error(err) {306 if (done) return;307 done = true;308309 // clean up310 cleanup();311 if (!self.headerSent) self.removeHeader('Content-Disposition');312313 // callback available314 if (fn) return fn(err);315316 // list in limbo if there's no callback317 if (self.headerSent) return;318319 // delegate320 next(err);321 }322323 // streaming324 function stream() {325 if (done) return;326 cleanup();327 if (fn) self.on('finish', fn);328 }329330 // cleanup331 function cleanup() {332 req.socket.removeListener('error', error);333 }334335 // transfer336 var file = send(req, path);337 if (options.root) file.root(options.root);338 file.maxage(options.maxAge || 0);339 file.on('error', error);340 file.on('directory', next);341 file.on('stream', stream);342 file.pipe(this);343 this.on('finish', cleanup);344};345346/**347 * Transfer the file at the given `path` as an attachment.348 *349 * Optionally providing an alternate attachment `filename`,350 * and optional callback `fn(err)`. The callback is invoked351 * when the data transfer is complete, or when an error has352 * ocurred. Be sure to check `res.headerSent` if you plan to respond.353 *354 * This method uses `res.sendfile()`.355 *356 * @param {String} path357 * @param {String|Function} filename or fn358 * @param {Function} fn359 * @api public360 */361362res.download = function(path, filename, fn){363 // support function as second arg364 if ('function' == typeof filename) {365 fn = filename;366 filename = null;367 }368369 filename = filename || path;370 this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');371 return this.sendfile(path, fn);372};373374/**375 * Set _Content-Type_ response header with `type` through `mime.lookup()`376 * when it does not contain "/", or set the Content-Type to `type` otherwise.377 *378 * Examples:379 *380 * res.type('.html');381 * res.type('html');382 * res.type('json');383 * res.type('application/json');384 * res.type('png');385 *386 * @param {String} type387 * @return {ServerResponse} for chaining388 * @api public389 */390391res.contentType =392res.type = function(type){393 return this.set('Content-Type', ~type.indexOf('/')394 ? type395 : mime.lookup(type));396};397398/**399 * Respond to the Acceptable formats using an `obj`400 * of mime-type callbacks.401 *402 * This method uses `req.accepted`, an array of403 * acceptable types ordered by their quality values.404 * When "Accept" is not present the _first_ callback405 * is invoked, otherwise the first match is used. When406 * no match is performed the server responds with407 * 406 "Not Acceptable".408 *409 * Content-Type is set for you, however if you choose410 * you may alter this within the callback using `res.type()`411 * or `res.set('Content-Type', ...)`.412 *413 * res.format({414 * 'text/plain': function(){415 * res.send('hey');416 * },417 *418 * 'text/html': function(){419 * res.send('<p>hey</p>');420 * },421 *422 * 'appliation/json': function(){423 * res.send({ message: 'hey' });424 * }425 * });426 *427 * In addition to canonicalized MIME types you may428 * also use extnames mapped to these types:429 *430 * res.format({431 * text: function(){432 * res.send('hey');433 * },434 *435 * html: function(){436 * res.send('<p>hey</p>');437 * },438 *439 * json: function(){440 * res.send({ message: 'hey' });441 * }442 * });443 *444 * By default Express passes an `Error`445 * with a `.status` of 406 to `next(err)`446 * if a match is not made. If you provide447 * a `.default` callback it will be invoked448 * instead.449 *450 * @param {Object} obj451 * @return {ServerResponse} for chaining452 * @api public453 */454455res.format = function(obj){456 var req = this.req457 , next = req.next;458459 var fn = obj.default;460 if (fn) delete obj.default;461 var keys = Object.keys(obj);462463 var key = req.accepts(keys);464465 this.set('Vary', 'Accept');466467 if (key) {468 this.set('Content-Type', normalizeType(key).value);469 obj[key](req, this, next);470 } else if (fn) {471 fn();472 } else {473 var err = new Error('Not Acceptable');474 err.status = 406;475 err.types = normalizeTypes(keys).map(function(o){ return o.value });476 next(err);477 }478479 return this;480};481482/**483 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.484 *485 * @param {String} filename486 * @return {ServerResponse}487 * @api public488 */489490res.attachment = function(filename){491 if (filename) this.type(extname(filename));492 this.set('Content-Disposition', filename493 ? 'attachment; filename="' + basename(filename) + '"'494 : 'attachment');495 return this;496};497498/**499 * Set header `field` to `val`, or pass500 * an object of header fields.501 *502 * Examples:503 *504 * res.set('Foo', ['bar', 'baz']);505 * res.set('Accept', 'application/json');506 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });507 *508 * Aliased as `res.header()`.509 *510 * @param {String|Object|Array} field511 * @param {String} val512 * @return {ServerResponse} for chaining513 * @api public514 */515516res.set =517res.header = function(field, val){518 if (2 == arguments.length) {519 if (Array.isArray(val)) val = val.map(String);520 else val = String(val);521 this.setHeader(field, val);522 } else {523 for (var key in field) {524 this.set(key, field[key]);525 }526 }527 return this;528};529530/**531 * Get value for header `field`.532 *533 * @param {String} field534 * @return {String}535 * @api public536 */537538res.get = function(field){539 return this.getHeader(field);540};541542/**543 * Clear cookie `name`.544 *545 * @param {String} name546 * @param {Object} options547 * @param {ServerResponse} for chaining548 * @api public549 */550551res.clearCookie = function(name, options){552 var opts = { expires: new Date(1), path: '/' };553 return this.cookie(name, '', options554 ? utils.merge(opts, options)555 : opts);556};557558/**559 * Set cookie `name` to `val`, with the given `options`.560 *561 * Options:562 *563 * - `maxAge` max-age in milliseconds, converted to `expires`564 * - `signed` sign the cookie565 * - `path` defaults to "/"566 *567 * Examples:568 *569 * // "Remember Me" for 15 minutes570 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });571 *572 * // save as above573 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })574 *575 * @param {String} name576 * @param {String|Object} val577 * @param {Options} options578 * @api public579 */580581res.cookie = function(name, val, options){582 options = utils.merge({}, options);583 var secret = this.req.secret;584 var signed = options.signed;585 if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');586 if ('number' == typeof val) val = val.toString();587 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);588 if (signed) val = 's:' + sign(val, secret);589 if ('maxAge' in options) {590 options.expires = new Date(Date.now() + options.maxAge);591 options.maxAge /= 1000;592 }593 if (null == options.path) options.path = '/';594 this.set('Set-Cookie', cookie.serialize(name, String(val), options));595 return this;596};597598599/**600 * Set the location header to `url`.601 *602 * The given `url` can also be the name of a mapped url, for603 * example by default express supports "back" which redirects604 * to the _Referrer_ or _Referer_ headers or "/".605 *606 * Examples:607 *608 * res.location('/foo/bar').;609 * res.location('http://example.com');610 * res.location('../login'); // /blog/post/1 -> /blog/login611 *612 * Mounting:613 *614 * When an application is mounted and `res.location()`615 * is given a path that does _not_ lead with "/" it becomes616 * relative to the mount-point. For example if the application617 * is mounted at "/blog", the following would become "/blog/login".618 *619 * res.location('login');620 *621 * While the leading slash would result in a location of "/login":622 *623 * res.location('/login');624 *625 * @param {String} url626 * @api public627 */628629res.location = function(url){630 var app = this.app631 , req = this.req;632633 // setup redirect map634 var map = { back: req.get('Referrer') || '/' };635636 // perform redirect637 url = map[url] || url;638639 // relative640 if (!~url.indexOf('://') && 0 != url.indexOf('//')) {641 var path642643 // relative to path644 if ('.' == url[0]) {645 path = req.originalUrl.split('?')[0]646 url = path + ('/' == path[path.length - 1] ? '' : '/') + url;647 // relative to mount-point648 } else if ('/' != url[0]) {649 path = app.path();650 url = path + '/' + url;651 }652 }653654 // Respond655 this.set('Location', url);656 return this;657};658659/**660 * Redirect to the given `url` with optional response `status`661 * defaulting to 302.662 *663 * The resulting `url` is determined by `res.location()`, so664 * it will play nicely with mounted apps, relative paths,665 * `"back"` etc.666 *667 * Examples:668 *669 * res.redirect('/foo/bar');670 * res.redirect('http://example.com');671 * res.redirect(301, 'http://example.com');672 * res.redirect('http://example.com', 301);673 * res.redirect('../login'); // /blog/post/1 -> /blog/login674 *675 * @param {String} url676 * @param {Number} code677 * @api public678 */679680res.redirect = function(url){681 var app = this.app682 , head = 'HEAD' == this.req.method683 , status = 302684 , 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 = utils.escape(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 * Render `view` with the given `options` and optional callback `fn`.724 * When a callback function is given a response will _not_ be made725 * automatically, otherwise a response of _200_ and _text/html_ is given.726 *727 * Options:728 *729 * - `cache` boolean hinting to the engine it should cache730 * - `filename` filename of the view being rendered731 *732 * @param {String} view733 * @param {Object|Function} options or callback function734 * @param {Function} fn735 * @api public736 */737738res.render = function(view, options, fn){739 var self = this740 , options = options || {}741 , req = this.req742 , app = req.app;743744 // support callback function as second arg745 if ('function' == typeof options) {746 fn = options, options = {};747 }748749 // merge res.locals750 options._locals = self.locals;751752 // default callback to respond753 fn = fn || function(err, str){754 if (err) return req.next(err);755 self.send(str);756 };757758 // render759 app.render(view, options, fn);760};