Skip to content
Myr

response.js

This file

Path

lib/response.js

647 lines · 15.0 KiB · JavaScript

Last changed by

Fixed: expose connects mime module. Cloases #1165TJ Holowaychukbefore adoption8956731

History of this file

Take it

12/**3 * Module dependencies.4 */56var fs = require('fs')7  , http = require('http')8  , path = require('path')9  , connect = require('connect')10  , utils = connect.utils11  , normalizeType = require('./utils').normalizeType12  , normalizeTypes = require('./utils').normalizeTypes13  , statusCodes = http.STATUS_CODES14  , send = connect.static.send15  , cookie = require('cookie')16  , crc = require('crc')17  , mime = connect.mime18  , basename = path.basename19  , extname = path.extname20  , join = path.join;2122/**23 * Response prototype.24 */2526var res = module.exports = {27  __proto__: http.ServerResponse.prototype28};2930/**31 * Set status `code`.32 *33 * @param {Number} code34 * @return {ServerResponse}35 * @api public36 */3738res.status = function(code){39  this.statusCode = code;40  return this;41};4243/**44 * Send a response.45 *46 * Examples:47 *48 *     res.send(new Buffer('wahoo'));49 *     res.send({ some: 'json' });50 *     res.send('<p>some html</p>');51 *     res.send(404, 'Sorry, cant find that');52 *     res.send(404);53 *54 * @param {Mixed} body or status55 * @param {Mixed} body56 * @return {ServerResponse}57 * @api public58 */5960res.send = function(body){61  var req = this.req62    , head = 'HEAD' == req.method63    , len;6465  // allow status / body66  if (2 == arguments.length) {67    this.statusCode = body;68    body = arguments[1];69  }70  71  // convert string objects to primitives72  if (body instanceof String) body = body.toString();7374  switch (typeof body) {75    // response status76    case 'number':77      this.get('Content-Type') || this.type('txt');78      this.statusCode = body;79      body = http.STATUS_CODES[body];80      break;81    // string defaulting to html82    case 'string':83      if (!this.get('Content-Type')) {84        this.charset = this.charset || 'utf-8';85        this.type('html');86      }87      break;88    case 'boolean':89    case 'object':90      if (null == body) {91        body = '';92      } else if (Buffer.isBuffer(body)) {93        this.get('Content-Type') || this.type('bin');94      } else {95        return this.json(body);96      }97      break;98  }99100  // populate Content-Length101  if (undefined !== body && !this.get('Content-Length')) {102    this.set('Content-Length', len = Buffer.isBuffer(body)103      ? body.length104      : Buffer.byteLength(body));105  }106107  // ETag support108  // TODO: W/ support109  if (len > 1024) {110    if (!this.get('ETag')) this.set('ETag', Buffer.isBuffer(body)111      ? crc.buffer.crc32(body)112      : crc.crc32(body));113    if (req.fresh) this.statusCode = 304;114  }115116  // strip irrelevant headers117  if (204 == this.statusCode || 304 == this.statusCode) {118    this.removeHeader('Content-Type');119    this.removeHeader('Content-Length');120    body = '';121  }122123  // respond124  this.end(head ? null : body);125  return this;126};127128/**129 * Send JSON response.130 *131 * Examples:132 *133 *     res.json(null);134 *     res.json({ user: 'tj' });135 *     res.json(500, 'oh noes!');136 *     res.json(404, 'I dont have that');137 *138 * @param {Mixed} obj or status139 * @param {Mixed} obj140 * @return {ServerResponse}141 * @api public142 */143144res.json = function(obj){145  // allow status / body146  if (2 == arguments.length) {147    this.statusCode = obj;148    obj = arguments[1];149  }150151  var app = this.app152    , jsonp = app.get('jsonp callback')153    , replacer = app.get('json replacer')154    , spaces = app.get('json spaces')155    , body = JSON.stringify(obj, replacer, spaces)156    , callback = this.req.query.callback;157158  this.charset = this.charset || 'utf-8';159  this.set('Content-Type', 'application/json');160161  if (callback && jsonp) {162    this.set('Content-Type', 'text/javascript');163    body = callback.replace(/[^[]\w$.]/g, '') + '(' + body + ');';164  }165166  return this.send(body);167};168169/**170 * Transfer the file at the given `path`.171 * 172 * Automatically sets the _Content-Type_ response header field.173 * The callback `fn(err)` is invoked when the transfer is complete174 * or when an error occurs. Be sure to check `res.sentHeader`175 * if you wish to attempt responding, as the header and some data176 * may have already been transferred.177 *178 * Options:179 *180 *   - `maxAge` defaulting to 0181 *   - `root`   root directory for relative filenames182 *183 * Examples:184 *185 *  The following example illustrates how `res.sendfile()` may186 *  be used as an alternative for the `static()` middleware for187 *  dynamic situations. The code backing `res.sendfile()` is actually188 *  the same code, so HTTP cache support etc is identical.189 *190 *     app.get('/user/:uid/photos/:file', function(req, res){191 *       var uid = req.params.uid192 *         , file = req.params.file;193 *     194 *       req.user.mayViewFilesFrom(uid, function(yes){195 *         if (yes) {196 *           res.sendfile('/uploads/' + uid + '/' + file);197 *         } else {198 *           res.send(403, 'Sorry! you cant see that.');199 *         }200 *       });201 *     });202 *203 * @param {String} path204 * @param {Object|Function} options or fn205 * @param {Function} fn206 * @api public207 */208209res.sendfile = function(path, options, fn){210  var self = this211    , req = self.req212    , next = this.req.next213    , options = options || {};214215  // support function as second arg216  if ('function' == typeof options) {217    fn = options;218    options = {};219  }220221  // callback222  options.callback = function(err){223    if (err) {224      // cast ENOENT225      if ('ENOENT' == err.code) err = utils.error(404);226227      // ditch content-disposition to prevent funky responses228      if (!self.headerSent) self.removeHeader('Content-Disposition');229230      // woot! callback available231      if (fn) return fn(err);232233      // lost in limbo if there's no callback234      if (self.headerSent) return;235236      return req.next(err);237    }238239    fn && fn();240  };241242  // transfer243  options.path = encodeURIComponent(path);244  send(this.req, this, next, options);245};246247/**248 * Transfer the file at the given `path` as an attachment.249 *250 * Optionally providing an alternate attachment `filename`,251 * and optional callback `fn(err)`. The callback is invoked252 * when the data transfer is complete, or when an error has253 * ocurred. Be sure to check `res.headerSent` if you plan to respond.254 *255 * This method uses `res.sendfile()`.256 *257 * @param {String} path258 * @param {String|Function} filename or fn259 * @param {Function} fn260 * @api public261 */262263res.download = function(path, filename, fn){264  // support function as second arg265  if ('function' == typeof filename) {266    fn = filename;267    filename = null;268  }269270  filename = filename || path;271  this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');272  return this.sendfile(path, fn);273};274275/**276 * Set _Content-Type_ response header with `type` through `mime.lookup()`277 * when it does not contain "/", or set the Content-Type to `type` otherwise.278 *279 * Examples:280 *281 *     res.type('.html');282 *     res.type('html');283 *     res.type('json');284 *     res.type('application/json');285 *     res.type('png');286 *287 * @param {String} type288 * @return {ServerResponse} for chaining289 * @api public290 */291292res.contentType =293res.type = function(type){294  return this.set('Content-Type', ~type.indexOf('/')295    ? type296    : mime.lookup(type));297};298299/**300 * Respond to the Acceptable formats using an `obj`301 * of mime-type callbacks.302 *303 * This method uses `req.accepted`, an array of304 * acceptable types ordered by their quality values.305 * When "Accept" is not present the _first_ callback306 * is invoked, otherwise the first match is used. When307 * no match is performed the server responds with308 * 406 "Not Acceptable".309 *310 * Content-Type is set for you, however if you choose311 * you may alter this within the callback using `res.type()`312 * or `res.set('Content-Type', ...)`.313 *314 *    res.format({315 *      'text/plain': function(){316 *        res.send('hey');317 *      },318 *    319 *      'text/html': function(){320 *        res.send('<p>hey</p>');321 *      },322 *    323 *      'appliation/json': function(){324 *        res.send({ message: 'hey' });325 *      }326 *    });327 *328 * In addition to canonicalized MIME types you may329 * also use extnames mapped to these types:330 *331 *    res.format({332 *      text: function(){333 *        res.send('hey');334 *      },335 *    336 *      html: function(){337 *        res.send('<p>hey</p>');338 *      },339 *    340 *      json: function(){341 *        res.send({ message: 'hey' });342 *      }343 *    });344 *345 * By default Express passes an `Error`346 * with a `.status` of 406 to `next(err)`347 * if a match is not made, however you may348 * provide an optional callback `fn` to349 * be invoked instead.350 *351 * @param {Object} obj352 * @param {Function} fn353 * @return {ServerResponse} for chaining354 * @api public355 */356357res.format = function(obj, fn){358  var keys = Object.keys(obj)359    , req = this.req360    , next = req.next361    , key = req.accepts(keys);362363  this.set('Vary', 'Accept');364365  if (key) {366    this.set('Content-Type', normalizeType(key));367    obj[key](req, this, next);368  } else if (fn) {369    fn();370  } else {371    var err = new Error('Not Acceptable');372    err.status = 406;373    err.types = normalizeTypes(keys);374    next(err);375  }376377  return this;378};379380/**381 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.382 *383 * @param {String} filename384 * @return {ServerResponse}385 * @api public386 */387388res.attachment = function(filename){389  if (filename) this.type(extname(filename));390  this.set('Content-Disposition', filename391    ? 'attachment; filename="' + basename(filename) + '"'392    : 'attachment');393  return this;394};395396/**397 * Set header `field` to `val`, or pass398 * an object of of header fields.399 *400 * Examples:401 *402 *    res.set('Accept', 'application/json');403 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });404 *405 * Aliased as `res.header()`. 406 *407 * @param {String|Object} field408 * @param {String} val409 * @return {ServerResponse} for chaining410 * @api public411 */412413res.set = 414res.header = function(field, val){415  if (2 == arguments.length) {416    this.setHeader(field, '' + val);417  } else {418    for (var key in field) {419      this.setHeader(key, '' + field[key]);420    }421  }422  return this;423};424425/**426 * Get value for header `field`.427 *428 * @param {String} field429 * @return {String}430 * @api public431 */432433res.get = function(field){434  return this.getHeader(field);435};436437/**438 * Clear cookie `name`.439 *440 * @param {String} name441 * @param {Object} options442 * @param {ServerResponse} for chaining443 * @api public444 */445446res.clearCookie = function(name, options){447  var opts = { expires: new Date(1), path: '/' };448  return this.cookie(name, '', options449    ? utils.merge(opts, options)450    : opts);451};452453/**454 * Set cookie `name` to `val`, with the given `options`.455 *456 * Options:457 *458 *    - `maxAge`   max-age in milliseconds, converted to `expires`459 *    - `signed`   sign the cookie460 *    - `path`     defaults to "/"461 *462 * Examples:463 *464 *    // "Remember Me" for 15 minutes465 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });466 *467 *    // save as above468 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })469 *470 * @param {String} name471 * @param {String|Object} val472 * @param {Options} options473 * @api public474 */475476res.cookie = function(name, val, options){477  options = options || {};478  var secret = this.req.secret;479  var signed = options.signed;480  if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');481  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);482  if (signed) val = utils.sign(val, secret);483  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);484  if (null == options.path) options.path = '/';485  this.set('Set-Cookie', cookie.serialize(name, String(val), options));486  return this;487};488489/**490 * Redirect to the given `url` with optional response `status`491 * defaulting to 302.492 *493 * The given `url` can also be the name of a mapped url, for494 * example by default express supports "back" which redirects495 * to the _Referrer_ or _Referer_ headers or "/".496 *497 * Examples:498 *499 *    res.redirect('/foo/bar');500 *    res.redirect('http://example.com');501 *    res.redirect(301, 'http://example.com');502 *    res.redirect('../login'); // /blog/post/1 -> /blog/login503 *504 * Mounting:505 *506 *   When an application is mounted, and `res.redirect()`507 *   is given a path that does _not_ lead with "/". For 508 *   example suppose a "blog" app is mounted at "/blog",509 *   the following redirect would result in "/blog/login":510 *511 *      res.redirect('login');512 *513 *   While the leading slash would result in a redirect to "/login":514 *515 *      res.redirect('/login');516 *517 * @param {String} url518 * @param {Number} code519 * @api public520 */521522res.redirect = function(url){523  var app = this.app524    , req = this.req525    , head = 'HEAD' == req.method526    , status = 302527    , body;528529  // allow status / url530  if (2 == arguments.length) {531    status = url;532    url = arguments[1];533  }534535  // setup redirect map536  var map = { back: req.get('Referrer') || '/' };537538  // perform redirect539  url = map[url] || url;540541  // relative542  if (!~url.indexOf('://')) {543    var path = app.path();544545    // relative to path546    if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {547      url = req.path + '/' + url;548    // relative to mount-point549    } else if ('/' != url[0]) {550      url = path + '/' + url;551    }552553    // Absolute554    var host = req.get('Host');555    url = req.protocol + '://' + host + url;556  }557558  // Support text/{plain,html} by default559  this.format({560    text: function(){561      body = statusCodes[status] + '. Redirecting to ' + url;562    },563564    html: function(){565      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';566    }567  }, function(){568    body = '';569  })570571  // Respond572  this.statusCode = status;573  this.set('Location', url);574  this.set('Content-Length', Buffer.byteLength(body));575  this.end(head ? null : body);576};577578/**579 * Render `view` with the given `options` and optional callback `fn`.580 * When a callback function is given a response will _not_ be made581 * automatically, otherwise a response of _200_ and _text/html_ is given.582 *583 * Options:584 *  585 *  - `status`    Response status code (`res.statusCode`)586 *  - `charset`   Set the charset (`res.charset`)587 *588 * Reserved locals:589 *590 *  - `cache`     boolean hinting to the engine it should cache591 *  - `filename`  filename of the view being rendered592 *593 * @param  {String} view594 * @param  {Object|Function} options or callback function595 * @param  {Function} fn596 * @api public597 */598599res.render = function(view, options, fn){600  var self = this601    , options = options || {}602    , req = this.req603    , app = req.app;604605  // support callback function as second arg606  if ('function' == typeof options) {607    fn = options, options = {};608  }609610  function render() {611    // merge res.locals612    options.locals = self.locals;613614    // default callback to respond615    fn = fn || function(err, str){616      if (err) return req.next(err);617      self.send(str);618    };619620    // render621    app.render(view, options, fn);622  }623624  // invoke view callbacks625  var callbacks = app.viewCallbacks.concat(self.viewCallbacks)626    , pending = callbacks.length627    , len = pending628    , done;629630  if (len) {631    for (var i = 0; i < len; ++i) {632      callbacks[i](req, self, function(err){633        if (done) return;634635        if (err) {636          req.next(err);637          done = true;638          return;639        }640641        --pending || render();642      });643    }644  } else {645    render();646  }647};