Skip to content
Myr

response.js

This file

Path

lib/response.js

829 lines · 19.7 KiB · JavaScript

Last changed by

Fix original URL parsing in res.locationDouglas Christopher Wilsonbefore adoptiona57efea

History of this file

Take it

1/**2 * Module dependencies.3 */45var deprecate = require('depd')('express');6var escapeHtml = require('escape-html');7var parseUrl = require('parseurl');8var vary = require('vary');9var http = require('http')10  , path = require('path')11  , connect = require('connect')12  , utils = connect.utils13  , sign = require('cookie-signature').sign14  , normalizeType = require('./utils').normalizeType15  , normalizeTypes = require('./utils').normalizeTypes16  , setCharset = require('./utils').setCharset17  , statusCodes = http.STATUS_CODES18  , cookie = require('cookie')19  , send = require('send')20  , mime = connect.mime21  , resolve = require('url').resolve22  , basename = path.basename23  , extname = path.extname;2425/**26 * Response prototype.27 */2829var res = module.exports = {30  __proto__: http.ServerResponse.prototype31};3233/**34 * Set status `code`.35 *36 * @param {Number} code37 * @return {ServerResponse}38 * @api public39 */4041res.status = function(code){42  this.statusCode = code;43  return this;44};4546/**47 * Set Link header field with the given `links`.48 *49 * Examples:50 *51 *    res.links({52 *      next: 'http://api.example.com/users?page=2',53 *      last: 'http://api.example.com/users?page=5'54 *    });55 *56 * @param {Object} links57 * @return {ServerResponse}58 * @api public59 */6061res.links = function(links){62  var link = this.get('Link') || '';63  if (link) link += ', ';64  return this.set('Link', link + Object.keys(links).map(function(rel){65    return '<' + links[rel] + '>; rel="' + rel + '"';66  }).join(', '));67};6869/**70 * Send a response.71 *72 * Examples:73 *74 *     res.send(new Buffer('wahoo'));75 *     res.send({ some: 'json' });76 *     res.send('<p>some html</p>');77 *     res.send(404, 'Sorry, cant find that');78 *     res.send(404);79 *80 * @param {Mixed} body or status81 * @param {Mixed} body82 * @return {ServerResponse}83 * @api public84 */8586res.send = function(body){87  var req = this.req;88  var head = 'HEAD' == req.method;89  var type;90  var encoding;91  var len;9293  // settings94  var app = this.app;9596  // allow status / body97  if (2 == arguments.length) {98    // res.send(body, status) backwards compat99    if ('number' != typeof body && 'number' == typeof arguments[1]) {100      this.statusCode = arguments[1];101    } else {102      this.statusCode = body;103      body = arguments[1];104    }105  }106107  // disambiguate res.send(status) and res.send(status, num)108  if (typeof body === 'number' && arguments.length === 1) {109    // res.send(status) will set status message as text string110    this.get('Content-Type') || this.type('txt');111    this.statusCode = body;112    body = http.STATUS_CODES[body];113  }114115  switch (typeof body) {116    // string defaulting to html117    case 'string':118      if (!this.get('Content-Type')) {119        this.charset = this.charset || 'utf-8';120        this.type('html');121      }122      break;123    case 'boolean':124    case 'number':125    case 'object':126      if (null == body) {127        body = '';128      } else if (Buffer.isBuffer(body)) {129        this.get('Content-Type') || this.type('bin');130      } else {131        return this.json(body);132      }133      break;134  }135136  // write strings in utf-8137  if ('string' === typeof body) {138    encoding = 'utf8';139    type = this.get('Content-Type');140141    // reflect this in content-type142    if ('string' === typeof type) {143      this.set('Content-Type', setCharset(type, 'utf-8'));144    }145  }146147  // populate Content-Length148  if (undefined !== body && !this.get('Content-Length')) {149    len = Buffer.isBuffer(body)150      ? body.length151      : Buffer.byteLength(body, encoding);152    this.set('Content-Length', len);153  }154155  // ETag support156  var etag = len !== undefined && app.get('etag fn');157  if (etag && ('GET' === req.method || 'HEAD' === req.method)) {158    if (!this.get('ETag')) {159      etag = etag(body, encoding);160      etag && this.set('ETag', etag);161    }162  }163164  // freshness165  if (req.fresh) this.statusCode = 304;166167  // strip irrelevant headers168  if (204 == this.statusCode || 304 == this.statusCode) {169    this.removeHeader('Content-Type');170    this.removeHeader('Content-Length');171    this.removeHeader('Transfer-Encoding');172    body = '';173  }174175  // respond176  this.end((head ? null : body), encoding);177178  return this;179};180181/**182 * Send JSON response.183 *184 * Examples:185 *186 *     res.json(null);187 *     res.json({ user: 'tj' });188 *     res.json(500, 'oh noes!');189 *     res.json(404, 'I dont have that');190 *191 * @param {Mixed} obj or status192 * @param {Mixed} obj193 * @return {ServerResponse}194 * @api public195 */196197res.json = function(obj){198  // allow status / body199  if (2 == arguments.length) {200    // res.json(body, status) backwards compat201    if ('number' == typeof arguments[1]) {202      this.statusCode = arguments[1];203      if (typeof obj === 'number') {204        deprecate('res.json(obj, status): Use res.json(status, obj) instead');205      } else {206        deprecate('res.json(num, status): Use res.status(status).json(num) instead');207      }208    } else {209      this.statusCode = obj;210      obj = arguments[1];211    }212  }213214  // settings215  var app = this.app;216  var replacer = app.get('json replacer');217  var spaces = app.get('json spaces');218  var body = JSON.stringify(obj, replacer, spaces);219220  // content-type221  this.charset = this.charset || 'utf-8';222  this.get('Content-Type') || this.set('Content-Type', 'application/json');223224  return this.send(body);225};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      if (typeof obj === 'number') {250        deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');251      } else {252        deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');253      }254    } else {255      this.statusCode = obj;256      obj = arguments[1];257    }258  }259260  // settings261  var app = this.app;262  var replacer = app.get('json replacer');263  var spaces = app.get('json spaces');264  var body = JSON.stringify(obj, replacer, spaces);265  var callback = this.req.query[app.get('jsonp callback name')];266267  // content-type268  if (!this.get('Content-Type')) {269    this.charset = 'utf-8';270    this.set('X-Content-Type-Options', 'nosniff');271    this.set('Content-Type', 'application/json');272  }273274  // fixup callback275  if (Array.isArray(callback)) {276    callback = callback[0];277  }278279  // jsonp280  if (typeof callback === 'string' && callback.length !== 0) {281    this.charset = 'utf-8';282    this.set('X-Content-Type-Options', 'nosniff');283    this.set('Content-Type', 'text/javascript');284285    // restrict callback charset286    callback = callback.replace(/[^\[\]\w$.]/g, '');287288    // replace chars not allowed in JavaScript that are in JSON289    body = body290      .replace(/\u2028/g, '\\u2028')291      .replace(/\u2029/g, '\\u2029');292293    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"294    // the typeof check is just to reduce client error noise295    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';296  }297298  return this.send(body);299};300301/**302 * Transfer the file at the given `path`.303 *304 * Automatically sets the _Content-Type_ response header field.305 * The callback `fn(err)` is invoked when the transfer is complete306 * or when an error occurs. Be sure to check `res.sentHeader`307 * if you wish to attempt responding, as the header and some data308 * may have already been transferred.309 *310 * Options:311 *312 *   - `maxAge`   defaulting to 0313 *   - `root`     root directory for relative filenames314 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them315 *316 * Other options are passed along to `send`.317 *318 * Examples:319 *320 *  The following example illustrates how `res.sendfile()` may321 *  be used as an alternative for the `static()` middleware for322 *  dynamic situations. The code backing `res.sendfile()` is actually323 *  the same code, so HTTP cache support etc is identical.324 *325 *     app.get('/user/:uid/photos/:file', function(req, res){326 *       var uid = req.params.uid327 *         , file = req.params.file;328 *329 *       req.user.mayViewFilesFrom(uid, function(yes){330 *         if (yes) {331 *           res.sendfile('/uploads/' + uid + '/' + file);332 *         } else {333 *           res.send(403, 'Sorry! you cant see that.');334 *         }335 *       });336 *     });337 *338 * @param {String} path339 * @param {Object|Function} options or fn340 * @param {Function} fn341 * @api public342 */343344res.sendfile = function(path, options, fn){345  var self = this346    , req = self.req347    , next = this.req.next348    , options = options || {}349    , done;350351  // support function as second arg352  if ('function' == typeof options) {353    fn = options;354    options = {};355  }356357  // socket errors358  req.socket.on('error', error);359360  // errors361  function error(err) {362    if (done) return;363    done = true;364365    // clean up366    cleanup();367    if (!self.headersSent) self.removeHeader('Content-Disposition');368369    // callback available370    if (fn) return fn(err);371372    // list in limbo if there's no callback373    if (self.headersSent) return;374375    // delegate376    next(err);377  }378379  // streaming380  function stream(stream) {381    if (done) return;382    cleanup();383    if (fn) stream.on('end', fn);384  }385386  // cleanup387  function cleanup() {388    req.socket.removeListener('error', error);389  }390391  // transfer392  var file = send(req, path, options);393  file.on('error', error);394  file.on('directory', next);395  file.on('stream', stream);396  file.pipe(this);397  this.on('finish', cleanup);398};399400/**401 * Transfer the file at the given `path` as an attachment.402 *403 * Optionally providing an alternate attachment `filename`,404 * and optional callback `fn(err)`. The callback is invoked405 * when the data transfer is complete, or when an error has406 * ocurred. Be sure to check `res.headersSent` if you plan to respond.407 *408 * This method uses `res.sendfile()`.409 *410 * @param {String} path411 * @param {String|Function} filename or fn412 * @param {Function} fn413 * @api public414 */415416res.download = function(path, filename, fn){417  // support function as second arg418  if ('function' == typeof filename) {419    fn = filename;420    filename = null;421  }422423  filename = filename || path;424  this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');425  return this.sendfile(path, fn);426};427428/**429 * Set _Content-Type_ response header with `type` through `mime.lookup()`430 * when it does not contain "/", or set the Content-Type to `type` otherwise.431 *432 * Examples:433 *434 *     res.type('.html');435 *     res.type('html');436 *     res.type('json');437 *     res.type('application/json');438 *     res.type('png');439 *440 * @param {String} type441 * @return {ServerResponse} for chaining442 * @api public443 */444445res.contentType =446res.type = function(type){447  return this.set('Content-Type', ~type.indexOf('/')448    ? type449    : mime.lookup(type));450};451452/**453 * Respond to the Acceptable formats using an `obj`454 * of mime-type callbacks.455 *456 * This method uses `req.accepted`, an array of457 * acceptable types ordered by their quality values.458 * When "Accept" is not present the _first_ callback459 * is invoked, otherwise the first match is used. When460 * no match is performed the server responds with461 * 406 "Not Acceptable".462 *463 * Content-Type is set for you, however if you choose464 * you may alter this within the callback using `res.type()`465 * or `res.set('Content-Type', ...)`.466 *467 *    res.format({468 *      'text/plain': function(){469 *        res.send('hey');470 *      },471 *472 *      'text/html': function(){473 *        res.send('<p>hey</p>');474 *      },475 *476 *      'appliation/json': function(){477 *        res.send({ message: 'hey' });478 *      }479 *    });480 *481 * In addition to canonicalized MIME types you may482 * also use extnames mapped to these types:483 *484 *    res.format({485 *      text: function(){486 *        res.send('hey');487 *      },488 *489 *      html: function(){490 *        res.send('<p>hey</p>');491 *      },492 *493 *      json: function(){494 *        res.send({ message: 'hey' });495 *      }496 *    });497 *498 * By default Express passes an `Error`499 * with a `.status` of 406 to `next(err)`500 * if a match is not made. If you provide501 * a `.default` callback it will be invoked502 * instead.503 *504 * @param {Object} obj505 * @return {ServerResponse} for chaining506 * @api public507 */508509res.format = function(obj){510  var req = this.req511    , next = req.next;512513  var fn = obj.default;514  if (fn) delete obj.default;515  var keys = Object.keys(obj);516517  var key = req.accepts(keys);518519  this.vary("Accept");520521  if (key) {522    var type = normalizeType(key).value;523    var charset = mime.charsets.lookup(type);524    if (charset) type += '; charset=' + charset;525    this.set('Content-Type', type);526    obj[key](req, this, next);527  } else if (fn) {528    fn();529  } else {530    var err = new Error('Not Acceptable');531    err.status = 406;532    err.types = normalizeTypes(keys).map(function(o){ return o.value });533    next(err);534  }535536  return this;537};538539/**540 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.541 *542 * @param {String} filename543 * @return {ServerResponse}544 * @api public545 */546547res.attachment = function(filename){548  if (filename) this.type(extname(filename));549  this.set('Content-Disposition', filename550    ? 'attachment; filename="' + basename(filename) + '"'551    : 'attachment');552  return this;553};554555/**556 * Set header `field` to `val`, or pass557 * an object of header fields.558 *559 * Examples:560 *561 *    res.set('Foo', ['bar', 'baz']);562 *    res.set('Accept', 'application/json');563 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });564 *565 * Aliased as `res.header()`.566 *567 * @param {String|Object|Array} field568 * @param {String} val569 * @return {ServerResponse} for chaining570 * @api public571 */572573res.set =574res.header = function(field, val){575  if (2 == arguments.length) {576    if (Array.isArray(val)) val = val.map(String);577    else val = String(val);578    this.setHeader(field, val);579  } else {580    for (var key in field) {581      this.set(key, field[key]);582    }583  }584  return this;585};586587/**588 * Get value for header `field`.589 *590 * @param {String} field591 * @return {String}592 * @api public593 */594595res.get = function(field){596  return this.getHeader(field);597};598599/**600 * Clear cookie `name`.601 *602 * @param {String} name603 * @param {Object} options604 * @param {ServerResponse} for chaining605 * @api public606 */607608res.clearCookie = function(name, options){609  var opts = { expires: new Date(1), path: '/' };610  return this.cookie(name, '', options611    ? utils.merge(opts, options)612    : opts);613};614615/**616 * Set cookie `name` to `val`, with the given `options`.617 *618 * Options:619 *620 *    - `maxAge`   max-age in milliseconds, converted to `expires`621 *    - `signed`   sign the cookie622 *    - `path`     defaults to "/"623 *624 * Examples:625 *626 *    // "Remember Me" for 15 minutes627 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });628 *629 *    // save as above630 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })631 *632 * @param {String} name633 * @param {String|Object} val634 * @param {Options} options635 * @api public636 */637638res.cookie = function(name, val, options){639  options = utils.merge({}, options);640  var secret = this.req.secret;641  var signed = options.signed;642  if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');643  if ('number' == typeof val) val = val.toString();644  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);645  if (signed) val = 's:' + sign(val, secret);646  if ('maxAge' in options) {647    options.expires = new Date(Date.now() + options.maxAge);648    options.maxAge /= 1000;649  }650  if (null == options.path) options.path = '/';651  this.set('Set-Cookie', cookie.serialize(name, String(val), options));652  return this;653};654655656/**657 * Set the location header to `url`.658 *659 * The given `url` can also be "back", which redirects660 * to the _Referrer_ or _Referer_ headers or "/".661 *662 * Examples:663 *664 *    res.location('/foo/bar').;665 *    res.location('http://example.com');666 *    res.location('../login'); // /blog/post/1 -> /blog/login667 *668 * Mounting:669 *670 *   When an application is mounted and `res.location()`671 *   is given a path that does _not_ lead with "/" it becomes672 *   relative to the mount-point. For example if the application673 *   is mounted at "/blog", the following would become "/blog/login".674 *675 *      res.location('login');676 *677 *   While the leading slash would result in a location of "/login":678 *679 *      res.location('/login');680 *681 * @param {String} url682 * @api public683 */684685res.location = function(url){686  var app = this.app687    , req = this.req688    , path;689690  // "back" is an alias for the referrer691  if ('back' == url) url = req.get('Referrer') || '/';692693  // relative694  if (!~url.indexOf('://') && 0 != url.indexOf('//')) {695    // relative to path696    if ('.' == url[0]) {697      path = parseUrl.original(req).pathname;698      path = path + ('/' == path[path.length - 1] ? '' : '/');699      url = resolve(path, url);700      // relative to mount-point701    } else if ('/' != url[0]) {702      path = app.path();703      url = path + '/' + url;704    }705  }706707  // Respond708  this.set('Location', url);709  return this;710};711712/**713 * Redirect to the given `url` with optional response `status`714 * defaulting to 302.715 *716 * The resulting `url` is determined by `res.location()`, so717 * it will play nicely with mounted apps, relative paths,718 * `"back"` etc.719 *720 * Examples:721 *722 *    res.redirect('/foo/bar');723 *    res.redirect('http://example.com');724 *    res.redirect(301, 'http://example.com');725 *    res.redirect('../login'); // /blog/post/1 -> /blog/login726 *727 * @api public728 */729730res.redirect = function(url){731  var head = 'HEAD' == this.req.method732    , status = 302733    , body;734735  // allow status / url736  if (2 == arguments.length) {737    if ('number' == typeof url) {738      status = url;739      url = arguments[1];740    } else {741      deprecate('res.redirect(ur, status): Use res.redirect(status, url) instead');742      status = arguments[1];743    }744  }745746  // Set location header747  this.location(url);748  url = this.get('Location');749750  // Support text/{plain,html} by default751  this.format({752    text: function(){753      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);754    },755756    html: function(){757      var u = escapeHtml(url);758      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';759    },760761    default: function(){762      body = '';763    }764  });765766  // Respond767  this.statusCode = status;768  this.set('Content-Length', Buffer.byteLength(body));769  this.end(head ? null : body);770};771772/**773 * Add `field` to Vary. If already present in the Vary set, then774 * this call is simply ignored.775 *776 * @param {Array|String} field777 * @param {ServerResponse} for chaining778 * @api public779 */780781res.vary = function(field){782  // checks for back-compat783  if (!field) return this;784  if (Array.isArray(field) && !field.length) return this;785786  vary(this, field);787788  return this;789};790791/**792 * Render `view` with the given `options` and optional callback `fn`.793 * When a callback function is given a response will _not_ be made794 * automatically, otherwise a response of _200_ and _text/html_ is given.795 *796 * Options:797 *798 *  - `cache`     boolean hinting to the engine it should cache799 *  - `filename`  filename of the view being rendered800 *801 * @param  {String} view802 * @param  {Object|Function} options or callback function803 * @param  {Function} fn804 * @api public805 */806807res.render = function(view, options, fn){808  var self = this809    , options = options || {}810    , req = this.req811    , app = req.app;812813  // support callback function as second arg814  if ('function' == typeof options) {815    fn = options, options = {};816  }817818  // merge res.locals819  options._locals = self.locals;820821  // default callback to respond822  fn = fn || function(err, str){823    if (err) return req.next(err);824    self.send(str);825  };826827  // render828  app.render(view, options, fn);829};