Skip to content
Myr

response.js

This file

Path

lib/response.js

841 lines · 19.5 KiB · JavaScript

Last changed by

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

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 path = require('path');9var mixin = require('utils-merge');10var sign = require('cookie-signature').sign;11var normalizeType = require('./utils').normalizeType;12var normalizeTypes = require('./utils').normalizeTypes;13var setCharset = require('./utils').setCharset;14var contentDisposition = require('./utils').contentDisposition;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;21var vary = require('vary');2223/**24 * Response prototype.25 */2627var res = module.exports = {28  __proto__: http.ServerResponse.prototype29};3031/**32 * Set status `code`.33 *34 * @param {Number} code35 * @return {ServerResponse}36 * @api public37 */3839res.status = function(code){40  this.statusCode = code;41  return this;42};4344/**45 * Set Link header field with the given `links`.46 *47 * Examples:48 *49 *    res.links({50 *      next: 'http://api.example.com/users?page=2',51 *      last: 'http://api.example.com/users?page=5'52 *    });53 *54 * @param {Object} links55 * @return {ServerResponse}56 * @api public57 */5859res.links = function(links){60  var link = this.get('Link') || '';61  if (link) link += ', ';62  return this.set('Link', link + Object.keys(links).map(function(rel){63    return '<' + links[rel] + '>; rel="' + rel + '"';64  }).join(', '));65};6667/**68 * Send a response.69 *70 * Examples:71 *72 *     res.send(new Buffer('wahoo'));73 *     res.send({ some: 'json' });74 *     res.send('<p>some html</p>');75 *     res.send(404, 'Sorry, cant find that');76 *     res.send(404);77 *78 * @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.send(status, body) instead');96      this.statusCode = arguments[1];97    } else {98      this.statusCode = arguments[0];99      chunk = arguments[1];100    }101  }102103  // disambiguate res.send(status) and res.send(status, num)104  if (typeof chunk === 'number' && arguments.length === 1) {105    // res.send(status) will set status message as text string106    if (!this.get('Content-Type')) {107      this.type('txt');108    }109110    this.statusCode = chunk;111    chunk = http.STATUS_CODES[chunk];112  }113114  switch (typeof chunk) {115    // string defaulting to html116    case 'string':117      if (!this.get('Content-Type')) {118        this.type('html');119      }120      break;121    case 'boolean':122    case 'number':123    case 'object':124      if (chunk === null) {125        chunk = '';126      } else if (Buffer.isBuffer(chunk)) {127        if (!this.get('Content-Type')) {128          this.type('bin');129        }130      } else {131        return this.json(chunk);132      }133      break;134  }135136  // write strings in utf-8137  if (typeof chunk === 'string') {138    encoding = 'utf8';139    type = this.get('Content-Type');140141    // reflect this in content-type142    if (typeof type === 'string') {143      this.set('Content-Type', setCharset(type, 'utf-8'));144    }145  }146147  // populate Content-Length148  if (chunk !== undefined) {149    if (!Buffer.isBuffer(chunk)) {150      // convert chunk to Buffer; saves later double conversions151      chunk = new Buffer(chunk, encoding);152      encoding = undefined;153    }154155    len = chunk.length;156    this.set('Content-Length', len);157  }158159  // method check160  var isHead = req.method === 'HEAD';161162  // ETag support163  if (len !== undefined && (isHead || req.method === 'GET')) {164    var etag = app.get('etag fn');165    if (etag && !this.get('ETag')) {166      etag = etag(chunk, encoding);167      etag && this.set('ETag', etag);168    }169  }170171  // freshness172  if (req.fresh) this.statusCode = 304;173174  // strip irrelevant headers175  if (204 == this.statusCode || 304 == this.statusCode) {176    this.removeHeader('Content-Type');177    this.removeHeader('Content-Length');178    this.removeHeader('Transfer-Encoding');179    chunk = '';180  }181182  // skip body for HEAD183  if (isHead) {184    this.end();185  }186187  // respond188  this.end(chunk, encoding);189190  return this;191};192193/**194 * Send JSON response.195 *196 * Examples:197 *198 *     res.json(null);199 *     res.json({ user: 'tj' });200 *     res.json(500, 'oh noes!');201 *     res.json(404, 'I dont have that');202 *203 * @api public204 */205206res.json = function json(obj) {207  var val = obj;208209  // allow status / body210  if (arguments.length === 2) {211    // res.json(body, status) backwards compat212    if (typeof arguments[1] === 'number') {213      this.statusCode = arguments[1];214      if (typeof arguments[0] === 'number') {215        deprecate('res.json(obj, status): Use res.json(status, obj) instead');216      } else {217        deprecate('res.json(num, status): Use res.status(status).json(num) instead');218      }219    } else {220      this.statusCode = arguments[0];221      val = arguments[1];222    }223  }224225  // settings226  var app = this.app;227  var replacer = app.get('json replacer');228  var spaces = app.get('json spaces');229  var body = JSON.stringify(val, replacer, spaces);230231  // content-type232  if (!this.get('Content-Type')) {233    this.set('Content-Type', 'application/json');234  }235236  return this.send(body);237};238239/**240 * Send JSON response with JSONP callback support.241 *242 * Examples:243 *244 *     res.jsonp(null);245 *     res.jsonp({ user: 'tj' });246 *     res.jsonp(500, 'oh noes!');247 *     res.jsonp(404, 'I dont have that');248 *249 * @api public250 */251252res.jsonp = function jsonp(obj) {253  var val = obj;254255  // allow status / body256  if (arguments.length === 2) {257    // res.json(body, status) backwards compat258    if (typeof arguments[1] === 'number') {259      this.statusCode = arguments[1];260      if (typeof arguments[0] === 'number') {261        deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');262      } else {263        deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');264      }265    } else {266      this.statusCode = arguments[0];267      val = arguments[1];268    }269  }270271  // settings272  var app = this.app;273  var replacer = app.get('json replacer');274  var spaces = app.get('json spaces');275  var body = JSON.stringify(val, replacer, spaces);276  var callback = this.req.query[app.get('jsonp callback name')];277278  // content-type279  if (!this.get('Content-Type')) {280    this.set('X-Content-Type-Options', 'nosniff');281    this.set('Content-Type', 'application/json');282  }283284  // fixup callback285  if (Array.isArray(callback)) {286    callback = callback[0];287  }288289  // jsonp290  if (typeof callback === 'string' && callback.length !== 0) {291    this.charset = 'utf-8';292    this.set('X-Content-Type-Options', 'nosniff');293    this.set('Content-Type', 'text/javascript');294295    // restrict callback charset296    callback = callback.replace(/[^\[\]\w$.]/g, '');297298    // replace chars not allowed in JavaScript that are in JSON299    body = body300      .replace(/\u2028/g, '\\u2028')301      .replace(/\u2029/g, '\\u2029');302303    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"304    // the typeof check is just to reduce client error noise305    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';306  }307308  return this.send(body);309};310311/**312 * Transfer the file at the given `path`.313 *314 * Automatically sets the _Content-Type_ response header field.315 * The callback `fn(err)` is invoked when the transfer is complete316 * or when an error occurs. Be sure to check `res.sentHeader`317 * if you wish to attempt responding, as the header and some data318 * may have already been transferred.319 *320 * Options:321 *322 *   - `maxAge`  defaulting to 0 (can be string converted by `ms`)323 *   - `root`    root directory for relative filenames324 *   - `headers` object of headers to serve with file325 *   - `hidden`  serve hidden files, defaulting to false326 *327 * Other options are passed along to `send`.328 *329 * Examples:330 *331 *  The following example illustrates how `res.sendfile()` may332 *  be used as an alternative for the `static()` middleware for333 *  dynamic situations. The code backing `res.sendfile()` is actually334 *  the same code, so HTTP cache support etc is identical.335 *336 *     app.get('/user/:uid/photos/:file', function(req, res){337 *       var uid = req.params.uid338 *         , file = req.params.file;339 *340 *       req.user.mayViewFilesFrom(uid, function(yes){341 *         if (yes) {342 *           res.sendfile('/uploads/' + uid + '/' + file);343 *         } else {344 *           res.send(403, 'Sorry! you cant see that.');345 *         }346 *       });347 *     });348 *349 * @api public350 */351352res.sendfile = function(path, options, fn){353  options = options || {};354  var self = this;355  var req = self.req;356  var next = this.req.next;357  var done;358359360  // support function as second arg361  if ('function' == typeof options) {362    fn = options;363    options = {};364  }365366  // socket errors367  req.socket.on('error', error);368369  // errors370  function error(err) {371    if (done) return;372    done = true;373374    // clean up375    cleanup();376377    // callback available378    if (fn) return fn(err);379380    // delegate381    next(err);382  }383384  // streaming385  function stream(stream) {386    if (done) return;387    cleanup();388    if (fn) stream.on('end', fn);389  }390391  // cleanup392  function cleanup() {393    req.socket.removeListener('error', error);394  }395396  // Back-compat397  options.maxage = options.maxage || options.maxAge || 0;398399  // transfer400  var file = send(req, path, options);401  file.on('error', error);402  file.on('directory', next);403  file.on('stream', stream);404405  if (options.headers) {406    // set headers on successful transfer407    file.on('headers', function headers(res) {408      var obj = options.headers;409      var keys = Object.keys(obj);410411      for (var i = 0; i < keys.length; i++) {412        var k = keys[i];413        res.setHeader(k, obj[k]);414      }415    });416  }417418  // pipe419  file.pipe(this);420  this.on('finish', cleanup);421};422423/**424 * Transfer the file at the given `path` as an attachment.425 *426 * Optionally providing an alternate attachment `filename`,427 * and optional callback `fn(err)`. The callback is invoked428 * when the data transfer is complete, or when an error has429 * ocurred. Be sure to check `res.headersSent` if you plan to respond.430 *431 * This method uses `res.sendfile()`.432 *433 * @api public434 */435436res.download = function(path, filename, fn){437  // support function as second arg438  if ('function' == typeof filename) {439    fn = filename;440    filename = null;441  }442443  filename = filename || path;444445  // set Content-Disposition when file is sent446  var headers = {447    'Content-Disposition': contentDisposition(filename)448  };449450  return this.sendfile(path, { headers: headers }, fn);451};452453/**454 * Set _Content-Type_ response header with `type` through `mime.lookup()`455 * when it does not contain "/", or set the Content-Type to `type` otherwise.456 *457 * Examples:458 *459 *     res.type('.html');460 *     res.type('html');461 *     res.type('json');462 *     res.type('application/json');463 *     res.type('png');464 *465 * @param {String} type466 * @return {ServerResponse} for chaining467 * @api public468 */469470res.contentType =471res.type = function(type){472  return this.set('Content-Type', ~type.indexOf('/')473    ? type474    : mime.lookup(type));475};476477/**478 * Respond to the Acceptable formats using an `obj`479 * of mime-type callbacks.480 *481 * This method uses `req.accepted`, an array of482 * acceptable types ordered by their quality values.483 * When "Accept" is not present the _first_ callback484 * is invoked, otherwise the first match is used. When485 * no match is performed the server responds with486 * 406 "Not Acceptable".487 *488 * Content-Type is set for you, however if you choose489 * you may alter this within the callback using `res.type()`490 * or `res.set('Content-Type', ...)`.491 *492 *    res.format({493 *      'text/plain': function(){494 *        res.send('hey');495 *      },496 *497 *      'text/html': function(){498 *        res.send('<p>hey</p>');499 *      },500 *501 *      'appliation/json': function(){502 *        res.send({ message: 'hey' });503 *      }504 *    });505 *506 * In addition to canonicalized MIME types you may507 * also use extnames mapped to these types:508 *509 *    res.format({510 *      text: function(){511 *        res.send('hey');512 *      },513 *514 *      html: function(){515 *        res.send('<p>hey</p>');516 *      },517 *518 *      json: function(){519 *        res.send({ message: 'hey' });520 *      }521 *    });522 *523 * By default Express passes an `Error`524 * with a `.status` of 406 to `next(err)`525 * if a match is not made. If you provide526 * a `.default` callback it will be invoked527 * instead.528 *529 * @param {Object} obj530 * @return {ServerResponse} for chaining531 * @api public532 */533534res.format = function(obj){535  var req = this.req;536  var next = req.next;537538  var fn = obj.default;539  if (fn) delete obj.default;540  var keys = Object.keys(obj);541542  var key = req.accepts(keys);543544  this.vary("Accept");545546  if (key) {547    this.set('Content-Type', normalizeType(key).value);548    obj[key](req, this, next);549  } else if (fn) {550    fn();551  } else {552    var err = new Error('Not Acceptable');553    err.status = 406;554    err.types = normalizeTypes(keys).map(function(o){ return o.value });555    next(err);556  }557558  return this;559};560561/**562 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.563 *564 * @param {String} filename565 * @return {ServerResponse}566 * @api public567 */568569res.attachment = function(filename){570  if (filename) this.type(extname(filename));571  this.set('Content-Disposition', contentDisposition(filename));572  return this;573};574575/**576 * Set header `field` to `val`, or pass577 * an object of header fields.578 *579 * Examples:580 *581 *    res.set('Foo', ['bar', 'baz']);582 *    res.set('Accept', 'application/json');583 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });584 *585 * Aliased as `res.header()`.586 *587 * @param {String|Object|Array} field588 * @param {String} val589 * @return {ServerResponse} for chaining590 * @api public591 */592593res.set =594res.header = function header(field, val) {595  if (arguments.length === 2) {596    if (Array.isArray(val)) val = val.map(String);597    else val = String(val);598    if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {599      var charset = mime.charsets.lookup(val.split(';')[0]);600      if (charset) val += '; charset=' + charset.toLowerCase();601    }602    this.setHeader(field, val);603  } else {604    for (var key in field) {605      this.set(key, field[key]);606    }607  }608  return this;609};610611/**612 * Get value for header `field`.613 *614 * @param {String} field615 * @return {String}616 * @api public617 */618619res.get = function(field){620  return this.getHeader(field);621};622623/**624 * Clear cookie `name`.625 *626 * @param {String} name627 * @param {Object} options628 * @return {ServerResponse} for chaining629 * @api public630 */631632res.clearCookie = function(name, options){633  var opts = { expires: new Date(1), path: '/' };634  return this.cookie(name, '', options635    ? mixin(opts, options)636    : opts);637};638639/**640 * Set cookie `name` to `val`, with the given `options`.641 *642 * Options:643 *644 *    - `maxAge`   max-age in milliseconds, converted to `expires`645 *    - `signed`   sign the cookie646 *    - `path`     defaults to "/"647 *648 * Examples:649 *650 *    // "Remember Me" for 15 minutes651 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });652 *653 *    // save as above654 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })655 *656 * @param {String} name657 * @param {String|Object} val658 * @param {Options} options659 * @return {ServerResponse} for chaining660 * @api public661 */662663res.cookie = function(name, val, options){664  options = mixin({}, options);665  var secret = this.req.secret;666  var signed = options.signed;667  if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');668  if ('number' == typeof val) val = val.toString();669  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);670  if (signed) val = 's:' + sign(val, secret);671  if ('maxAge' in options) {672    options.expires = new Date(Date.now() + options.maxAge);673    options.maxAge /= 1000;674  }675  if (null == options.path) options.path = '/';676  var headerVal = cookie.serialize(name, String(val), options);677678  // supports multiple 'res.cookie' calls by getting previous value679  var prev = this.get('Set-Cookie');680  if (prev) {681    if (Array.isArray(prev)) {682      headerVal = prev.concat(headerVal);683    } else {684      headerVal = [prev, headerVal];685    }686  }687  this.set('Set-Cookie', headerVal);688  return this;689};690691692/**693 * Set the location header to `url`.694 *695 * The given `url` can also be "back", which redirects696 * to the _Referrer_ or _Referer_ headers or "/".697 *698 * Examples:699 *700 *    res.location('/foo/bar').;701 *    res.location('http://example.com');702 *    res.location('../login');703 *704 * @param {String} url705 * @return {ServerResponse} for chaining706 * @api public707 */708709res.location = function(url){710  var req = this.req;711712  // "back" is an alias for the referrer713  if ('back' == url) url = req.get('Referrer') || '/';714715  // Respond716  this.set('Location', url);717  return this;718};719720/**721 * Redirect to the given `url` with optional response `status`722 * defaulting to 302.723 *724 * The resulting `url` is determined by `res.location()`, so725 * it will play nicely with mounted apps, relative paths,726 * `"back"` etc.727 *728 * Examples:729 *730 *    res.redirect('/foo/bar');731 *    res.redirect('http://example.com');732 *    res.redirect(301, 'http://example.com');733 *    res.redirect('../login'); // /blog/post/1 -> /blog/login734 *735 * @api public736 */737738res.redirect = function redirect(url) {739  var address = url;740  var body;741  var status = 302;742743  // allow status / url744  if (arguments.length === 2) {745    if (typeof arguments[0] === 'number') {746      status = arguments[0];747      address = arguments[1];748    } else {749      deprecate('res.redirect(ur, status): Use res.redirect(status, url) instead');750      status = arguments[1];751    }752  }753754  // Set location header755  this.location(address);756  address = this.get('Location');757758  // Support text/{plain,html} by default759  this.format({760    text: function(){761      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);762    },763764    html: function(){765      var u = escapeHtml(url);766      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';767    },768769    default: function(){770      body = '';771    }772  });773774  // Respond775  this.statusCode = status;776  this.set('Content-Length', Buffer.byteLength(body));777778  if (this.req.method === 'HEAD') {779    this.end();780  }781782  this.end(body);783};784785/**786 * Add `field` to Vary. If already present in the Vary set, then787 * this call is simply ignored.788 *789 * @param {Array|String} field790 * @return {ServerResponse} for chaining791 * @api public792 */793794res.vary = function(field){795  // checks for back-compat796  if (!field || (Array.isArray(field) && !field.length)) {797    deprecate('res.vary(): Provide a field name');798    return this;799  }800801  vary(this, field);802803  return this;804};805806/**807 * Render `view` with the given `options` and optional callback `fn`.808 * When a callback function is given a response will _not_ be made809 * automatically, otherwise a response of _200_ and _text/html_ is given.810 *811 * Options:812 *813 *  - `cache`     boolean hinting to the engine it should cache814 *  - `filename`  filename of the view being rendered815 *816 * @api public817 */818819res.render = function(view, options, fn){820  options = options || {};821  var self = this;822  var req = this.req;823  var app = req.app;824825  // support callback function as second arg826  if ('function' == typeof options) {827    fn = options, options = {};828  }829830  // merge res.locals831  options._locals = self.locals;832833  // default callback to respond834  fn = fn || function(err, str){835    if (err) return req.next(err);836    self.send(str);837  };838839  // render840  app.render(view, options, fn);841};