Skip to content
Myr

response.js

This file

Path

lib/response.js

834 lines · 19.7 KiB · JavaScript

Last changed by

Fix internal utils.merge deprecation warningsDouglas Christopher Wilsonbefore adoptionaf10438

History of this file

Take it

1/**2 * Module dependencies.3 */45var contentDisposition = require('content-disposition');6var deprecate = require('depd')('express');7var escapeHtml = require('escape-html');8var merge = require('utils-merge');9var parseUrl = require('parseurl');10var vary = require('vary');11var http = require('http')12  , path = require('path')13  , connect = require('connect')14  , sign = require('cookie-signature').sign15  , normalizeType = require('./utils').normalizeType16  , normalizeTypes = require('./utils').normalizeTypes17  , setCharset = require('./utils').setCharset18  , statusCodes = http.STATUS_CODES19  , cookie = require('cookie')20  , send = require('send')21  , mime = connect.mime22  , resolve = require('url').resolve23  , basename = path.basename24  , extname = path.extname;2526/**27 * Response prototype.28 */2930var res = module.exports = {31  __proto__: http.ServerResponse.prototype32};3334/**35 * Set status `code`.36 *37 * @param {Number} code38 * @return {ServerResponse}39 * @api public40 */4142res.status = function(code){43  this.statusCode = code;44  return this;45};4647/**48 * Set Link header field with the given `links`.49 *50 * Examples:51 *52 *    res.links({53 *      next: 'http://api.example.com/users?page=2',54 *      last: 'http://api.example.com/users?page=5'55 *    });56 *57 * @param {Object} links58 * @return {ServerResponse}59 * @api public60 */6162res.links = function(links){63  var link = this.get('Link') || '';64  if (link) link += ', ';65  return this.set('Link', link + Object.keys(links).map(function(rel){66    return '<' + links[rel] + '>; rel="' + rel + '"';67  }).join(', '));68};6970/**71 * Send a response.72 *73 * Examples:74 *75 *     res.send(new Buffer('wahoo'));76 *     res.send({ some: 'json' });77 *     res.send('<p>some html</p>');78 *     res.send(404, 'Sorry, cant find that');79 *     res.send(404);80 *81 * @param {Mixed} body or status82 * @param {Mixed} body83 * @return {ServerResponse}84 * @api public85 */8687res.send = function(body){88  var req = this.req;89  var head = 'HEAD' == req.method;90  var type;91  var encoding;92  var len;9394  // settings95  var app = this.app;9697  // allow status / body98  if (2 == arguments.length) {99    // res.send(body, status) backwards compat100    if ('number' != typeof body && 'number' == typeof arguments[1]) {101      this.statusCode = arguments[1];102    } else {103      this.statusCode = body;104      body = arguments[1];105    }106  }107108  // disambiguate res.send(status) and res.send(status, num)109  if (typeof body === 'number' && arguments.length === 1) {110    // res.send(status) will set status message as text string111    this.get('Content-Type') || this.type('txt');112    this.statusCode = body;113    body = http.STATUS_CODES[body];114  }115116  switch (typeof body) {117    // string defaulting to html118    case 'string':119      if (!this.get('Content-Type')) {120        this.charset = this.charset || 'utf-8';121        this.type('html');122      }123      break;124    case 'boolean':125    case 'number':126    case 'object':127      if (null == body) {128        body = '';129      } else if (Buffer.isBuffer(body)) {130        this.get('Content-Type') || this.type('bin');131      } else {132        return this.json(body);133      }134      break;135  }136137  // write strings in utf-8138  if ('string' === typeof body) {139    encoding = 'utf8';140    type = this.get('Content-Type');141142    // reflect this in content-type143    if ('string' === typeof type) {144      this.set('Content-Type', setCharset(type, 'utf-8'));145    }146  }147148  // populate Content-Length149  if (undefined !== body && !this.get('Content-Length')) {150    len = Buffer.isBuffer(body)151      ? body.length152      : Buffer.byteLength(body, encoding);153    this.set('Content-Length', len);154  }155156  // ETag support157  var etag = len !== undefined && app.get('etag fn');158  if (etag && ('GET' === req.method || 'HEAD' === req.method)) {159    if (!this.get('ETag')) {160      etag = etag(body, encoding);161      etag && this.set('ETag', etag);162    }163  }164165  // freshness166  if (req.fresh) this.statusCode = 304;167168  // strip irrelevant headers169  if (204 == this.statusCode || 304 == this.statusCode) {170    this.removeHeader('Content-Type');171    this.removeHeader('Content-Length');172    this.removeHeader('Transfer-Encoding');173    body = '';174  }175176  // respond177  this.end((head ? null : body), encoding);178179  return this;180};181182/**183 * Send JSON response.184 *185 * Examples:186 *187 *     res.json(null);188 *     res.json({ user: 'tj' });189 *     res.json(500, 'oh noes!');190 *     res.json(404, 'I dont have that');191 *192 * @param {Mixed} obj or status193 * @param {Mixed} obj194 * @return {ServerResponse}195 * @api public196 */197198res.json = function(obj){199  // allow status / body200  if (2 == arguments.length) {201    // res.json(body, status) backwards compat202    if ('number' == typeof arguments[1]) {203      this.statusCode = arguments[1];204      if (typeof obj === 'number') {205        deprecate('res.json(obj, status): Use res.json(status, obj) instead');206      } else {207        deprecate('res.json(num, status): Use res.status(status).json(num) instead');208      }209    } else {210      this.statusCode = obj;211      obj = arguments[1];212    }213  }214215  // settings216  var app = this.app;217  var replacer = app.get('json replacer');218  var spaces = app.get('json spaces');219  var body = JSON.stringify(obj, replacer, spaces);220221  // content-type222  this.charset = this.charset || 'utf-8';223  this.get('Content-Type') || this.set('Content-Type', 'application/json');224225  return this.send(body);226};227228/**229 * Send JSON response with JSONP callback support.230 *231 * Examples:232 *233 *     res.jsonp(null);234 *     res.jsonp({ user: 'tj' });235 *     res.jsonp(500, 'oh noes!');236 *     res.jsonp(404, 'I dont have that');237 *238 * @param {Mixed} obj or status239 * @param {Mixed} obj240 * @return {ServerResponse}241 * @api public242 */243244res.jsonp = function(obj){245  // allow status / body246  if (2 == arguments.length) {247    // res.json(body, status) backwards compat248    if ('number' == typeof arguments[1]) {249      this.statusCode = arguments[1];250      if (typeof obj === 'number') {251        deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');252      } else {253        deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');254      }255    } else {256      this.statusCode = obj;257      obj = arguments[1];258    }259  }260261  // settings262  var app = this.app;263  var replacer = app.get('json replacer');264  var spaces = app.get('json spaces');265  var body = JSON.stringify(obj, replacer, spaces);266  var callback = this.req.query[app.get('jsonp callback name')];267268  // content-type269  if (!this.get('Content-Type')) {270    this.charset = 'utf-8';271    this.set('X-Content-Type-Options', 'nosniff');272    this.set('Content-Type', 'application/json');273  }274275  // fixup callback276  if (Array.isArray(callback)) {277    callback = callback[0];278  }279280  // jsonp281  if (typeof callback === 'string' && callback.length !== 0) {282    this.charset = 'utf-8';283    this.set('X-Content-Type-Options', 'nosniff');284    this.set('Content-Type', 'text/javascript');285286    // restrict callback charset287    callback = callback.replace(/[^\[\]\w$.]/g, '');288289    // replace chars not allowed in JavaScript that are in JSON290    body = body291      .replace(/\u2028/g, '\\u2028')292      .replace(/\u2029/g, '\\u2029');293294    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"295    // the typeof check is just to reduce client error noise296    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';297  }298299  return this.send(body);300};301302/**303 * Transfer the file at the given `path`.304 *305 * Automatically sets the _Content-Type_ response header field.306 * The callback `fn(err)` is invoked when the transfer is complete307 * or when an error occurs. Be sure to check `res.sentHeader`308 * if you wish to attempt responding, as the header and some data309 * may have already been transferred.310 *311 * Options:312 *313 *   - `maxAge`   defaulting to 0314 *   - `root`     root directory for relative filenames315 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them316 *317 * Other options are passed along to `send`.318 *319 * Examples:320 *321 *  The following example illustrates how `res.sendfile()` may322 *  be used as an alternative for the `static()` middleware for323 *  dynamic situations. The code backing `res.sendfile()` is actually324 *  the same code, so HTTP cache support etc is identical.325 *326 *     app.get('/user/:uid/photos/:file', function(req, res){327 *       var uid = req.params.uid328 *         , file = req.params.file;329 *330 *       req.user.mayViewFilesFrom(uid, function(yes){331 *         if (yes) {332 *           res.sendfile('/uploads/' + uid + '/' + file);333 *         } else {334 *           res.send(403, 'Sorry! you cant see that.');335 *         }336 *       });337 *     });338 *339 * @param {String} path340 * @param {Object|Function} options or fn341 * @param {Function} fn342 * @api public343 */344345res.sendfile = function(path, options, fn){346  var self = this347    , req = self.req348    , next = this.req.next349    , options = options || {}350    , done;351352  // support function as second arg353  if ('function' == typeof options) {354    fn = options;355    options = {};356  }357358  // socket errors359  req.socket.on('error', error);360361  // errors362  function error(err) {363    if (done) return;364    done = true;365366    // clean up367    cleanup();368    if (!self.headersSent) self.removeHeader('Content-Disposition');369370    // callback available371    if (fn) return fn(err);372373    // list in limbo if there's no callback374    if (self.headersSent) return;375376    // delegate377    next(err);378  }379380  // streaming381  function stream(stream) {382    if (done) return;383    cleanup();384    if (fn) stream.on('end', fn);385  }386387  // cleanup388  function cleanup() {389    req.socket.removeListener('error', error);390  }391392  // transfer393  var file = send(req, path, options);394  file.on('error', error);395  file.on('directory', next);396  file.on('stream', stream);397  file.pipe(this);398  this.on('finish', cleanup);399};400401/**402 * Transfer the file at the given `path` as an attachment.403 *404 * Optionally providing an alternate attachment `filename`,405 * and optional callback `fn(err)`. The callback is invoked406 * when the data transfer is complete, or when an error has407 * ocurred. Be sure to check `res.headersSent` if you plan to respond.408 *409 * This method uses `res.sendfile()`.410 *411 * @param {String} path412 * @param {String|Function} filename or fn413 * @param {Function} fn414 * @api public415 */416417res.download = function download(path, filename, fn) {418  // support function as second arg419  if (typeof filename === 'function') {420    fn = filename;421    filename = null;422  }423424  filename = filename || path;425426  this.set('Content-Disposition', contentDisposition(filename));427428  return this.sendfile(path, fn);429};430431/**432 * Set _Content-Type_ response header with `type` through `mime.lookup()`433 * when it does not contain "/", or set the Content-Type to `type` otherwise.434 *435 * Examples:436 *437 *     res.type('.html');438 *     res.type('html');439 *     res.type('json');440 *     res.type('application/json');441 *     res.type('png');442 *443 * @param {String} type444 * @return {ServerResponse} for chaining445 * @api public446 */447448res.contentType =449res.type = function(type){450  return this.set('Content-Type', ~type.indexOf('/')451    ? type452    : mime.lookup(type));453};454455/**456 * Respond to the Acceptable formats using an `obj`457 * of mime-type callbacks.458 *459 * This method uses `req.accepted`, an array of460 * acceptable types ordered by their quality values.461 * When "Accept" is not present the _first_ callback462 * is invoked, otherwise the first match is used. When463 * no match is performed the server responds with464 * 406 "Not Acceptable".465 *466 * Content-Type is set for you, however if you choose467 * you may alter this within the callback using `res.type()`468 * or `res.set('Content-Type', ...)`.469 *470 *    res.format({471 *      'text/plain': function(){472 *        res.send('hey');473 *      },474 *475 *      'text/html': function(){476 *        res.send('<p>hey</p>');477 *      },478 *479 *      'appliation/json': function(){480 *        res.send({ message: 'hey' });481 *      }482 *    });483 *484 * In addition to canonicalized MIME types you may485 * also use extnames mapped to these types:486 *487 *    res.format({488 *      text: function(){489 *        res.send('hey');490 *      },491 *492 *      html: function(){493 *        res.send('<p>hey</p>');494 *      },495 *496 *      json: function(){497 *        res.send({ message: 'hey' });498 *      }499 *    });500 *501 * By default Express passes an `Error`502 * with a `.status` of 406 to `next(err)`503 * if a match is not made. If you provide504 * a `.default` callback it will be invoked505 * instead.506 *507 * @param {Object} obj508 * @return {ServerResponse} for chaining509 * @api public510 */511512res.format = function(obj){513  var req = this.req514    , next = req.next;515516  var fn = obj.default;517  if (fn) delete obj.default;518  var keys = Object.keys(obj);519520  var key = req.accepts(keys);521522  this.vary("Accept");523524  if (key) {525    var type = normalizeType(key).value;526    var charset = mime.charsets.lookup(type);527    if (charset) type += '; charset=' + charset;528    this.set('Content-Type', type);529    obj[key](req, this, next);530  } else if (fn) {531    fn();532  } else {533    var err = new Error('Not Acceptable');534    err.status = 406;535    err.types = normalizeTypes(keys).map(function(o){ return o.value });536    next(err);537  }538539  return this;540};541542/**543 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.544 *545 * @param {String} filename546 * @return {ServerResponse}547 * @api public548 */549550res.attachment = function attachment(filename) {551  if (filename) {552    this.type(extname(filename));553  }554555  this.set('Content-Disposition', contentDisposition(filename));556557  return this;558};559560/**561 * Set header `field` to `val`, or pass562 * an object of header fields.563 *564 * Examples:565 *566 *    res.set('Foo', ['bar', 'baz']);567 *    res.set('Accept', 'application/json');568 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });569 *570 * Aliased as `res.header()`.571 *572 * @param {String|Object|Array} field573 * @param {String} val574 * @return {ServerResponse} for chaining575 * @api public576 */577578res.set =579res.header = function(field, val){580  if (2 == arguments.length) {581    if (Array.isArray(val)) val = val.map(String);582    else val = String(val);583    this.setHeader(field, val);584  } else {585    for (var key in field) {586      this.set(key, field[key]);587    }588  }589  return this;590};591592/**593 * Get value for header `field`.594 *595 * @param {String} field596 * @return {String}597 * @api public598 */599600res.get = function(field){601  return this.getHeader(field);602};603604/**605 * Clear cookie `name`.606 *607 * @param {String} name608 * @param {Object} options609 * @param {ServerResponse} for chaining610 * @api public611 */612613res.clearCookie = function(name, options){614  var opts = { expires: new Date(1), path: '/' };615  return this.cookie(name, '', options616    ? merge(opts, options)617    : opts);618};619620/**621 * Set cookie `name` to `val`, with the given `options`.622 *623 * Options:624 *625 *    - `maxAge`   max-age in milliseconds, converted to `expires`626 *    - `signed`   sign the cookie627 *    - `path`     defaults to "/"628 *629 * Examples:630 *631 *    // "Remember Me" for 15 minutes632 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });633 *634 *    // save as above635 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })636 *637 * @param {String} name638 * @param {String|Object} val639 * @param {Options} options640 * @api public641 */642643res.cookie = function(name, val, options){644  options = merge({}, options);645  var secret = this.req.secret;646  var signed = options.signed;647  if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');648  if ('number' == typeof val) val = val.toString();649  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);650  if (signed) val = 's:' + sign(val, secret);651  if ('maxAge' in options) {652    options.expires = new Date(Date.now() + options.maxAge);653    options.maxAge /= 1000;654  }655  if (null == options.path) options.path = '/';656  this.set('Set-Cookie', cookie.serialize(name, String(val), options));657  return this;658};659660661/**662 * Set the location header to `url`.663 *664 * The given `url` can also be "back", which redirects665 * to the _Referrer_ or _Referer_ headers or "/".666 *667 * Examples:668 *669 *    res.location('/foo/bar').;670 *    res.location('http://example.com');671 *    res.location('../login'); // /blog/post/1 -> /blog/login672 *673 * Mounting:674 *675 *   When an application is mounted and `res.location()`676 *   is given a path that does _not_ lead with "/" it becomes677 *   relative to the mount-point. For example if the application678 *   is mounted at "/blog", the following would become "/blog/login".679 *680 *      res.location('login');681 *682 *   While the leading slash would result in a location of "/login":683 *684 *      res.location('/login');685 *686 * @param {String} url687 * @api public688 */689690res.location = function(url){691  var app = this.app692    , req = this.req693    , path;694695  // "back" is an alias for the referrer696  if ('back' == url) url = req.get('Referrer') || '/';697698  // relative699  if (!~url.indexOf('://') && 0 != url.indexOf('//')) {700    // relative to path701    if ('.' == url[0]) {702      path = parseUrl.original(req).pathname;703      path = path + ('/' == path[path.length - 1] ? '' : '/');704      url = resolve(path, url);705      // relative to mount-point706    } else if ('/' != url[0]) {707      path = app.path();708      url = path + '/' + url;709    }710  }711712  // Respond713  this.set('Location', url);714  return this;715};716717/**718 * Redirect to the given `url` with optional response `status`719 * defaulting to 302.720 *721 * The resulting `url` is determined by `res.location()`, so722 * it will play nicely with mounted apps, relative paths,723 * `"back"` etc.724 *725 * Examples:726 *727 *    res.redirect('/foo/bar');728 *    res.redirect('http://example.com');729 *    res.redirect(301, 'http://example.com');730 *    res.redirect('../login'); // /blog/post/1 -> /blog/login731 *732 * @api public733 */734735res.redirect = function(url){736  var head = 'HEAD' == this.req.method737    , status = 302738    , body;739740  // allow status / url741  if (2 == arguments.length) {742    if ('number' == typeof url) {743      status = url;744      url = arguments[1];745    } else {746      deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');747      status = arguments[1];748    }749  }750751  // Set location header752  this.location(url);753  url = this.get('Location');754755  // Support text/{plain,html} by default756  this.format({757    text: function(){758      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);759    },760761    html: function(){762      var u = escapeHtml(url);763      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';764    },765766    default: function(){767      body = '';768    }769  });770771  // Respond772  this.statusCode = status;773  this.set('Content-Length', Buffer.byteLength(body));774  this.end(head ? null : body);775};776777/**778 * Add `field` to Vary. If already present in the Vary set, then779 * this call is simply ignored.780 *781 * @param {Array|String} field782 * @param {ServerResponse} for chaining783 * @api public784 */785786res.vary = function(field){787  // checks for back-compat788  if (!field) return this;789  if (Array.isArray(field) && !field.length) return this;790791  vary(this, field);792793  return this;794};795796/**797 * Render `view` with the given `options` and optional callback `fn`.798 * When a callback function is given a response will _not_ be made799 * automatically, otherwise a response of _200_ and _text/html_ is given.800 *801 * Options:802 *803 *  - `cache`     boolean hinting to the engine it should cache804 *  - `filename`  filename of the view being rendered805 *806 * @param  {String} view807 * @param  {Object|Function} options or callback function808 * @param  {Function} fn809 * @api public810 */811812res.render = function(view, options, fn){813  var self = this814    , options = options || {}815    , req = this.req816    , app = req.app;817818  // support callback function as second arg819  if ('function' == typeof options) {820    fn = options, options = {};821  }822823  // merge res.locals824  options._locals = self.locals;825826  // default callback to respond827  fn = fn || function(err, str){828    if (err) return req.next(err);829    self.send(str);830  };831832  // render833  app.render(view, options, fn);834};