Skip to content
Myr

response.js

This file

Path

lib/response.js

777 lines · 17.7 KiB · JavaScript

Last changed by

remove res.charset usageJonathan Ongbefore adoption2064f41

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 etag = require('./utils').etag;13var statusCodes = http.STATUS_CODES;14var cookie = require('cookie');15var send = require('send');16var basename = path.basename;17var extname = path.extname;18var mime = send.mime;1920/**21 * Response prototype.22 */2324var res = module.exports = {25  __proto__: http.ServerResponse.prototype26};2728/**29 * Set status `code`.30 *31 * @param {Number} code32 * @return {ServerResponse}33 * @api public34 */3536res.status = function(code){37  this.statusCode = code;38  return this;39};4041/**42 * Set Link header field with the given `links`.43 *44 * Examples:45 *46 *    res.links({47 *      next: 'http://api.example.com/users?page=2',48 *      last: 'http://api.example.com/users?page=5'49 *    });50 *51 * @param {Object} links52 * @return {ServerResponse}53 * @api public54 */5556res.links = function(links){57  var link = this.get('Link') || '';58  if (link) link += ', ';59  return this.set('Link', link + Object.keys(links).map(function(rel){60    return '<' + links[rel] + '>; rel="' + rel + '"';61  }).join(', '));62};6364/**65 * Send a response.66 *67 * Examples:68 *69 *     res.send(new Buffer('wahoo'));70 *     res.send({ some: 'json' });71 *     res.send('<p>some html</p>');72 *     res.send(404, 'Sorry, cant find that');73 *     res.send(404);74 *75 * @param {Mixed} body or status76 * @param {Mixed} body77 * @return {ServerResponse}78 * @api public79 */8081res.send = function(body){82  var req = this.req;83  var head = 'HEAD' == req.method;84  var len;8586  // settings87  var app = this.app;8889  // allow status / body90  if (2 == arguments.length) {91    // res.send(body, status) backwards compat92    if ('number' != typeof body && 'number' == typeof arguments[1]) {93      this.statusCode = arguments[1];94    } else {95      this.statusCode = body;96      body = arguments[1];97    }98  }99100  switch (typeof body) {101    // response status102    case 'number':103      this.get('Content-Type') || this.type('txt');104      this.statusCode = body;105      body = http.STATUS_CODES[body];106      break;107    // string defaulting to html108    case 'string':109      if (!this.get('Content-Type')) this.type('html');110      break;111    case 'boolean':112    case 'object':113      if (null == body) {114        body = '';115      } else if (Buffer.isBuffer(body)) {116        this.get('Content-Type') || this.type('bin');117      } else {118        return this.json(body);119      }120      break;121  }122123  // populate Content-Length124  if (undefined !== body && !this.get('Content-Length')) {125    this.set('Content-Length', len = Buffer.isBuffer(body)126      ? body.length127      : Buffer.byteLength(body));128  }129130  // ETag support131  // TODO: W/ support132  if (app.settings.etag && len && 'GET' == req.method) {133    if (!this.get('ETag')) {134      this.set('ETag', etag(body));135    }136  }137138  // freshness139  if (req.fresh) this.statusCode = 304;140141  // strip irrelevant headers142  if (204 == this.statusCode || 304 == this.statusCode) {143    this.removeHeader('Content-Type');144    this.removeHeader('Content-Length');145    this.removeHeader('Transfer-Encoding');146    body = '';147  }148149  // respond150  this.end(head ? null : body);151  return this;152};153154/**155 * Send JSON response.156 *157 * Examples:158 *159 *     res.json(null);160 *     res.json({ user: 'tj' });161 *     res.json(500, 'oh noes!');162 *     res.json(404, 'I dont have that');163 *164 * @param {Mixed} obj or status165 * @param {Mixed} obj166 * @return {ServerResponse}167 * @api public168 */169170res.json = function(obj){171  // allow status / body172  if (2 == arguments.length) {173    // res.json(body, status) backwards compat174    if ('number' == typeof arguments[1]) {175      this.statusCode = arguments[1];176    } else {177      this.statusCode = obj;178      obj = arguments[1];179    }180  }181182  // settings183  var app = this.app;184  var replacer = app.get('json replacer');185  var spaces = app.get('json spaces');186  var body = JSON.stringify(obj, replacer, spaces);187188  // content-type189  this.get('Content-Type') || this.set('Content-Type', 'application/json');190191  return this.send(body);192};193194/**195 * Send JSON response with JSONP callback support.196 *197 * Examples:198 *199 *     res.jsonp(null);200 *     res.jsonp({ user: 'tj' });201 *     res.jsonp(500, 'oh noes!');202 *     res.jsonp(404, 'I dont have that');203 *204 * @param {Mixed} obj or status205 * @param {Mixed} obj206 * @return {ServerResponse}207 * @api public208 */209210res.jsonp = function(obj){211  // allow status / body212  if (2 == arguments.length) {213    // res.json(body, status) backwards compat214    if ('number' == typeof arguments[1]) {215      this.statusCode = arguments[1];216    } else {217      this.statusCode = obj;218      obj = arguments[1];219    }220  }221222  // settings223  var app = this.app;224  var replacer = app.get('json replacer');225  var spaces = app.get('json spaces');226  var body = JSON.stringify(obj, replacer, spaces)227    .replace(/\u2028/g, '\\u2028')228    .replace(/\u2029/g, '\\u2029');229  var callback = this.req.query[app.get('jsonp callback name')];230231  // content-type232  this.set('Content-Type', 'application/json');233234  // jsonp235  if (callback) {236    if (Array.isArray(callback)) callback = callback[0];237    this.set('Content-Type', 'text/javascript');238    var cb = callback.replace(/[^\[\]\w$.]/g, '');239    body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';240  }241242  return this.send(body);243};244245/**246 * Transfer the file at the given `path`.247 *248 * Automatically sets the _Content-Type_ response header field.249 * The callback `fn(err)` is invoked when the transfer is complete250 * or when an error occurs. Be sure to check `res.sentHeader`251 * if you wish to attempt responding, as the header and some data252 * may have already been transferred.253 *254 * Options:255 *256 *   - `maxAge` defaulting to 0257 *   - `root`   root directory for relative filenames258 *259 * Examples:260 *261 *  The following example illustrates how `res.sendfile()` may262 *  be used as an alternative for the `static()` middleware for263 *  dynamic situations. The code backing `res.sendfile()` is actually264 *  the same code, so HTTP cache support etc is identical.265 *266 *     app.get('/user/:uid/photos/:file', function(req, res){267 *       var uid = req.params.uid268 *         , file = req.params.file;269 *270 *       req.user.mayViewFilesFrom(uid, function(yes){271 *         if (yes) {272 *           res.sendfile('/uploads/' + uid + '/' + file);273 *         } else {274 *           res.send(403, 'Sorry! you cant see that.');275 *         }276 *       });277 *     });278 *279 * @param {String} path280 * @param {Object|Function} options or fn281 * @param {Function} fn282 * @api public283 */284285res.sendfile = function(path, options, fn){286  var self = this287    , req = self.req288    , next = this.req.next289    , options = options || {}290    , done;291292  // support function as second arg293  if ('function' == typeof options) {294    fn = options;295    options = {};296  }297298  // socket errors299  req.socket.on('error', error);300301  // errors302  function error(err) {303    if (done) return;304    done = true;305306    // clean up307    cleanup();308    if (!self.headersSent) self.removeHeader('Content-Disposition');309310    // callback available311    if (fn) return fn(err);312313    // list in limbo if there's no callback314    if (self.headersSent) return;315316    // delegate317    next(err);318  }319320  // streaming321  function stream(stream) {322    if (done) return;323    cleanup();324    if (fn) stream.on('end', fn);325  }326327  // cleanup328  function cleanup() {329    req.socket.removeListener('error', error);330  }331332  // transfer333  var file = send(req, path);334  if (options.root) file.root(options.root);335  file.maxage(options.maxAge || 0);336  file.on('error', error);337  file.on('directory', next);338  file.on('stream', stream);339  file.pipe(this);340  this.on('finish', cleanup);341};342343/**344 * Transfer the file at the given `path` as an attachment.345 *346 * Optionally providing an alternate attachment `filename`,347 * and optional callback `fn(err)`. The callback is invoked348 * when the data transfer is complete, or when an error has349 * ocurred. Be sure to check `res.headersSent` if you plan to respond.350 *351 * This method uses `res.sendfile()`.352 *353 * @param {String} path354 * @param {String|Function} filename or fn355 * @param {Function} fn356 * @api public357 */358359res.download = function(path, filename, fn){360  // support function as second arg361  if ('function' == typeof filename) {362    fn = filename;363    filename = null;364  }365366  filename = filename || path;367  this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');368  return this.sendfile(path, fn);369};370371/**372 * Set _Content-Type_ response header with `type` through `mime.lookup()`373 * when it does not contain "/", or set the Content-Type to `type` otherwise.374 *375 * Examples:376 *377 *     res.type('.html');378 *     res.type('html');379 *     res.type('json');380 *     res.type('application/json');381 *     res.type('png');382 *383 * @param {String} type384 * @return {ServerResponse} for chaining385 * @api public386 */387388res.contentType =389res.type = function(type){390  return this.set('Content-Type', ~type.indexOf('/')391    ? type392    : mime.lookup(type));393};394395/**396 * Respond to the Acceptable formats using an `obj`397 * of mime-type callbacks.398 *399 * This method uses `req.accepted`, an array of400 * acceptable types ordered by their quality values.401 * When "Accept" is not present the _first_ callback402 * is invoked, otherwise the first match is used. When403 * no match is performed the server responds with404 * 406 "Not Acceptable".405 *406 * Content-Type is set for you, however if you choose407 * you may alter this within the callback using `res.type()`408 * or `res.set('Content-Type', ...)`.409 *410 *    res.format({411 *      'text/plain': function(){412 *        res.send('hey');413 *      },414 *415 *      'text/html': function(){416 *        res.send('<p>hey</p>');417 *      },418 *419 *      'appliation/json': function(){420 *        res.send({ message: 'hey' });421 *      }422 *    });423 *424 * In addition to canonicalized MIME types you may425 * also use extnames mapped to these types:426 *427 *    res.format({428 *      text: function(){429 *        res.send('hey');430 *      },431 *432 *      html: function(){433 *        res.send('<p>hey</p>');434 *      },435 *436 *      json: function(){437 *        res.send({ message: 'hey' });438 *      }439 *    });440 *441 * By default Express passes an `Error`442 * with a `.status` of 406 to `next(err)`443 * if a match is not made. If you provide444 * a `.default` callback it will be invoked445 * instead.446 *447 * @param {Object} obj448 * @return {ServerResponse} for chaining449 * @api public450 */451452res.format = function(obj){453  var req = this.req454    , next = req.next;455456  var fn = obj.default;457  if (fn) delete obj.default;458  var keys = Object.keys(obj);459460  var key = req.accepts(keys);461462  this.vary("Accept");463464  if (key) {465    this.set('Content-Type', normalizeType(key).value);466    obj[key](req, this, next);467  } else if (fn) {468    fn();469  } else {470    var err = new Error('Not Acceptable');471    err.status = 406;472    err.types = normalizeTypes(keys).map(function(o){ return o.value });473    next(err);474  }475476  return this;477};478479/**480 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.481 *482 * @param {String} filename483 * @return {ServerResponse}484 * @api public485 */486487res.attachment = function(filename){488  if (filename) this.type(extname(filename));489  this.set('Content-Disposition', filename490    ? 'attachment; filename="' + basename(filename) + '"'491    : 'attachment');492  return this;493};494495/**496 * Set header `field` to `val`, or pass497 * an object of header fields.498 *499 * Examples:500 *501 *    res.set('Foo', ['bar', 'baz']);502 *    res.set('Accept', 'application/json');503 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });504 *505 * Aliased as `res.header()`.506 *507 * @param {String|Object|Array} field508 * @param {String} val509 * @return {ServerResponse} for chaining510 * @api public511 */512513res.set =514res.header = function(field, val){515  if (2 == arguments.length) {516    if (Array.isArray(val)) val = val.map(String);517    else val = String(val);518    field = field.toLowerCase();519    if ('content-type' == field && !/;\s*charset\s*=/.test(val)) {520      var charset = mime.charsets.lookup(val.split(';')[0]);521      if (charset) val += '; charset=' + charset.toLowerCase();522    }523    this.setHeader(field, val);524  } else {525    for (var key in field) {526      this.set(key, field[key]);527    }528  }529  return this;530};531532/**533 * Get value for header `field`.534 *535 * @param {String} field536 * @return {String}537 * @api public538 */539540res.get = function(field){541  return this.getHeader(field);542};543544/**545 * Clear cookie `name`.546 *547 * @param {String} name548 * @param {Object} options549 * @param {ServerResponse} for chaining550 * @api public551 */552553res.clearCookie = function(name, options){554  var opts = { expires: new Date(1), path: '/' };555  return this.cookie(name, '', options556    ? mixin(opts, options)557    : opts);558};559560/**561 * Set cookie `name` to `val`, with the given `options`.562 *563 * Options:564 *565 *    - `maxAge`   max-age in milliseconds, converted to `expires`566 *    - `signed`   sign the cookie567 *    - `path`     defaults to "/"568 *569 * Examples:570 *571 *    // "Remember Me" for 15 minutes572 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });573 *574 *    // save as above575 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })576 *577 * @param {String} name578 * @param {String|Object} val579 * @param {Options} options580 * @api public581 */582583res.cookie = function(name, val, options){584  options = mixin({}, options);585  var secret = this.req.secret;586  var signed = options.signed;587  if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');588  if ('number' == typeof val) val = val.toString();589  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);590  if (signed) val = 's:' + sign(val, secret);591  if ('maxAge' in options) {592    options.expires = new Date(Date.now() + options.maxAge);593    options.maxAge /= 1000;594  }595  if (null == options.path) options.path = '/';596  var headerVal = cookie.serialize(name, String(val), options);597598  // supports multiple 'res.cookie' calls by getting previous value599  var prev = this.get('Set-Cookie');600  if (prev) {601    if (Array.isArray(prev)) {602      headerVal = prev.concat(headerVal);603    } else {604      headerVal = [prev, headerVal];605    }606  }607  this.set('Set-Cookie', headerVal);608  return this;609};610611612/**613 * Set the location header to `url`.614 *615 * The given `url` can also be "back", which redirects616 * to the _Referrer_ or _Referer_ headers or "/".617 *618 * Examples:619 *620 *    res.location('/foo/bar').;621 *    res.location('http://example.com');622 *    res.location('../login');623 *624 * @param {String} url625 * @api public626 */627628res.location = function(url){629  var req = this.req;630631  // "back" is an alias for the referrer632  if ('back' == url) url = req.get('Referrer') || '/';633634  // Respond635  this.set('Location', url);636  return this;637};638639/**640 * Redirect to the given `url` with optional response `status`641 * defaulting to 302.642 *643 * The resulting `url` is determined by `res.location()`, so644 * it will play nicely with mounted apps, relative paths,645 * `"back"` etc.646 *647 * Examples:648 *649 *    res.redirect('/foo/bar');650 *    res.redirect('http://example.com');651 *    res.redirect(301, 'http://example.com');652 *    res.redirect('http://example.com', 301);653 *    res.redirect('../login'); // /blog/post/1 -> /blog/login654 *655 * @param {String} url656 * @param {Number} code657 * @api public658 */659660res.redirect = function(url){661  var head = 'HEAD' == this.req.method662    , status = 302663    , body;664665  // allow status / url666  if (2 == arguments.length) {667    if ('number' == typeof url) {668      status = url;669      url = arguments[1];670    } else {671      status = arguments[1];672    }673  }674675  // Set location header676  this.location(url);677  url = this.get('Location');678679  // Support text/{plain,html} by default680  this.format({681    text: function(){682      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);683    },684685    html: function(){686      var u = escapeHtml(url);687      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';688    },689690    default: function(){691      body = '';692    }693  });694695  // Respond696  this.statusCode = status;697  this.set('Content-Length', Buffer.byteLength(body));698  this.end(head ? null : body);699};700701/**702 * Add `field` to Vary. If already present in the Vary set, then703 * this call is simply ignored.704 *705 * @param {Array|String} field706 * @param {ServerResponse} for chaining707 * @api public708 */709710res.vary = function(field){711  var self = this;712713  // nothing714  if (!field) return this;715716  // array717  if (Array.isArray(field)) {718    field.forEach(function(field){719      self.vary(field);720    });721    return;722  }723724  var vary = this.get('Vary');725726  // append727  if (vary) {728    vary = vary.split(/ *, */);729    if (!~vary.indexOf(field)) vary.push(field);730    this.set('Vary', vary.join(', '));731    return this;732  }733734  // set735  this.set('Vary', field);736  return this;737};738739/**740 * Render `view` with the given `options` and optional callback `fn`.741 * When a callback function is given a response will _not_ be made742 * automatically, otherwise a response of _200_ and _text/html_ is given.743 *744 * Options:745 *746 *  - `cache`     boolean hinting to the engine it should cache747 *  - `filename`  filename of the view being rendered748 *749 * @param  {String} view750 * @param  {Object|Function} options or callback function751 * @param  {Function} fn752 * @api public753 */754755res.render = function(view, options, fn){756  var self = this757    , options = options || {}758    , req = this.req759    , app = req.app;760761  // support callback function as second arg762  if ('function' == typeof options) {763    fn = options, options = {};764  }765766  // merge res.locals767  options._locals = self.locals;768769  // default callback to respond770  fn = fn || function(err, str){771    if (err) return req.next(err);772    self.send(str);773  };774775  // render776  app.render(view, options, fn);777};