Skip to content
Myr

response.js

This file

Path

lib/response.js

802 lines · 18.3 KiB · JavaScript

Last changed by

lint: remove unused stuffJonathan Ongbefore adoption9bed2b8

History of this file

Take it

1/**2 * Module dependencies.3 */45var http = require('http')6  , path = require('path')7  , connect = require('connect')8  , utils = connect.utils9  , sign = require('cookie-signature').sign10  , normalizeType = require('./utils').normalizeType11  , normalizeTypes = require('./utils').normalizeTypes12  , etag = require('./utils').etag13  , statusCodes = http.STATUS_CODES14  , cookie = require('cookie')15  , send = require('send')16  , mime = connect.mime17  , basename = path.basename18  , extname = path.extname;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')) {110        this.charset = this.charset || 'utf-8';111        this.type('html');112      }113      break;114    case 'boolean':115    case 'object':116      if (null == body) {117        body = '';118      } else if (Buffer.isBuffer(body)) {119        this.get('Content-Type') || this.type('bin');120      } else {121        return this.json(body);122      }123      break;124  }125126  // populate Content-Length127  if (undefined !== body && !this.get('Content-Length')) {128    this.set('Content-Length', len = Buffer.isBuffer(body)129      ? body.length130      : Buffer.byteLength(body));131  }132133  // ETag support134  // TODO: W/ support135  if (app.settings.etag && len > 1024 && 'GET' == req.method) {136    if (!this.get('ETag')) {137      this.set('ETag', etag(body));138    }139  }140141  // freshness142  if (req.fresh) this.statusCode = 304;143144  // strip irrelevant headers145  if (204 == this.statusCode || 304 == this.statusCode) {146    this.removeHeader('Content-Type');147    this.removeHeader('Content-Length');148    this.removeHeader('Transfer-Encoding');149    body = '';150  }151152  // respond153  this.end(head ? null : body);154  return this;155};156157/**158 * Send JSON response.159 *160 * Examples:161 *162 *     res.json(null);163 *     res.json({ user: 'tj' });164 *     res.json(500, 'oh noes!');165 *     res.json(404, 'I dont have that');166 *167 * @param {Mixed} obj or status168 * @param {Mixed} obj169 * @return {ServerResponse}170 * @api public171 */172173res.json = function(obj){174  // allow status / body175  if (2 == arguments.length) {176    // res.json(body, status) backwards compat177    if ('number' == typeof arguments[1]) {178      this.statusCode = arguments[1];179    } else {180      this.statusCode = obj;181      obj = arguments[1];182    }183  }184185  // settings186  var app = this.app;187  var replacer = app.get('json replacer');188  var spaces = app.get('json spaces');189  var body = JSON.stringify(obj, replacer, spaces);190191  // content-type192  this.charset = this.charset || 'utf-8';193  this.get('Content-Type') || this.set('Content-Type', 'application/json');194195  return this.send(body);196};197198/**199 * Send JSON response with JSONP callback support.200 *201 * Examples:202 *203 *     res.jsonp(null);204 *     res.jsonp({ user: 'tj' });205 *     res.jsonp(500, 'oh noes!');206 *     res.jsonp(404, 'I dont have that');207 *208 * @param {Mixed} obj or status209 * @param {Mixed} obj210 * @return {ServerResponse}211 * @api public212 */213214res.jsonp = function(obj){215  // allow status / body216  if (2 == arguments.length) {217    // res.json(body, status) backwards compat218    if ('number' == typeof arguments[1]) {219      this.statusCode = arguments[1];220    } else {221      this.statusCode = obj;222      obj = arguments[1];223    }224  }225226  // settings227  var app = this.app;228  var replacer = app.get('json replacer');229  var spaces = app.get('json spaces');230  var body = JSON.stringify(obj, replacer, spaces)231    .replace(/\u2028/g, '\\u2028')232    .replace(/\u2029/g, '\\u2029');233  var callback = this.req.query[app.get('jsonp callback name')];234235  // content-type236  this.charset = this.charset || 'utf-8';237  this.set('Content-Type', 'application/json');238239  // jsonp240  if (callback) {241    if (Array.isArray(callback)) callback = callback[0];242    this.set('Content-Type', 'text/javascript');243    var cb = callback.replace(/[^\[\]\w$.]/g, '');244    body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';245  }246247  return this.send(body);248};249250/**251 * Transfer the file at the given `path`.252 *253 * Automatically sets the _Content-Type_ response header field.254 * The callback `fn(err)` is invoked when the transfer is complete255 * or when an error occurs. Be sure to check `res.sentHeader`256 * if you wish to attempt responding, as the header and some data257 * may have already been transferred.258 *259 * Options:260 *261 *   - `maxAge` defaulting to 0262 *   - `root`   root directory for relative filenames263 *264 * Examples:265 *266 *  The following example illustrates how `res.sendfile()` may267 *  be used as an alternative for the `static()` middleware for268 *  dynamic situations. The code backing `res.sendfile()` is actually269 *  the same code, so HTTP cache support etc is identical.270 *271 *     app.get('/user/:uid/photos/:file', function(req, res){272 *       var uid = req.params.uid273 *         , file = req.params.file;274 *275 *       req.user.mayViewFilesFrom(uid, function(yes){276 *         if (yes) {277 *           res.sendfile('/uploads/' + uid + '/' + file);278 *         } else {279 *           res.send(403, 'Sorry! you cant see that.');280 *         }281 *       });282 *     });283 *284 * @param {String} path285 * @param {Object|Function} options or fn286 * @param {Function} fn287 * @api public288 */289290res.sendfile = function(path, options, fn){291  var self = this292    , req = self.req293    , next = this.req.next294    , options = options || {}295    , done;296297  // support function as second arg298  if ('function' == typeof options) {299    fn = options;300    options = {};301  }302303  // socket errors304  req.socket.on('error', error);305306  // errors307  function error(err) {308    if (done) return;309    done = true;310311    // clean up312    cleanup();313    if (!self.headerSent) self.removeHeader('Content-Disposition');314315    // callback available316    if (fn) return fn(err);317318    // list in limbo if there's no callback319    if (self.headerSent) return;320321    // delegate322    next(err);323  }324325  // streaming326  function stream(stream) {327    if (done) return;328    cleanup();329    if (fn) stream.on('end', fn);330  }331332  // cleanup333  function cleanup() {334    req.socket.removeListener('error', error);335  }336337  // transfer338  var file = send(req, path);339  if (options.root) file.root(options.root);340  file.maxage(options.maxAge || 0);341  file.on('error', error);342  file.on('directory', next);343  file.on('stream', stream);344  file.pipe(this);345  this.on('finish', cleanup);346};347348/**349 * Transfer the file at the given `path` as an attachment.350 *351 * Optionally providing an alternate attachment `filename`,352 * and optional callback `fn(err)`. The callback is invoked353 * when the data transfer is complete, or when an error has354 * ocurred. Be sure to check `res.headerSent` if you plan to respond.355 *356 * This method uses `res.sendfile()`.357 *358 * @param {String} path359 * @param {String|Function} filename or fn360 * @param {Function} fn361 * @api public362 */363364res.download = function(path, filename, fn){365  // support function as second arg366  if ('function' == typeof filename) {367    fn = filename;368    filename = null;369  }370371  filename = filename || path;372  this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');373  return this.sendfile(path, fn);374};375376/**377 * Set _Content-Type_ response header with `type` through `mime.lookup()`378 * when it does not contain "/", or set the Content-Type to `type` otherwise.379 *380 * Examples:381 *382 *     res.type('.html');383 *     res.type('html');384 *     res.type('json');385 *     res.type('application/json');386 *     res.type('png');387 *388 * @param {String} type389 * @return {ServerResponse} for chaining390 * @api public391 */392393res.contentType =394res.type = function(type){395  return this.set('Content-Type', ~type.indexOf('/')396    ? type397    : mime.lookup(type));398};399400/**401 * Respond to the Acceptable formats using an `obj`402 * of mime-type callbacks.403 *404 * This method uses `req.accepted`, an array of405 * acceptable types ordered by their quality values.406 * When "Accept" is not present the _first_ callback407 * is invoked, otherwise the first match is used. When408 * no match is performed the server responds with409 * 406 "Not Acceptable".410 *411 * Content-Type is set for you, however if you choose412 * you may alter this within the callback using `res.type()`413 * or `res.set('Content-Type', ...)`.414 *415 *    res.format({416 *      'text/plain': function(){417 *        res.send('hey');418 *      },419 *420 *      'text/html': function(){421 *        res.send('<p>hey</p>');422 *      },423 *424 *      'appliation/json': function(){425 *        res.send({ message: 'hey' });426 *      }427 *    });428 *429 * In addition to canonicalized MIME types you may430 * also use extnames mapped to these types:431 *432 *    res.format({433 *      text: function(){434 *        res.send('hey');435 *      },436 *437 *      html: function(){438 *        res.send('<p>hey</p>');439 *      },440 *441 *      json: function(){442 *        res.send({ message: 'hey' });443 *      }444 *    });445 *446 * By default Express passes an `Error`447 * with a `.status` of 406 to `next(err)`448 * if a match is not made. If you provide449 * a `.default` callback it will be invoked450 * instead.451 *452 * @param {Object} obj453 * @return {ServerResponse} for chaining454 * @api public455 */456457res.format = function(obj){458  var req = this.req459    , next = req.next;460461  var fn = obj.default;462  if (fn) delete obj.default;463  var keys = Object.keys(obj);464465  var key = req.accepts(keys);466467  this.vary("Accept");468469  if (key) {470    var type = normalizeType(key).value;471    var charset = mime.charsets.lookup(type);472    if (charset) type += '; charset=' + charset;473    this.set('Content-Type', type);474    obj[key](req, this, next);475  } else if (fn) {476    fn();477  } else {478    var err = new Error('Not Acceptable');479    err.status = 406;480    err.types = normalizeTypes(keys).map(function(o){ return o.value });481    next(err);482  }483484  return this;485};486487/**488 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.489 *490 * @param {String} filename491 * @return {ServerResponse}492 * @api public493 */494495res.attachment = function(filename){496  if (filename) this.type(extname(filename));497  this.set('Content-Disposition', filename498    ? 'attachment; filename="' + basename(filename) + '"'499    : 'attachment');500  return this;501};502503/**504 * Set header `field` to `val`, or pass505 * an object of header fields.506 *507 * Examples:508 *509 *    res.set('Foo', ['bar', 'baz']);510 *    res.set('Accept', 'application/json');511 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });512 *513 * Aliased as `res.header()`.514 *515 * @param {String|Object|Array} field516 * @param {String} val517 * @return {ServerResponse} for chaining518 * @api public519 */520521res.set =522res.header = function(field, val){523  if (2 == arguments.length) {524    if (Array.isArray(val)) val = val.map(String);525    else val = String(val);526    this.setHeader(field, val);527  } else {528    for (var key in field) {529      this.set(key, field[key]);530    }531  }532  return this;533};534535/**536 * Get value for header `field`.537 *538 * @param {String} field539 * @return {String}540 * @api public541 */542543res.get = function(field){544  return this.getHeader(field);545};546547/**548 * Clear cookie `name`.549 *550 * @param {String} name551 * @param {Object} options552 * @param {ServerResponse} for chaining553 * @api public554 */555556res.clearCookie = function(name, options){557  var opts = { expires: new Date(1), path: '/' };558  return this.cookie(name, '', options559    ? utils.merge(opts, options)560    : opts);561};562563/**564 * Set cookie `name` to `val`, with the given `options`.565 *566 * Options:567 *568 *    - `maxAge`   max-age in milliseconds, converted to `expires`569 *    - `signed`   sign the cookie570 *    - `path`     defaults to "/"571 *572 * Examples:573 *574 *    // "Remember Me" for 15 minutes575 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });576 *577 *    // save as above578 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })579 *580 * @param {String} name581 * @param {String|Object} val582 * @param {Options} options583 * @api public584 */585586res.cookie = function(name, val, options){587  options = utils.merge({}, options);588  var secret = this.req.secret;589  var signed = options.signed;590  if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');591  if ('number' == typeof val) val = val.toString();592  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);593  if (signed) val = 's:' + sign(val, secret);594  if ('maxAge' in options) {595    options.expires = new Date(Date.now() + options.maxAge);596    options.maxAge /= 1000;597  }598  if (null == options.path) options.path = '/';599  this.set('Set-Cookie', cookie.serialize(name, String(val), options));600  return this;601};602603604/**605 * Set the location header to `url`.606 *607 * The given `url` can also be the name of a mapped url, for608 * example by default express supports "back" which redirects609 * to the _Referrer_ or _Referer_ headers or "/".610 *611 * Examples:612 *613 *    res.location('/foo/bar').;614 *    res.location('http://example.com');615 *    res.location('../login'); // /blog/post/1 -> /blog/login616 *617 * Mounting:618 *619 *   When an application is mounted and `res.location()`620 *   is given a path that does _not_ lead with "/" it becomes621 *   relative to the mount-point. For example if the application622 *   is mounted at "/blog", the following would become "/blog/login".623 *624 *      res.location('login');625 *626 *   While the leading slash would result in a location of "/login":627 *628 *      res.location('/login');629 *630 * @param {String} url631 * @api public632 */633634res.location = function(url){635  var app = this.app636    , req = this.req;637638  // setup redirect map639  var map = { back: req.get('Referrer') || '/' };640641  // perform redirect642  url = map[url] || url;643644  // relative645  if (!~url.indexOf('://') && 0 != url.indexOf('//')) {646    var path647648    // relative to path649    if ('.' == url[0]) {650      path = req.originalUrl.split('?')[0]651      url =  path + ('/' == path[path.length - 1] ? '' : '/') + url;652      // relative to mount-point653    } else if ('/' != url[0]) {654      path = app.path();655      url = path + '/' + url;656    }657  }658659  // Respond660  this.set('Location', url);661  return this;662};663664/**665 * Redirect to the given `url` with optional response `status`666 * defaulting to 302.667 *668 * The resulting `url` is determined by `res.location()`, so669 * it will play nicely with mounted apps, relative paths,670 * `"back"` etc.671 *672 * Examples:673 *674 *    res.redirect('/foo/bar');675 *    res.redirect('http://example.com');676 *    res.redirect(301, 'http://example.com');677 *    res.redirect('http://example.com', 301);678 *    res.redirect('../login'); // /blog/post/1 -> /blog/login679 *680 * @param {String} url681 * @param {Number} code682 * @api public683 */684685res.redirect = function(url){686  var head = 'HEAD' == this.req.method687    , status = 302688    , body;689690  // allow status / url691  if (2 == arguments.length) {692    if ('number' == typeof url) {693      status = url;694      url = arguments[1];695    } else {696      status = arguments[1];697    }698  }699700  // Set location header701  this.location(url);702  url = this.get('Location');703704  // Support text/{plain,html} by default705  this.format({706    text: function(){707      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);708    },709710    html: function(){711      var u = utils.escape(url);712      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';713    },714715    default: function(){716      body = '';717    }718  });719720  // Respond721  this.statusCode = status;722  this.set('Content-Length', Buffer.byteLength(body));723  this.end(head ? null : body);724};725726/**727 * Add `field` to Vary. If already present in the Vary set, then728 * this call is simply ignored.729 *730 * @param {Array|String} field731 * @param {ServerResponse} for chaining732 * @api public733 */734735res.vary = function(field){736  var self = this;737738  // nothing739  if (!field) return this;740741  // array742  if (Array.isArray(field)) {743    field.forEach(function(field){744      self.vary(field);745    });746    return;747  }748749  var vary = this.get('Vary');750751  // append752  if (vary) {753    vary = vary.split(/ *, */);754    if (!~vary.indexOf(field)) vary.push(field);755    this.set('Vary', vary.join(', '));756    return this;757  }758759  // set760  this.set('Vary', field);761  return this;762};763764/**765 * Render `view` with the given `options` and optional callback `fn`.766 * When a callback function is given a response will _not_ be made767 * automatically, otherwise a response of _200_ and _text/html_ is given.768 *769 * Options:770 *771 *  - `cache`     boolean hinting to the engine it should cache772 *  - `filename`  filename of the view being rendered773 *774 * @param  {String} view775 * @param  {Object|Function} options or callback function776 * @param  {Function} fn777 * @api public778 */779780res.render = function(view, options, fn){781  var self = this782    , options = options || {}783    , req = this.req784    , app = req.app;785786  // support callback function as second arg787  if ('function' == typeof options) {788    fn = options, options = {};789  }790791  // merge res.locals792  options._locals = self.locals;793794  // default callback to respond795  fn = fn || function(err, str){796    if (err) return req.next(err);797    self.send(str);798  };799800  // render801  app.render(view, options, fn);802};