Skip to content
Myr

response.js

This file

Path

lib/response.js

803 lines · 18.6 KiB · JavaScript

Last changed by

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

History of this file

Take it

1/**2 * Module dependencies.3 */45var http = require('http');6var path = require('path');7var mixin = require('utils-merge');8var escapeHtml = require('escape-html');9var sign = require('cookie-signature').sign;10var normalizeType = require('./utils').normalizeType;11var normalizeTypes = require('./utils').normalizeTypes;12var contentDisposition = require('./utils').contentDisposition;13var deprecate = require('./utils').deprecate;14var etag = require('./utils').etag;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;2122/**23 * Response prototype.24 */2526var res = module.exports = {27  __proto__: http.ServerResponse.prototype28};2930/**31 * Set status `code`.32 *33 * @param {Number} code34 * @return {ServerResponse}35 * @api public36 */3738res.status = function(code){39  this.statusCode = code;40  return this;41};4243/**44 * Set Link header field with the given `links`.45 *46 * Examples:47 *48 *    res.links({49 *      next: 'http://api.example.com/users?page=2',50 *      last: 'http://api.example.com/users?page=5'51 *    });52 *53 * @param {Object} links54 * @return {ServerResponse}55 * @api public56 */5758res.links = function(links){59  var link = this.get('Link') || '';60  if (link) link += ', ';61  return this.set('Link', link + Object.keys(links).map(function(rel){62    return '<' + links[rel] + '>; rel="' + rel + '"';63  }).join(', '));64};6566/**67 * Send a response.68 *69 * Examples:70 *71 *     res.send(new Buffer('wahoo'));72 *     res.send({ some: 'json' });73 *     res.send('<p>some html</p>');74 *     res.send(404, 'Sorry, cant find that');75 *     res.send(404);76 *77 * @param {Mixed} body or status78 * @param {Mixed} body79 * @return {ServerResponse}80 * @api public81 */8283res.send = function(body){84  var req = this.req;85  var head = 'HEAD' == req.method;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      this.statusCode = arguments[1];96    } else {97      this.statusCode = body;98      body = arguments[1];99    }100  }101102  switch (typeof body) {103    // response status104    case 'number':105      this.get('Content-Type') || this.type('txt');106      this.statusCode = body;107      body = http.STATUS_CODES[body];108      break;109    // string defaulting to html110    case 'string':111      if (!this.get('Content-Type')) this.type('html');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 && ('GET' == req.method || 'HEAD' == 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      return 'number' === typeof obj179        ? jsonNumDeprecated.call(this, obj)180        : jsonDeprecated.call(this, obj);181    } else {182      this.statusCode = obj;183      obj = arguments[1];184    }185  }186187  // settings188  var app = this.app;189  var replacer = app.get('json replacer');190  var spaces = app.get('json spaces');191  var body = JSON.stringify(obj, replacer, spaces);192193  // content-type194  this.get('Content-Type') || this.set('Content-Type', 'application/json');195196  return this.send(body);197};198199var jsonDeprecated = deprecate(res.json,200  'res.json(obj, status): Use res.json(status, obj) instead');201202var jsonNumDeprecated = deprecate(res.json,203  'res.json(num, status): Use res.status(status).json(num) instead');204205/**206 * Send JSON response with JSONP callback support.207 *208 * Examples:209 *210 *     res.jsonp(null);211 *     res.jsonp({ user: 'tj' });212 *     res.jsonp(500, 'oh noes!');213 *     res.jsonp(404, 'I dont have that');214 *215 * @param {Mixed} obj or status216 * @param {Mixed} obj217 * @return {ServerResponse}218 * @api public219 */220221res.jsonp = function(obj){222  // allow status / body223  if (2 == arguments.length) {224    // res.json(body, status) backwards compat225    if ('number' == typeof arguments[1]) {226      this.statusCode = arguments[1];227      return 'number' === typeof obj228        ? jsonpNumDeprecated.call(this, obj)229        : jsonpDeprecated.call(this, obj);230    } else {231      this.statusCode = obj;232      obj = arguments[1];233    }234  }235236  // settings237  var app = this.app;238  var replacer = app.get('json replacer');239  var spaces = app.get('json spaces');240  var body = JSON.stringify(obj, replacer, spaces)241    .replace(/\u2028/g, '\\u2028')242    .replace(/\u2029/g, '\\u2029');243  var callback = this.req.query[app.get('jsonp callback name')];244245  // content-type246  this.get('Content-Type') || this.set('Content-Type', 'application/json');247248  // fixup callback249  if (Array.isArray(callback)) {250    callback = callback[0];251  }252253  // jsonp254  if (callback && 'string' === typeof callback) {255    this.set('Content-Type', 'text/javascript');256    var cb = callback.replace(/[^\[\]\w$.]/g, '');257    body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';258  }259260  return this.send(body);261};262263var jsonpDeprecated = deprecate(res.json,264  'res.jsonp(obj, status): Use res.jsonp(status, obj) instead');265266var jsonpNumDeprecated = deprecate(res.json,267  'res.jsonp(num, status): Use res.status(status).jsonp(num) instead');268269/**270 * Transfer the file at the given `path`.271 *272 * Automatically sets the _Content-Type_ response header field.273 * The callback `fn(err)` is invoked when the transfer is complete274 * or when an error occurs. Be sure to check `res.sentHeader`275 * if you wish to attempt responding, as the header and some data276 * may have already been transferred.277 *278 * Options:279 *280 *   - `maxAge` defaulting to 0281 *   - `root`   root directory for relative filenames282 *   - `hidden` serve hidden files, defaulting to false283 *284 * Other options are passed along to `send`.285 *286 * Examples:287 *288 *  The following example illustrates how `res.sendfile()` may289 *  be used as an alternative for the `static()` middleware for290 *  dynamic situations. The code backing `res.sendfile()` is actually291 *  the same code, so HTTP cache support etc is identical.292 *293 *     app.get('/user/:uid/photos/:file', function(req, res){294 *       var uid = req.params.uid295 *         , file = req.params.file;296 *297 *       req.user.mayViewFilesFrom(uid, function(yes){298 *         if (yes) {299 *           res.sendfile('/uploads/' + uid + '/' + file);300 *         } else {301 *           res.send(403, 'Sorry! you cant see that.');302 *         }303 *       });304 *     });305 *306 * @param {String} path307 * @param {Object|Function} options or fn308 * @param {Function} fn309 * @api public310 */311312res.sendfile = function(path, options, fn){313  options = options || {};314  var self = this;315  var req = self.req;316  var next = this.req.next;317  var done;318319320  // support function as second arg321  if ('function' == typeof options) {322    fn = options;323    options = {};324  }325326  // socket errors327  req.socket.on('error', error);328329  // errors330  function error(err) {331    if (done) return;332    done = true;333334    // clean up335    cleanup();336    if (!self.headersSent) self.removeHeader('Content-Disposition');337338    // callback available339    if (fn) return fn(err);340341    // list in limbo if there's no callback342    if (self.headersSent) return;343344    // delegate345    next(err);346  }347348  // streaming349  function stream(stream) {350    if (done) return;351    cleanup();352    if (fn) stream.on('end', fn);353  }354355  // cleanup356  function cleanup() {357    req.socket.removeListener('error', error);358  }359360  // Back-compat361  options.maxage = options.maxage || options.maxAge || 0;362363  // transfer364  var file = send(req, path, options);365  file.on('error', error);366  file.on('directory', next);367  file.on('stream', stream);368  file.pipe(this);369  this.on('finish', cleanup);370};371372/**373 * Transfer the file at the given `path` as an attachment.374 *375 * Optionally providing an alternate attachment `filename`,376 * and optional callback `fn(err)`. The callback is invoked377 * when the data transfer is complete, or when an error has378 * ocurred. Be sure to check `res.headersSent` if you plan to respond.379 *380 * This method uses `res.sendfile()`.381 *382 * @param {String} path383 * @param {String|Function} filename or fn384 * @param {Function} fn385 * @api public386 */387388res.download = function(path, filename, fn){389  // support function as second arg390  if ('function' == typeof filename) {391    fn = filename;392    filename = null;393  }394395  filename = filename || path;396  this.set('Content-Disposition', contentDisposition(filename));397  return this.sendfile(path, fn);398};399400/**401 * Set _Content-Type_ response header with `type` through `mime.lookup()`402 * when it does not contain "/", or set the Content-Type to `type` otherwise.403 *404 * Examples:405 *406 *     res.type('.html');407 *     res.type('html');408 *     res.type('json');409 *     res.type('application/json');410 *     res.type('png');411 *412 * @param {String} type413 * @return {ServerResponse} for chaining414 * @api public415 */416417res.contentType =418res.type = function(type){419  return this.set('Content-Type', ~type.indexOf('/')420    ? type421    : mime.lookup(type));422};423424/**425 * Respond to the Acceptable formats using an `obj`426 * of mime-type callbacks.427 *428 * This method uses `req.accepted`, an array of429 * acceptable types ordered by their quality values.430 * When "Accept" is not present the _first_ callback431 * is invoked, otherwise the first match is used. When432 * no match is performed the server responds with433 * 406 "Not Acceptable".434 *435 * Content-Type is set for you, however if you choose436 * you may alter this within the callback using `res.type()`437 * or `res.set('Content-Type', ...)`.438 *439 *    res.format({440 *      'text/plain': function(){441 *        res.send('hey');442 *      },443 *444 *      'text/html': function(){445 *        res.send('<p>hey</p>');446 *      },447 *448 *      'appliation/json': function(){449 *        res.send({ message: 'hey' });450 *      }451 *    });452 *453 * In addition to canonicalized MIME types you may454 * also use extnames mapped to these types:455 *456 *    res.format({457 *      text: function(){458 *        res.send('hey');459 *      },460 *461 *      html: function(){462 *        res.send('<p>hey</p>');463 *      },464 *465 *      json: function(){466 *        res.send({ message: 'hey' });467 *      }468 *    });469 *470 * By default Express passes an `Error`471 * with a `.status` of 406 to `next(err)`472 * if a match is not made. If you provide473 * a `.default` callback it will be invoked474 * instead.475 *476 * @param {Object} obj477 * @return {ServerResponse} for chaining478 * @api public479 */480481res.format = function(obj){482  var req = this.req;483  var next = req.next;484485  var fn = obj.default;486  if (fn) delete obj.default;487  var keys = Object.keys(obj);488489  var key = req.accepts(keys);490491  this.vary("Accept");492493  if (key) {494    this.set('Content-Type', normalizeType(key).value);495    obj[key](req, this, next);496  } else if (fn) {497    fn();498  } else {499    var err = new Error('Not Acceptable');500    err.status = 406;501    err.types = normalizeTypes(keys).map(function(o){ return o.value });502    next(err);503  }504505  return this;506};507508/**509 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.510 *511 * @param {String} filename512 * @return {ServerResponse}513 * @api public514 */515516res.attachment = function(filename){517  if (filename) this.type(extname(filename));518  this.set('Content-Disposition', contentDisposition(filename));519  return this;520};521522/**523 * Set header `field` to `val`, or pass524 * an object of header fields.525 *526 * Examples:527 *528 *    res.set('Foo', ['bar', 'baz']);529 *    res.set('Accept', 'application/json');530 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });531 *532 * Aliased as `res.header()`.533 *534 * @param {String|Object|Array} field535 * @param {String} val536 * @return {ServerResponse} for chaining537 * @api public538 */539540res.set =541res.header = function(field, val){542  if (2 == arguments.length) {543    if (Array.isArray(val)) val = val.map(String);544    else val = String(val);545    if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {546      var charset = mime.charsets.lookup(val.split(';')[0]);547      if (charset) val += '; charset=' + charset.toLowerCase();548    }549    this.setHeader(field, val);550  } else {551    for (var key in field) {552      this.set(key, field[key]);553    }554  }555  return this;556};557558/**559 * Get value for header `field`.560 *561 * @param {String} field562 * @return {String}563 * @api public564 */565566res.get = function(field){567  return this.getHeader(field);568};569570/**571 * Clear cookie `name`.572 *573 * @param {String} name574 * @param {Object} options575 * @param {ServerResponse} for chaining576 * @api public577 */578579res.clearCookie = function(name, options){580  var opts = { expires: new Date(1), path: '/' };581  return this.cookie(name, '', options582    ? mixin(opts, options)583    : opts);584};585586/**587 * Set cookie `name` to `val`, with the given `options`.588 *589 * Options:590 *591 *    - `maxAge`   max-age in milliseconds, converted to `expires`592 *    - `signed`   sign the cookie593 *    - `path`     defaults to "/"594 *595 * Examples:596 *597 *    // "Remember Me" for 15 minutes598 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });599 *600 *    // save as above601 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })602 *603 * @param {String} name604 * @param {String|Object} val605 * @param {Options} options606 * @api public607 */608609res.cookie = function(name, val, options){610  options = mixin({}, options);611  var secret = this.req.secret;612  var signed = options.signed;613  if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');614  if ('number' == typeof val) val = val.toString();615  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);616  if (signed) val = 's:' + sign(val, secret);617  if ('maxAge' in options) {618    options.expires = new Date(Date.now() + options.maxAge);619    options.maxAge /= 1000;620  }621  if (null == options.path) options.path = '/';622  var headerVal = cookie.serialize(name, String(val), options);623624  // supports multiple 'res.cookie' calls by getting previous value625  var prev = this.get('Set-Cookie');626  if (prev) {627    if (Array.isArray(prev)) {628      headerVal = prev.concat(headerVal);629    } else {630      headerVal = [prev, headerVal];631    }632  }633  this.set('Set-Cookie', headerVal);634  return this;635};636637638/**639 * Set the location header to `url`.640 *641 * The given `url` can also be "back", which redirects642 * to the _Referrer_ or _Referer_ headers or "/".643 *644 * Examples:645 *646 *    res.location('/foo/bar').;647 *    res.location('http://example.com');648 *    res.location('../login');649 *650 * @param {String} url651 * @api public652 */653654res.location = function(url){655  var req = this.req;656657  // "back" is an alias for the referrer658  if ('back' == url) url = req.get('Referrer') || '/';659660  // Respond661  this.set('Location', url);662  return this;663};664665/**666 * Redirect to the given `url` with optional response `status`667 * defaulting to 302.668 *669 * The resulting `url` is determined by `res.location()`, so670 * it will play nicely with mounted apps, relative paths,671 * `"back"` etc.672 *673 * Examples:674 *675 *    res.redirect('/foo/bar');676 *    res.redirect('http://example.com');677 *    res.redirect(301, 'http://example.com');678 *    res.redirect('http://example.com', 301);679 *    res.redirect('../login'); // /blog/post/1 -> /blog/login680 *681 * @param {String} url682 * @param {Number} code683 * @api public684 */685686res.redirect = function(url){687  var head = 'HEAD' == this.req.method;688  var status = 302;689  var body;690691  // allow status / url692  if (2 == arguments.length) {693    if ('number' == typeof url) {694      status = url;695      url = arguments[1];696    } else {697      status = arguments[1];698    }699  }700701  // Set location header702  this.location(url);703  url = this.get('Location');704705  // Support text/{plain,html} by default706  this.format({707    text: function(){708      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);709    },710711    html: function(){712      var u = escapeHtml(url);713      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';714    },715716    default: function(){717      body = '';718    }719  });720721  // Respond722  this.statusCode = status;723  this.set('Content-Length', Buffer.byteLength(body));724  this.end(head ? null : body);725};726727/**728 * Add `field` to Vary. If already present in the Vary set, then729 * this call is simply ignored.730 *731 * @param {Array|String} field732 * @param {ServerResponse} for chaining733 * @api public734 */735736res.vary = function(field){737  var self = this;738739  // nothing740  if (!field) return this;741742  // array743  if (Array.isArray(field)) {744    field.forEach(function(field){745      self.vary(field);746    });747    return;748  }749750  var vary = this.get('Vary');751752  // append753  if (vary) {754    vary = vary.split(/ *, */);755    if (!~vary.indexOf(field)) vary.push(field);756    this.set('Vary', vary.join(', '));757    return this;758  }759760  // set761  this.set('Vary', field);762  return this;763};764765/**766 * Render `view` with the given `options` and optional callback `fn`.767 * When a callback function is given a response will _not_ be made768 * automatically, otherwise a response of _200_ and _text/html_ is given.769 *770 * Options:771 *772 *  - `cache`     boolean hinting to the engine it should cache773 *  - `filename`  filename of the view being rendered774 *775 * @param  {String} view776 * @param  {Object|Function} options or callback function777 * @param  {Function} fn778 * @api public779 */780781res.render = function(view, options, fn){782  options = options || {};783  var self = this;784  var req = this.req;785  var app = req.app;786787  // support callback function as second arg788  if ('function' == typeof options) {789    fn = options, options = {};790  }791792  // merge res.locals793  options._locals = self.locals;794795  // default callback to respond796  fn = fn || function(err, str){797    if (err) return req.next(err);798    self.send(str);799  };800801  // render802  app.render(view, options, fn);803};