Skip to content
Myr

response.js

This file

Path

lib/response.js

775 lines · 17.9 KiB · JavaScript

Last changed by

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

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(body){82  var req = this.req;83  var head = 'HEAD' == req.method;84  var type;85  var encoding;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  // write strings in utf-8126  if ('string' === typeof body) {127    encoding = 'utf8';128    type = this.get('Content-Type');129130    // reflect this in content-type131    if ('string' === typeof type) {132      this.set('Content-Type', setCharset(type, 'utf-8'));133    }134  }135136  // populate Content-Length137  if (undefined !== body && !this.get('Content-Length')) {138    len = Buffer.isBuffer(body)139      ? body.length140      : Buffer.byteLength(body, encoding);141    this.set('Content-Length', len);142  }143144  // ETag support145  var etag = len !== undefined && app.get('etag fn');146  if (etag && ('GET' === req.method || 'HEAD' === req.method)) {147    if (!this.get('ETag')) {148      etag = etag(body, encoding);149      etag && this.set('ETag', etag);150    }151  }152153  // freshness154  if (req.fresh) this.statusCode = 304;155156  // strip irrelevant headers157  if (204 == this.statusCode || 304 == this.statusCode) {158    this.removeHeader('Content-Type');159    this.removeHeader('Content-Length');160    this.removeHeader('Transfer-Encoding');161    body = '';162  }163164  // respond165  this.end((head ? null : body), encoding);166167  return this;168};169170/**171 * Send JSON response.172 *173 * Examples:174 *175 *     res.json(null);176 *     res.json({ user: 'tj' });177 *     res.json(500, 'oh noes!');178 *     res.json(404, 'I dont have that');179 *180 * @api public181 */182183res.json = function(obj){184  // allow status / body185  if (2 == arguments.length) {186    // res.json(body, status) backwards compat187    if ('number' == typeof arguments[1]) {188      this.statusCode = arguments[1];189      if (typeof obj === 'number') {190        deprecate('res.json(obj, status): Use res.json(status, obj) instead');191      } else {192        deprecate('res.json(num, status): Use res.status(status).json(num) instead');193      }194    } else {195      this.statusCode = obj;196      obj = arguments[1];197    }198  }199200  // settings201  var app = this.app;202  var replacer = app.get('json replacer');203  var spaces = app.get('json spaces');204  var body = JSON.stringify(obj, replacer, spaces);205206  // content-type207  this.get('Content-Type') || this.set('Content-Type', 'application/json');208209  return this.send(body);210};211212/**213 * Send JSON response with JSONP callback support.214 *215 * Examples:216 *217 *     res.jsonp(null);218 *     res.jsonp({ user: 'tj' });219 *     res.jsonp(500, 'oh noes!');220 *     res.jsonp(404, 'I dont have that');221 *222 * @api public223 */224225res.jsonp = function(obj){226  // allow status / body227  if (2 == arguments.length) {228    // res.json(body, status) backwards compat229    if ('number' == typeof arguments[1]) {230      this.statusCode = arguments[1];231      if (typeof obj === 'number') {232        deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');233      } else {234        deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');235      }236    } else {237      this.statusCode = obj;238      obj = arguments[1];239    }240  }241242  // settings243  var app = this.app;244  var replacer = app.get('json replacer');245  var spaces = app.get('json spaces');246  var body = JSON.stringify(obj, replacer, spaces)247    .replace(/\u2028/g, '\\u2028')248    .replace(/\u2029/g, '\\u2029');249  var callback = this.req.query[app.get('jsonp callback name')];250251  // content-type252  this.get('Content-Type') || this.set('Content-Type', 'application/json');253254  // fixup callback255  if (Array.isArray(callback)) {256    callback = callback[0];257  }258259  // jsonp260  if (callback && 'string' === typeof callback) {261    this.set('Content-Type', 'text/javascript');262    var cb = callback.replace(/[^\[\]\w$.]/g, '');263    body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';264  }265266  return this.send(body);267};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 * @api public307 */308309res.sendfile = function(path, options, fn){310  options = options || {};311  var self = this;312  var req = self.req;313  var next = this.req.next;314  var done;315316317  // support function as second arg318  if ('function' == typeof options) {319    fn = options;320    options = {};321  }322323  // socket errors324  req.socket.on('error', error);325326  // errors327  function error(err) {328    if (done) return;329    done = true;330331    // clean up332    cleanup();333    if (!self.headersSent) self.removeHeader('Content-Disposition');334335    // callback available336    if (fn) return fn(err);337338    // list in limbo if there's no callback339    if (self.headersSent) return;340341    // delegate342    next(err);343  }344345  // streaming346  function stream(stream) {347    if (done) return;348    cleanup();349    if (fn) stream.on('end', fn);350  }351352  // cleanup353  function cleanup() {354    req.socket.removeListener('error', error);355  }356357  // Back-compat358  options.maxage = options.maxage || options.maxAge || 0;359360  // transfer361  var file = send(req, path, options);362  file.on('error', error);363  file.on('directory', next);364  file.on('stream', stream);365  file.pipe(this);366  this.on('finish', cleanup);367};368369/**370 * Transfer the file at the given `path` as an attachment.371 *372 * Optionally providing an alternate attachment `filename`,373 * and optional callback `fn(err)`. The callback is invoked374 * when the data transfer is complete, or when an error has375 * ocurred. Be sure to check `res.headersSent` if you plan to respond.376 *377 * This method uses `res.sendfile()`.378 *379 * @api public380 */381382res.download = function(path, filename, fn){383  // support function as second arg384  if ('function' == typeof filename) {385    fn = filename;386    filename = null;387  }388389  filename = filename || path;390  this.set('Content-Disposition', contentDisposition(filename));391  return this.sendfile(path, fn);392};393394/**395 * Set _Content-Type_ response header with `type` through `mime.lookup()`396 * when it does not contain "/", or set the Content-Type to `type` otherwise.397 *398 * Examples:399 *400 *     res.type('.html');401 *     res.type('html');402 *     res.type('json');403 *     res.type('application/json');404 *     res.type('png');405 *406 * @param {String} type407 * @return {ServerResponse} for chaining408 * @api public409 */410411res.contentType =412res.type = function(type){413  return this.set('Content-Type', ~type.indexOf('/')414    ? type415    : mime.lookup(type));416};417418/**419 * Respond to the Acceptable formats using an `obj`420 * of mime-type callbacks.421 *422 * This method uses `req.accepted`, an array of423 * acceptable types ordered by their quality values.424 * When "Accept" is not present the _first_ callback425 * is invoked, otherwise the first match is used. When426 * no match is performed the server responds with427 * 406 "Not Acceptable".428 *429 * Content-Type is set for you, however if you choose430 * you may alter this within the callback using `res.type()`431 * or `res.set('Content-Type', ...)`.432 *433 *    res.format({434 *      'text/plain': function(){435 *        res.send('hey');436 *      },437 *438 *      'text/html': function(){439 *        res.send('<p>hey</p>');440 *      },441 *442 *      'appliation/json': function(){443 *        res.send({ message: 'hey' });444 *      }445 *    });446 *447 * In addition to canonicalized MIME types you may448 * also use extnames mapped to these types:449 *450 *    res.format({451 *      text: function(){452 *        res.send('hey');453 *      },454 *455 *      html: function(){456 *        res.send('<p>hey</p>');457 *      },458 *459 *      json: function(){460 *        res.send({ message: 'hey' });461 *      }462 *    });463 *464 * By default Express passes an `Error`465 * with a `.status` of 406 to `next(err)`466 * if a match is not made. If you provide467 * a `.default` callback it will be invoked468 * instead.469 *470 * @param {Object} obj471 * @return {ServerResponse} for chaining472 * @api public473 */474475res.format = function(obj){476  var req = this.req;477  var next = req.next;478479  var fn = obj.default;480  if (fn) delete obj.default;481  var keys = Object.keys(obj);482483  var key = req.accepts(keys);484485  this.vary("Accept");486487  if (key) {488    this.set('Content-Type', normalizeType(key).value);489    obj[key](req, this, next);490  } else if (fn) {491    fn();492  } else {493    var err = new Error('Not Acceptable');494    err.status = 406;495    err.types = normalizeTypes(keys).map(function(o){ return o.value });496    next(err);497  }498499  return this;500};501502/**503 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.504 *505 * @param {String} filename506 * @return {ServerResponse}507 * @api public508 */509510res.attachment = function(filename){511  if (filename) this.type(extname(filename));512  this.set('Content-Disposition', contentDisposition(filename));513  return this;514};515516/**517 * Set header `field` to `val`, or pass518 * an object of header fields.519 *520 * Examples:521 *522 *    res.set('Foo', ['bar', 'baz']);523 *    res.set('Accept', 'application/json');524 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });525 *526 * Aliased as `res.header()`.527 *528 * @param {String|Object|Array} field529 * @param {String} val530 * @return {ServerResponse} for chaining531 * @api public532 */533534res.set =535res.header = function(field, val){536  if (2 == arguments.length) {537    if (Array.isArray(val)) val = val.map(String);538    else val = String(val);539    if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {540      var charset = mime.charsets.lookup(val.split(';')[0]);541      if (charset) val += '; charset=' + charset.toLowerCase();542    }543    this.setHeader(field, val);544  } else {545    for (var key in field) {546      this.set(key, field[key]);547    }548  }549  return this;550};551552/**553 * Get value for header `field`.554 *555 * @param {String} field556 * @return {String}557 * @api public558 */559560res.get = function(field){561  return this.getHeader(field);562};563564/**565 * Clear cookie `name`.566 *567 * @param {String} name568 * @param {Object} options569 * @param {ServerResponse} for chaining570 * @api public571 */572573res.clearCookie = function(name, options){574  var opts = { expires: new Date(1), path: '/' };575  return this.cookie(name, '', options576    ? mixin(opts, options)577    : opts);578};579580/**581 * Set cookie `name` to `val`, with the given `options`.582 *583 * Options:584 *585 *    - `maxAge`   max-age in milliseconds, converted to `expires`586 *    - `signed`   sign the cookie587 *    - `path`     defaults to "/"588 *589 * Examples:590 *591 *    // "Remember Me" for 15 minutes592 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });593 *594 *    // save as above595 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })596 *597 * @param {String} name598 * @param {String|Object} val599 * @param {Options} options600 * @api public601 */602603res.cookie = function(name, val, options){604  options = mixin({}, options);605  var secret = this.req.secret;606  var signed = options.signed;607  if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');608  if ('number' == typeof val) val = val.toString();609  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);610  if (signed) val = 's:' + sign(val, secret);611  if ('maxAge' in options) {612    options.expires = new Date(Date.now() + options.maxAge);613    options.maxAge /= 1000;614  }615  if (null == options.path) options.path = '/';616  var headerVal = cookie.serialize(name, String(val), options);617618  // supports multiple 'res.cookie' calls by getting previous value619  var prev = this.get('Set-Cookie');620  if (prev) {621    if (Array.isArray(prev)) {622      headerVal = prev.concat(headerVal);623    } else {624      headerVal = [prev, headerVal];625    }626  }627  this.set('Set-Cookie', headerVal);628  return this;629};630631632/**633 * Set the location header to `url`.634 *635 * The given `url` can also be "back", which redirects636 * to the _Referrer_ or _Referer_ headers or "/".637 *638 * Examples:639 *640 *    res.location('/foo/bar').;641 *    res.location('http://example.com');642 *    res.location('../login');643 *644 * @param {String} url645 * @api public646 */647648res.location = function(url){649  var req = this.req;650651  // "back" is an alias for the referrer652  if ('back' == url) url = req.get('Referrer') || '/';653654  // Respond655  this.set('Location', url);656  return this;657};658659/**660 * Redirect to the given `url` with optional response `status`661 * defaulting to 302.662 *663 * The resulting `url` is determined by `res.location()`, so664 * it will play nicely with mounted apps, relative paths,665 * `"back"` etc.666 *667 * Examples:668 *669 *    res.redirect('/foo/bar');670 *    res.redirect('http://example.com');671 *    res.redirect(301, 'http://example.com');672 *    res.redirect('http://example.com', 301);673 *    res.redirect('../login'); // /blog/post/1 -> /blog/login674 *675 * @param {String} url676 * @param {Number} code677 * @api public678 */679680res.redirect = function(url){681  var head = 'HEAD' == this.req.method;682  var status = 302;683  var body;684685  // allow status / url686  if (2 == arguments.length) {687    if ('number' == typeof url) {688      status = url;689      url = arguments[1];690    } else {691      status = arguments[1];692    }693  }694695  // Set location header696  this.location(url);697  url = this.get('Location');698699  // Support text/{plain,html} by default700  this.format({701    text: function(){702      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);703    },704705    html: function(){706      var u = escapeHtml(url);707      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';708    },709710    default: function(){711      body = '';712    }713  });714715  // Respond716  this.statusCode = status;717  this.set('Content-Length', Buffer.byteLength(body));718  this.end(head ? null : body);719};720721/**722 * Add `field` to Vary. If already present in the Vary set, then723 * this call is simply ignored.724 *725 * @param {Array|String} field726 * @param {ServerResponse} for chaining727 * @api public728 */729730res.vary = function(field){731  // checks for back-compat732  if (!field) return this;733  if (Array.isArray(field) && !field.length) return this;734735  vary(this, field);736737  return this;738};739740/**741 * Render `view` with the given `options` and optional callback `fn`.742 * When a callback function is given a response will _not_ be made743 * automatically, otherwise a response of _200_ and _text/html_ is given.744 *745 * Options:746 *747 *  - `cache`     boolean hinting to the engine it should cache748 *  - `filename`  filename of the view being rendered749 *750 * @api public751 */752753res.render = function(view, options, fn){754  options = options || {};755  var self = this;756  var req = this.req;757  var app = req.app;758759  // support callback function as second arg760  if ('function' == typeof options) {761    fn = options, options = {};762  }763764  // merge res.locals765  options._locals = self.locals;766767  // default callback to respond768  fn = fn || function(err, str){769    if (err) return req.next(err);770    self.send(str);771  };772773  // render774  app.render(view, options, fn);775};