Skip to content
Myr

response.js

This file

Path

lib/response.js

821 lines · 19.3 KiB · JavaScript

Last changed by

use vary@0.1.0Jonathan Ongbefore adoption6d65ae5

History of this file

Take it

1/**2 * Module dependencies.3 */45var escapeHtml = require('escape-html');6var vary = require('vary');7var http = require('http')8  , path = require('path')9  , connect = require('connect')10  , utils = connect.utils11  , sign = require('cookie-signature').sign12  , normalizeType = require('./utils').normalizeType13  , normalizeTypes = require('./utils').normalizeTypes14  , setCharset = require('./utils').setCharset15  , deprecate = require('./utils').deprecate16  , statusCodes = http.STATUS_CODES17  , cookie = require('cookie')18  , send = require('send')19  , mime = connect.mime20  , resolve = require('url').resolve21  , basename = path.basename22  , extname = path.extname;2324/**25 * Response prototype.26 */2728var res = module.exports = {29  __proto__: http.ServerResponse.prototype30};3132/**33 * Set status `code`.34 *35 * @param {Number} code36 * @return {ServerResponse}37 * @api public38 */3940res.status = function(code){41  this.statusCode = code;42  return this;43};4445/**46 * Set Link header field with the given `links`.47 *48 * Examples:49 *50 *    res.links({51 *      next: 'http://api.example.com/users?page=2',52 *      last: 'http://api.example.com/users?page=5'53 *    });54 *55 * @param {Object} links56 * @return {ServerResponse}57 * @api public58 */5960res.links = function(links){61  var link = this.get('Link') || '';62  if (link) link += ', ';63  return this.set('Link', link + Object.keys(links).map(function(rel){64    return '<' + links[rel] + '>; rel="' + rel + '"';65  }).join(', '));66};6768/**69 * Send a response.70 *71 * Examples:72 *73 *     res.send(new Buffer('wahoo'));74 *     res.send({ some: 'json' });75 *     res.send('<p>some html</p>');76 *     res.send(404, 'Sorry, cant find that');77 *     res.send(404);78 *79 * @param {Mixed} body or status80 * @param {Mixed} body81 * @return {ServerResponse}82 * @api public83 */8485res.send = function(body){86  var req = this.req;87  var head = 'HEAD' == req.method;88  var type;89  var encoding;90  var len;9192  // settings93  var app = this.app;9495  // allow status / body96  if (2 == arguments.length) {97    // res.send(body, status) backwards compat98    if ('number' != typeof body && 'number' == typeof arguments[1]) {99      this.statusCode = arguments[1];100    } else {101      this.statusCode = body;102      body = arguments[1];103    }104  }105106  switch (typeof body) {107    // response status108    case 'number':109      this.get('Content-Type') || this.type('txt');110      this.statusCode = body;111      body = http.STATUS_CODES[body];112      break;113    // string defaulting to html114    case 'string':115      if (!this.get('Content-Type')) {116        this.charset = this.charset || 'utf-8';117        this.type('html');118      }119      break;120    case 'boolean':121    case 'object':122      if (null == body) {123        body = '';124      } else if (Buffer.isBuffer(body)) {125        this.get('Content-Type') || this.type('bin');126      } else {127        return this.json(body);128      }129      break;130  }131132  // write strings in utf-8133  if ('string' === typeof body) {134    encoding = 'utf8';135    type = this.get('Content-Type');136137    // reflect this in content-type138    if ('string' === typeof type) {139      this.set('Content-Type', setCharset(type, 'utf-8'));140    }141  }142143  // populate Content-Length144  if (undefined !== body && !this.get('Content-Length')) {145    len = Buffer.isBuffer(body)146      ? body.length147      : Buffer.byteLength(body, encoding);148    this.set('Content-Length', len);149  }150151  // ETag support152  var etag = len !== undefined && app.get('etag fn');153  if (etag && ('GET' === req.method || 'HEAD' === req.method)) {154    if (!this.get('ETag')) {155      etag = etag(body, encoding);156      etag && this.set('ETag', etag);157    }158  }159160  // freshness161  if (req.fresh) this.statusCode = 304;162163  // strip irrelevant headers164  if (204 == this.statusCode || 304 == this.statusCode) {165    this.removeHeader('Content-Type');166    this.removeHeader('Content-Length');167    this.removeHeader('Transfer-Encoding');168    body = '';169  }170171  // respond172  this.end((head ? null : body), encoding);173174  return this;175};176177/**178 * Send JSON response.179 *180 * Examples:181 *182 *     res.json(null);183 *     res.json({ user: 'tj' });184 *     res.json(500, 'oh noes!');185 *     res.json(404, 'I dont have that');186 *187 * @param {Mixed} obj or status188 * @param {Mixed} obj189 * @return {ServerResponse}190 * @api public191 */192193res.json = function(obj){194  // allow status / body195  if (2 == arguments.length) {196    // res.json(body, status) backwards compat197    if ('number' == typeof arguments[1]) {198      this.statusCode = arguments[1];199      return 'number' === typeof obj200        ? jsonNumDeprecated.call(this, obj)201        : jsonDeprecated.call(this, obj);202    } else {203      this.statusCode = obj;204      obj = arguments[1];205    }206  }207208  // settings209  var app = this.app;210  var replacer = app.get('json replacer');211  var spaces = app.get('json spaces');212  var body = JSON.stringify(obj, replacer, spaces);213214  // content-type215  this.charset = this.charset || 'utf-8';216  this.get('Content-Type') || this.set('Content-Type', 'application/json');217218  return this.send(body);219};220221var jsonDeprecated = deprecate(res.json,222  'res.json(obj, status): Use res.json(status, obj) instead');223224var jsonNumDeprecated = deprecate(res.json,225  'res.json(num, status): Use res.status(status).json(num) instead');226227/**228 * Send JSON response with JSONP callback support.229 *230 * Examples:231 *232 *     res.jsonp(null);233 *     res.jsonp({ user: 'tj' });234 *     res.jsonp(500, 'oh noes!');235 *     res.jsonp(404, 'I dont have that');236 *237 * @param {Mixed} obj or status238 * @param {Mixed} obj239 * @return {ServerResponse}240 * @api public241 */242243res.jsonp = function(obj){244  // allow status / body245  if (2 == arguments.length) {246    // res.json(body, status) backwards compat247    if ('number' == typeof arguments[1]) {248      this.statusCode = arguments[1];249      return 'number' === typeof obj250        ? jsonpNumDeprecated.call(this, obj)251        : jsonpDeprecated.call(this, obj);252    } else {253      this.statusCode = obj;254      obj = arguments[1];255    }256  }257258  // settings259  var app = this.app;260  var replacer = app.get('json replacer');261  var spaces = app.get('json spaces');262  var body = JSON.stringify(obj, replacer, spaces)263    .replace(/\u2028/g, '\\u2028')264    .replace(/\u2029/g, '\\u2029');265  var callback = this.req.query[app.get('jsonp callback name')];266267  // content-type268  this.charset = this.charset || 'utf-8';269  this.get('Content-Type') || this.set('Content-Type', 'application/json');270271  // fixup callback272  if (Array.isArray(callback)) {273    callback = callback[0];274  }275276  // jsonp277  if (callback && 'string' === typeof callback) {278    this.set('Content-Type', 'text/javascript');279    var cb = callback.replace(/[^\[\]\w$.]/g, '');280    body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';281  }282283  return this.send(body);284};285286var jsonpDeprecated = deprecate(res.json,287  'res.jsonp(obj, status): Use res.jsonp(status, obj) instead');288289var jsonpNumDeprecated = deprecate(res.json,290  'res.jsonp(num, status): Use res.status(status).jsonp(num) instead');291292/**293 * Transfer the file at the given `path`.294 *295 * Automatically sets the _Content-Type_ response header field.296 * The callback `fn(err)` is invoked when the transfer is complete297 * or when an error occurs. Be sure to check `res.sentHeader`298 * if you wish to attempt responding, as the header and some data299 * may have already been transferred.300 *301 * Options:302 *303 *   - `maxAge` defaulting to 0304 *   - `root`   root directory for relative filenames305 *306 * Examples:307 *308 *  The following example illustrates how `res.sendfile()` may309 *  be used as an alternative for the `static()` middleware for310 *  dynamic situations. The code backing `res.sendfile()` is actually311 *  the same code, so HTTP cache support etc is identical.312 *313 *     app.get('/user/:uid/photos/:file', function(req, res){314 *       var uid = req.params.uid315 *         , file = req.params.file;316 *317 *       req.user.mayViewFilesFrom(uid, function(yes){318 *         if (yes) {319 *           res.sendfile('/uploads/' + uid + '/' + file);320 *         } else {321 *           res.send(403, 'Sorry! you cant see that.');322 *         }323 *       });324 *     });325 *326 * @param {String} path327 * @param {Object|Function} options or fn328 * @param {Function} fn329 * @api public330 */331332res.sendfile = function(path, options, fn){333  var self = this334    , req = self.req335    , next = this.req.next336    , options = options || {}337    , done;338339  // support function as second arg340  if ('function' == typeof options) {341    fn = options;342    options = {};343  }344345  // socket errors346  req.socket.on('error', error);347348  // errors349  function error(err) {350    if (done) return;351    done = true;352353    // clean up354    cleanup();355    if (!self.headersSent) self.removeHeader('Content-Disposition');356357    // callback available358    if (fn) return fn(err);359360    // list in limbo if there's no callback361    if (self.headersSent) return;362363    // delegate364    next(err);365  }366367  // streaming368  function stream(stream) {369    if (done) return;370    cleanup();371    if (fn) stream.on('end', fn);372  }373374  // cleanup375  function cleanup() {376    req.socket.removeListener('error', error);377  }378379  // transfer380  var file = send(req, path);381  if (options.root) file.root(options.root);382  file.maxage(options.maxAge || 0);383  file.on('error', error);384  file.on('directory', next);385  file.on('stream', stream);386  file.pipe(this);387  this.on('finish', cleanup);388};389390/**391 * Transfer the file at the given `path` as an attachment.392 *393 * Optionally providing an alternate attachment `filename`,394 * and optional callback `fn(err)`. The callback is invoked395 * when the data transfer is complete, or when an error has396 * ocurred. Be sure to check `res.headersSent` if you plan to respond.397 *398 * This method uses `res.sendfile()`.399 *400 * @param {String} path401 * @param {String|Function} filename or fn402 * @param {Function} fn403 * @api public404 */405406res.download = function(path, filename, fn){407  // support function as second arg408  if ('function' == typeof filename) {409    fn = filename;410    filename = null;411  }412413  filename = filename || path;414  this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');415  return this.sendfile(path, fn);416};417418/**419 * Set _Content-Type_ response header with `type` through `mime.lookup()`420 * when it does not contain "/", or set the Content-Type to `type` otherwise.421 *422 * Examples:423 *424 *     res.type('.html');425 *     res.type('html');426 *     res.type('json');427 *     res.type('application/json');428 *     res.type('png');429 *430 * @param {String} type431 * @return {ServerResponse} for chaining432 * @api public433 */434435res.contentType =436res.type = function(type){437  return this.set('Content-Type', ~type.indexOf('/')438    ? type439    : mime.lookup(type));440};441442/**443 * Respond to the Acceptable formats using an `obj`444 * of mime-type callbacks.445 *446 * This method uses `req.accepted`, an array of447 * acceptable types ordered by their quality values.448 * When "Accept" is not present the _first_ callback449 * is invoked, otherwise the first match is used. When450 * no match is performed the server responds with451 * 406 "Not Acceptable".452 *453 * Content-Type is set for you, however if you choose454 * you may alter this within the callback using `res.type()`455 * or `res.set('Content-Type', ...)`.456 *457 *    res.format({458 *      'text/plain': function(){459 *        res.send('hey');460 *      },461 *462 *      'text/html': function(){463 *        res.send('<p>hey</p>');464 *      },465 *466 *      'appliation/json': function(){467 *        res.send({ message: 'hey' });468 *      }469 *    });470 *471 * In addition to canonicalized MIME types you may472 * also use extnames mapped to these types:473 *474 *    res.format({475 *      text: function(){476 *        res.send('hey');477 *      },478 *479 *      html: function(){480 *        res.send('<p>hey</p>');481 *      },482 *483 *      json: function(){484 *        res.send({ message: 'hey' });485 *      }486 *    });487 *488 * By default Express passes an `Error`489 * with a `.status` of 406 to `next(err)`490 * if a match is not made. If you provide491 * a `.default` callback it will be invoked492 * instead.493 *494 * @param {Object} obj495 * @return {ServerResponse} for chaining496 * @api public497 */498499res.format = function(obj){500  var req = this.req501    , next = req.next;502503  var fn = obj.default;504  if (fn) delete obj.default;505  var keys = Object.keys(obj);506507  var key = req.accepts(keys);508509  this.vary("Accept");510511  if (key) {512    var type = normalizeType(key).value;513    var charset = mime.charsets.lookup(type);514    if (charset) type += '; charset=' + charset;515    this.set('Content-Type', type);516    obj[key](req, this, next);517  } else if (fn) {518    fn();519  } else {520    var err = new Error('Not Acceptable');521    err.status = 406;522    err.types = normalizeTypes(keys).map(function(o){ return o.value });523    next(err);524  }525526  return this;527};528529/**530 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.531 *532 * @param {String} filename533 * @return {ServerResponse}534 * @api public535 */536537res.attachment = function(filename){538  if (filename) this.type(extname(filename));539  this.set('Content-Disposition', filename540    ? 'attachment; filename="' + basename(filename) + '"'541    : 'attachment');542  return this;543};544545/**546 * Set header `field` to `val`, or pass547 * an object of header fields.548 *549 * Examples:550 *551 *    res.set('Foo', ['bar', 'baz']);552 *    res.set('Accept', 'application/json');553 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });554 *555 * Aliased as `res.header()`.556 *557 * @param {String|Object|Array} field558 * @param {String} val559 * @return {ServerResponse} for chaining560 * @api public561 */562563res.set =564res.header = function(field, val){565  if (2 == arguments.length) {566    if (Array.isArray(val)) val = val.map(String);567    else val = String(val);568    this.setHeader(field, val);569  } else {570    for (var key in field) {571      this.set(key, field[key]);572    }573  }574  return this;575};576577/**578 * Get value for header `field`.579 *580 * @param {String} field581 * @return {String}582 * @api public583 */584585res.get = function(field){586  return this.getHeader(field);587};588589/**590 * Clear cookie `name`.591 *592 * @param {String} name593 * @param {Object} options594 * @param {ServerResponse} for chaining595 * @api public596 */597598res.clearCookie = function(name, options){599  var opts = { expires: new Date(1), path: '/' };600  return this.cookie(name, '', options601    ? utils.merge(opts, options)602    : opts);603};604605/**606 * Set cookie `name` to `val`, with the given `options`.607 *608 * Options:609 *610 *    - `maxAge`   max-age in milliseconds, converted to `expires`611 *    - `signed`   sign the cookie612 *    - `path`     defaults to "/"613 *614 * Examples:615 *616 *    // "Remember Me" for 15 minutes617 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });618 *619 *    // save as above620 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })621 *622 * @param {String} name623 * @param {String|Object} val624 * @param {Options} options625 * @api public626 */627628res.cookie = function(name, val, options){629  options = utils.merge({}, options);630  var secret = this.req.secret;631  var signed = options.signed;632  if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');633  if ('number' == typeof val) val = val.toString();634  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);635  if (signed) val = 's:' + sign(val, secret);636  if ('maxAge' in options) {637    options.expires = new Date(Date.now() + options.maxAge);638    options.maxAge /= 1000;639  }640  if (null == options.path) options.path = '/';641  this.set('Set-Cookie', cookie.serialize(name, String(val), options));642  return this;643};644645646/**647 * Set the location header to `url`.648 *649 * The given `url` can also be "back", which redirects650 * to the _Referrer_ or _Referer_ headers or "/".651 *652 * Examples:653 *654 *    res.location('/foo/bar').;655 *    res.location('http://example.com');656 *    res.location('../login'); // /blog/post/1 -> /blog/login657 *658 * Mounting:659 *660 *   When an application is mounted and `res.location()`661 *   is given a path that does _not_ lead with "/" it becomes662 *   relative to the mount-point. For example if the application663 *   is mounted at "/blog", the following would become "/blog/login".664 *665 *      res.location('login');666 *667 *   While the leading slash would result in a location of "/login":668 *669 *      res.location('/login');670 *671 * @param {String} url672 * @api public673 */674675res.location = function(url){676  var app = this.app677    , req = this.req678    , path;679680  // "back" is an alias for the referrer681  if ('back' == url) url = req.get('Referrer') || '/';682683  // relative684  if (!~url.indexOf('://') && 0 != url.indexOf('//')) {685    // relative to path686    if ('.' == url[0]) {687      path = req.originalUrl.split('?')[0];688      path = path + ('/' == path[path.length - 1] ? '' : '/');689      url = resolve(path, url);690      // relative to mount-point691    } else if ('/' != url[0]) {692      path = app.path();693      url = path + '/' + url;694    }695  }696697  // Respond698  this.set('Location', url);699  return this;700};701702/**703 * Redirect to the given `url` with optional response `status`704 * defaulting to 302.705 *706 * The resulting `url` is determined by `res.location()`, so707 * it will play nicely with mounted apps, relative paths,708 * `"back"` etc.709 *710 * Examples:711 *712 *    res.redirect('/foo/bar');713 *    res.redirect('http://example.com');714 *    res.redirect(301, 'http://example.com');715 *    res.redirect('http://example.com', 301);716 *    res.redirect('../login'); // /blog/post/1 -> /blog/login717 *718 * @param {String} url719 * @param {Number} code720 * @api public721 */722723res.redirect = function(url){724  var head = 'HEAD' == this.req.method725    , status = 302726    , body;727728  // allow status / url729  if (2 == arguments.length) {730    if ('number' == typeof url) {731      status = url;732      url = arguments[1];733    } else {734      status = arguments[1];735    }736  }737738  // Set location header739  this.location(url);740  url = this.get('Location');741742  // Support text/{plain,html} by default743  this.format({744    text: function(){745      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);746    },747748    html: function(){749      var u = escapeHtml(url);750      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';751    },752753    default: function(){754      body = '';755    }756  });757758  // Respond759  this.statusCode = status;760  this.set('Content-Length', Buffer.byteLength(body));761  this.end(head ? null : body);762};763764/**765 * Add `field` to Vary. If already present in the Vary set, then766 * this call is simply ignored.767 *768 * @param {Array|String} field769 * @param {ServerResponse} for chaining770 * @api public771 */772773res.vary = function(field){774  // checks for back-compat775  if (!field) return this;776  if (Array.isArray(field) && !field.length) return this;777778  vary(this, field);779780  return this;781};782783/**784 * Render `view` with the given `options` and optional callback `fn`.785 * When a callback function is given a response will _not_ be made786 * automatically, otherwise a response of _200_ and _text/html_ is given.787 *788 * Options:789 *790 *  - `cache`     boolean hinting to the engine it should cache791 *  - `filename`  filename of the view being rendered792 *793 * @param  {String} view794 * @param  {Object|Function} options or callback function795 * @param  {Function} fn796 * @api public797 */798799res.render = function(view, options, fn){800  var self = this801    , options = options || {}802    , req = this.req803    , app = req.app;804805  // support callback function as second arg806  if ('function' == typeof options) {807    fn = options, options = {};808  }809810  // merge res.locals811  options._locals = self.locals;812813  // default callback to respond814  fn = fn || function(err, str){815    if (err) return req.next(err);816    self.send(str);817  };818819  // render820  app.render(view, options, fn);821};