Skip to content
Myr

response.js

This file

Path

lib/response.js

955 lines · 22.4 KiB · JavaScript

Last changed by

Remove unused variablelemmybefore adoptiond2d0aff

History of this file

Take it

1/**2 * Module dependencies.3 */45var deprecate = require('depd')('express');6var escapeHtml = require('escape-html');7var http = require('http');8var isAbsolute = require('./utils').isAbsolute;9var path = require('path');10var mixin = require('utils-merge');11var sign = require('cookie-signature').sign;12var normalizeType = require('./utils').normalizeType;13var normalizeTypes = require('./utils').normalizeTypes;14var setCharset = require('./utils').setCharset;15var contentDisposition = require('./utils').contentDisposition;16var statusCodes = http.STATUS_CODES;17var cookie = require('cookie');18var send = require('send');19var extname = path.extname;20var mime = send.mime;21var resolve = path.resolve;22var vary = require('vary');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 *77 * @param {string|number|boolean|object|Buffer} body78 * @api public79 */8081res.send = function send(body) {82  var chunk = body;83  var encoding;84  var len;85  var req = this.req;86  var type;8788  // settings89  var app = this.app;9091  // allow status / body92  if (arguments.length === 2) {93    // res.send(body, status) backwards compat94    if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {95      deprecate('res.send(body, status): Use res.status(status).send(body) instead');96      this.statusCode = arguments[1];97    } else {98      deprecate('res.send(status, body): Use res.status(status).send(body) instead');99      this.statusCode = arguments[0];100      chunk = arguments[1];101    }102  }103104  // disambiguate res.send(status) and res.send(status, num)105  if (typeof chunk === 'number' && arguments.length === 1) {106    // res.send(status) will set status message as text string107    if (!this.get('Content-Type')) {108      this.type('txt');109    }110111    deprecate('res.send(status): Use res.status(status).end() instead');112    this.statusCode = chunk;113    chunk = http.STATUS_CODES[chunk];114  }115116  switch (typeof chunk) {117    // string defaulting to html118    case 'string':119      if (!this.get('Content-Type')) {120        this.type('html');121      }122      break;123    case 'boolean':124    case 'number':125    case 'object':126      if (chunk === null) {127        chunk = '';128      } else if (Buffer.isBuffer(chunk)) {129        if (!this.get('Content-Type')) {130          this.type('bin');131        }132      } else {133        return this.json(chunk);134      }135      break;136  }137138  // write strings in utf-8139  if (typeof chunk === 'string') {140    encoding = 'utf8';141    type = this.get('Content-Type');142143    // reflect this in content-type144    if (typeof type === 'string') {145      this.set('Content-Type', setCharset(type, 'utf-8'));146    }147  }148149  // populate Content-Length150  if (chunk !== undefined) {151    if (!Buffer.isBuffer(chunk)) {152      // convert chunk to Buffer; saves later double conversions153      chunk = new Buffer(chunk, encoding);154      encoding = undefined;155    }156157    len = chunk.length;158    this.set('Content-Length', len);159  }160161  // method check162  var isHead = req.method === 'HEAD';163164  // ETag support165  if (len !== undefined && (isHead || req.method === 'GET')) {166    var etag = app.get('etag fn');167    if (etag && !this.get('ETag')) {168      etag = etag(chunk, encoding);169      etag && this.set('ETag', etag);170    }171  }172173  // freshness174  if (req.fresh) this.statusCode = 304;175176  // strip irrelevant headers177  if (204 == this.statusCode || 304 == this.statusCode) {178    this.removeHeader('Content-Type');179    this.removeHeader('Content-Length');180    this.removeHeader('Transfer-Encoding');181    chunk = '';182  }183184  // skip body for HEAD185  if (isHead) {186    this.end();187  }188189  // respond190  this.end(chunk, encoding);191192  return this;193};194195/**196 * Send JSON response.197 *198 * Examples:199 *200 *     res.json(null);201 *     res.json({ user: 'tj' });202 *203 * @param {string|number|boolean|object} obj204 * @api public205 */206207res.json = function json(obj) {208  var val = obj;209210  // allow status / body211  if (arguments.length === 2) {212    // res.json(body, status) backwards compat213    if (typeof arguments[1] === 'number') {214      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');215      this.statusCode = arguments[1];216    } else {217      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');218      this.statusCode = arguments[0];219      val = arguments[1];220    }221  }222223  // settings224  var app = this.app;225  var replacer = app.get('json replacer');226  var spaces = app.get('json spaces');227  var body = JSON.stringify(val, replacer, spaces);228229  // content-type230  if (!this.get('Content-Type')) {231    this.set('Content-Type', 'application/json');232  }233234  return this.send(body);235};236237/**238 * Send JSON response with JSONP callback support.239 *240 * Examples:241 *242 *     res.jsonp(null);243 *     res.jsonp({ user: 'tj' });244 *245 * @param {string|number|boolean|object} obj246 * @api public247 */248249res.jsonp = function jsonp(obj) {250  var val = obj;251252  // allow status / body253  if (arguments.length === 2) {254    // res.json(body, status) backwards compat255    if (typeof arguments[1] === 'number') {256      deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');257      this.statusCode = arguments[1];258    } else {259      deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');260      this.statusCode = arguments[0];261      val = arguments[1];262    }263  }264265  // settings266  var app = this.app;267  var replacer = app.get('json replacer');268  var spaces = app.get('json spaces');269  var body = JSON.stringify(val, replacer, spaces);270  var callback = this.req.query[app.get('jsonp callback name')];271272  // content-type273  if (!this.get('Content-Type')) {274    this.set('X-Content-Type-Options', 'nosniff');275    this.set('Content-Type', 'application/json');276  }277278  // fixup callback279  if (Array.isArray(callback)) {280    callback = callback[0];281  }282283  // jsonp284  if (typeof callback === 'string' && callback.length !== 0) {285    this.charset = 'utf-8';286    this.set('X-Content-Type-Options', 'nosniff');287    this.set('Content-Type', 'text/javascript');288289    // restrict callback charset290    callback = callback.replace(/[^\[\]\w$.]/g, '');291292    // replace chars not allowed in JavaScript that are in JSON293    body = body294      .replace(/\u2028/g, '\\u2028')295      .replace(/\u2029/g, '\\u2029');296297    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"298    // the typeof check is just to reduce client error noise299    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';300  }301302  return this.send(body);303};304305/**306 * Transfer the file at the given `path`.307 *308 * Automatically sets the _Content-Type_ response header field.309 * The callback `fn(err)` is invoked when the transfer is complete310 * or when an error occurs. Be sure to check `res.sentHeader`311 * if you wish to attempt responding, as the header and some data312 * may have already been transferred.313 *314 * Options:315 *316 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)317 *   - `root`     root directory for relative filenames318 *   - `headers`  object of headers to serve with file319 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them320 *321 * Other options are passed along to `send`.322 *323 * Examples:324 *325 *  The following example illustrates how `res.sendFile()` may326 *  be used as an alternative for the `static()` middleware for327 *  dynamic situations. The code backing `res.sendFile()` is actually328 *  the same code, so HTTP cache support etc is identical.329 *330 *     app.get('/user/:uid/photos/:file', function(req, res){331 *       var uid = req.params.uid332 *         , file = req.params.file;333 *334 *       req.user.mayViewFilesFrom(uid, function(yes){335 *         if (yes) {336 *           res.sendFile('/uploads/' + uid + '/' + file);337 *         } else {338 *           res.send(403, 'Sorry! you cant see that.');339 *         }340 *       });341 *     });342 *343 * @api public344 */345346res.sendFile = function sendFile(path, options, fn) {347  var done;348  var req = this.req;349  var next = req.next;350351  if (!path) {352    throw new TypeError('path argument is required to res.sendFile');353  }354355  // support function as second arg356  if (typeof options === 'function') {357    fn = options;358    options = {};359  }360361  options = options || {};362363  if (!options.root && !isAbsolute(path)) {364    throw new TypeError('path must be absolute or specify root to res.sendFile');365  }366367  // socket errors368  req.socket.on('error', onerror);369370  // errors371  function onerror(err) {372    if (done) return;373    done = true;374375    // clean up376    cleanup();377378    // callback available379    if (fn) return fn(err);380381    // delegate382    next(err);383  }384385  // streaming386  function onstream(stream) {387    if (done) return;388    cleanup();389    if (fn) stream.on('end', fn);390  }391392  // cleanup393  function cleanup() {394    req.socket.removeListener('error', onerror);395  }396397  // transfer398  var pathname = encodeURI(path);399  var file = send(req, pathname, options);400  file.on('error', onerror);401  file.on('directory', next);402  file.on('stream', onstream);403404  if (options.headers) {405    // set headers on successful transfer406    file.on('headers', function headers(res) {407      var obj = options.headers;408      var keys = Object.keys(obj);409410      for (var i = 0; i < keys.length; i++) {411        var k = keys[i];412        res.setHeader(k, obj[k]);413      }414    });415  }416417  // pipe418  file.pipe(this);419  this.on('finish', cleanup);420};421422/**423 * Transfer the file at the given `path`.424 *425 * Automatically sets the _Content-Type_ response header field.426 * The callback `fn(err)` is invoked when the transfer is complete427 * or when an error occurs. Be sure to check `res.sentHeader`428 * if you wish to attempt responding, as the header and some data429 * may have already been transferred.430 *431 * Options:432 *433 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)434 *   - `root`     root directory for relative filenames435 *   - `headers`  object of headers to serve with file436 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them437 *438 * Other options are passed along to `send`.439 *440 * Examples:441 *442 *  The following example illustrates how `res.sendfile()` may443 *  be used as an alternative for the `static()` middleware for444 *  dynamic situations. The code backing `res.sendfile()` is actually445 *  the same code, so HTTP cache support etc is identical.446 *447 *     app.get('/user/:uid/photos/:file', function(req, res){448 *       var uid = req.params.uid449 *         , file = req.params.file;450 *451 *       req.user.mayViewFilesFrom(uid, function(yes){452 *         if (yes) {453 *           res.sendfile('/uploads/' + uid + '/' + file);454 *         } else {455 *           res.send(403, 'Sorry! you cant see that.');456 *         }457 *       });458 *     });459 *460 * @api public461 */462463res.sendfile = function(path, options, fn){464  options = options || {};465  var self = this;466  var req = self.req;467  var next = this.req.next;468  var done;469470471  // support function as second arg472  if ('function' == typeof options) {473    fn = options;474    options = {};475  }476477  // socket errors478  req.socket.on('error', error);479480  // errors481  function error(err) {482    if (done) return;483    done = true;484485    // clean up486    cleanup();487488    // callback available489    if (fn) return fn(err);490491    // delegate492    next(err);493  }494495  // streaming496  function stream(stream) {497    if (done) return;498    cleanup();499    if (fn) stream.on('end', fn);500  }501502  // cleanup503  function cleanup() {504    req.socket.removeListener('error', error);505  }506507  // transfer508  var file = send(req, path, options);509  file.on('error', error);510  file.on('directory', next);511  file.on('stream', stream);512513  if (options.headers) {514    // set headers on successful transfer515    file.on('headers', function headers(res) {516      var obj = options.headers;517      var keys = Object.keys(obj);518519      for (var i = 0; i < keys.length; i++) {520        var k = keys[i];521        res.setHeader(k, obj[k]);522      }523    });524  }525526  // pipe527  file.pipe(this);528  this.on('finish', cleanup);529};530531res.sendfile = deprecate.function(res.sendfile,532  'res.sendfile: Use res.sendFile instead');533534/**535 * Transfer the file at the given `path` as an attachment.536 *537 * Optionally providing an alternate attachment `filename`,538 * and optional callback `fn(err)`. The callback is invoked539 * when the data transfer is complete, or when an error has540 * ocurred. Be sure to check `res.headersSent` if you plan to respond.541 *542 * This method uses `res.sendfile()`.543 *544 * @api public545 */546547res.download = function download(path, filename, fn) {548  // support function as second arg549  if (typeof filename === 'function') {550    fn = filename;551    filename = null;552  }553554  filename = filename || path;555556  // set Content-Disposition when file is sent557  var headers = {558    'Content-Disposition': contentDisposition(filename)559  };560561  // Resolve the full path for sendFile562  var fullPath = resolve(path);563564  return this.sendFile(fullPath, { headers: headers }, fn);565};566567/**568 * Set _Content-Type_ response header with `type` through `mime.lookup()`569 * when it does not contain "/", or set the Content-Type to `type` otherwise.570 *571 * Examples:572 *573 *     res.type('.html');574 *     res.type('html');575 *     res.type('json');576 *     res.type('application/json');577 *     res.type('png');578 *579 * @param {String} type580 * @return {ServerResponse} for chaining581 * @api public582 */583584res.contentType =585res.type = function(type){586  return this.set('Content-Type', ~type.indexOf('/')587    ? type588    : mime.lookup(type));589};590591/**592 * Respond to the Acceptable formats using an `obj`593 * of mime-type callbacks.594 *595 * This method uses `req.accepted`, an array of596 * acceptable types ordered by their quality values.597 * When "Accept" is not present the _first_ callback598 * is invoked, otherwise the first match is used. When599 * no match is performed the server responds with600 * 406 "Not Acceptable".601 *602 * Content-Type is set for you, however if you choose603 * you may alter this within the callback using `res.type()`604 * or `res.set('Content-Type', ...)`.605 *606 *    res.format({607 *      'text/plain': function(){608 *        res.send('hey');609 *      },610 *611 *      'text/html': function(){612 *        res.send('<p>hey</p>');613 *      },614 *615 *      'appliation/json': function(){616 *        res.send({ message: 'hey' });617 *      }618 *    });619 *620 * In addition to canonicalized MIME types you may621 * also use extnames mapped to these types:622 *623 *    res.format({624 *      text: function(){625 *        res.send('hey');626 *      },627 *628 *      html: function(){629 *        res.send('<p>hey</p>');630 *      },631 *632 *      json: function(){633 *        res.send({ message: 'hey' });634 *      }635 *    });636 *637 * By default Express passes an `Error`638 * with a `.status` of 406 to `next(err)`639 * if a match is not made. If you provide640 * a `.default` callback it will be invoked641 * instead.642 *643 * @param {Object} obj644 * @return {ServerResponse} for chaining645 * @api public646 */647648res.format = function(obj){649  var req = this.req;650  var next = req.next;651652  var fn = obj.default;653  if (fn) delete obj.default;654  var keys = Object.keys(obj);655656  var key = req.accepts(keys);657658  this.vary("Accept");659660  if (key) {661    this.set('Content-Type', normalizeType(key).value);662    obj[key](req, this, next);663  } else if (fn) {664    fn();665  } else {666    var err = new Error('Not Acceptable');667    err.status = 406;668    err.types = normalizeTypes(keys).map(function(o){ return o.value });669    next(err);670  }671672  return this;673};674675/**676 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.677 *678 * @param {String} filename679 * @return {ServerResponse}680 * @api public681 */682683res.attachment = function(filename){684  if (filename) this.type(extname(filename));685  this.set('Content-Disposition', contentDisposition(filename));686  return this;687};688689/**690 * Set header `field` to `val`, or pass691 * an object of header fields.692 *693 * Examples:694 *695 *    res.set('Foo', ['bar', 'baz']);696 *    res.set('Accept', 'application/json');697 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });698 *699 * Aliased as `res.header()`.700 *701 * @param {String|Object|Array} field702 * @param {String} val703 * @return {ServerResponse} for chaining704 * @api public705 */706707res.set =708res.header = function header(field, val) {709  if (arguments.length === 2) {710    if (Array.isArray(val)) val = val.map(String);711    else val = String(val);712    if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {713      var charset = mime.charsets.lookup(val.split(';')[0]);714      if (charset) val += '; charset=' + charset.toLowerCase();715    }716    this.setHeader(field, val);717  } else {718    for (var key in field) {719      this.set(key, field[key]);720    }721  }722  return this;723};724725/**726 * Get value for header `field`.727 *728 * @param {String} field729 * @return {String}730 * @api public731 */732733res.get = function(field){734  return this.getHeader(field);735};736737/**738 * Clear cookie `name`.739 *740 * @param {String} name741 * @param {Object} options742 * @return {ServerResponse} for chaining743 * @api public744 */745746res.clearCookie = function(name, options){747  var opts = { expires: new Date(1), path: '/' };748  return this.cookie(name, '', options749    ? mixin(opts, options)750    : opts);751};752753/**754 * Set cookie `name` to `val`, with the given `options`.755 *756 * Options:757 *758 *    - `maxAge`   max-age in milliseconds, converted to `expires`759 *    - `signed`   sign the cookie760 *    - `path`     defaults to "/"761 *762 * Examples:763 *764 *    // "Remember Me" for 15 minutes765 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });766 *767 *    // save as above768 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })769 *770 * @param {String} name771 * @param {String|Object} val772 * @param {Options} options773 * @return {ServerResponse} for chaining774 * @api public775 */776777res.cookie = function(name, val, options){778  options = mixin({}, options);779  var secret = this.req.secret;780  var signed = options.signed;781  if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');782  if ('number' == typeof val) val = val.toString();783  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);784  if (signed) val = 's:' + sign(val, secret);785  if ('maxAge' in options) {786    options.expires = new Date(Date.now() + options.maxAge);787    options.maxAge /= 1000;788  }789  if (null == options.path) options.path = '/';790  var headerVal = cookie.serialize(name, String(val), options);791792  // supports multiple 'res.cookie' calls by getting previous value793  var prev = this.get('Set-Cookie');794  if (prev) {795    if (Array.isArray(prev)) {796      headerVal = prev.concat(headerVal);797    } else {798      headerVal = [prev, headerVal];799    }800  }801  this.set('Set-Cookie', headerVal);802  return this;803};804805806/**807 * Set the location header to `url`.808 *809 * The given `url` can also be "back", which redirects810 * to the _Referrer_ or _Referer_ headers or "/".811 *812 * Examples:813 *814 *    res.location('/foo/bar').;815 *    res.location('http://example.com');816 *    res.location('../login');817 *818 * @param {String} url819 * @return {ServerResponse} for chaining820 * @api public821 */822823res.location = function(url){824  var req = this.req;825826  // "back" is an alias for the referrer827  if ('back' == url) url = req.get('Referrer') || '/';828829  // Respond830  this.set('Location', url);831  return this;832};833834/**835 * Redirect to the given `url` with optional response `status`836 * defaulting to 302.837 *838 * The resulting `url` is determined by `res.location()`, so839 * it will play nicely with mounted apps, relative paths,840 * `"back"` etc.841 *842 * Examples:843 *844 *    res.redirect('/foo/bar');845 *    res.redirect('http://example.com');846 *    res.redirect(301, 'http://example.com');847 *    res.redirect('../login'); // /blog/post/1 -> /blog/login848 *849 * @api public850 */851852res.redirect = function redirect(url) {853  var address = url;854  var body;855  var status = 302;856857  // allow status / url858  if (arguments.length === 2) {859    if (typeof arguments[0] === 'number') {860      status = arguments[0];861      address = arguments[1];862    } else {863      deprecate('res.redirect(ur, status): Use res.redirect(status, url) instead');864      status = arguments[1];865    }866  }867868  // Set location header869  this.location(address);870  address = this.get('Location');871872  // Support text/{plain,html} by default873  this.format({874    text: function(){875      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);876    },877878    html: function(){879      var u = escapeHtml(url);880      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';881    },882883    default: function(){884      body = '';885    }886  });887888  // Respond889  this.statusCode = status;890  this.set('Content-Length', Buffer.byteLength(body));891892  if (this.req.method === 'HEAD') {893    this.end();894  }895896  this.end(body);897};898899/**900 * Add `field` to Vary. If already present in the Vary set, then901 * this call is simply ignored.902 *903 * @param {Array|String} field904 * @return {ServerResponse} for chaining905 * @api public906 */907908res.vary = function(field){909  // checks for back-compat910  if (!field || (Array.isArray(field) && !field.length)) {911    deprecate('res.vary(): Provide a field name');912    return this;913  }914915  vary(this, field);916917  return this;918};919920/**921 * Render `view` with the given `options` and optional callback `fn`.922 * When a callback function is given a response will _not_ be made923 * automatically, otherwise a response of _200_ and _text/html_ is given.924 *925 * Options:926 *927 *  - `cache`     boolean hinting to the engine it should cache928 *  - `filename`  filename of the view being rendered929 *930 * @api public931 */932933res.render = function(view, options, fn){934  options = options || {};935  var self = this;936  var req = this.req;937  var app = req.app;938939  // support callback function as second arg940  if ('function' == typeof options) {941    fn = options, options = {};942  }943944  // merge res.locals945  options._locals = self.locals;946947  // default callback to respond948  fn = fn || function(err, str){949    if (err) return req.next(err);950    self.send(str);951  };952953  // render954  app.render(view, options, fn);955};