Skip to content
Myr

response.js

This file

Path

lib/response.js

803 lines · 18.4 KiB · JavaScript

Last changed by

Fix res.jsonp error if callback param is objectDouglas Christopher Wilsonbefore adoptiond58ca52

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  , resolve = require('url').resolve18  , basename = path.basename19  , extname = path.extname;2021/**22 * Response prototype.23 */2425var res = module.exports = {26  __proto__: http.ServerResponse.prototype27};2829/**30 * Set status `code`.31 *32 * @param {Number} code33 * @return {ServerResponse}34 * @api public35 */3637res.status = function(code){38  this.statusCode = code;39  return this;40};4142/**43 * Set Link header field with the given `links`.44 *45 * Examples:46 *47 *    res.links({48 *      next: 'http://api.example.com/users?page=2',49 *      last: 'http://api.example.com/users?page=5'50 *    });51 *52 * @param {Object} links53 * @return {ServerResponse}54 * @api public55 */5657res.links = function(links){58  var link = this.get('Link') || '';59  if (link) link += ', ';60  return this.set('Link', link + Object.keys(links).map(function(rel){61    return '<' + links[rel] + '>; rel="' + rel + '"';62  }).join(', '));63};6465/**66 * Send a response.67 *68 * Examples:69 *70 *     res.send(new Buffer('wahoo'));71 *     res.send({ some: 'json' });72 *     res.send('<p>some html</p>');73 *     res.send(404, 'Sorry, cant find that');74 *     res.send(404);75 *76 * @param {Mixed} body or status77 * @param {Mixed} body78 * @return {ServerResponse}79 * @api public80 */8182res.send = function(body){83  var req = this.req;84  var head = 'HEAD' == req.method;85  var len;8687  // settings88  var app = this.app;8990  // allow status / body91  if (2 == arguments.length) {92    // res.send(body, status) backwards compat93    if ('number' != typeof body && 'number' == typeof arguments[1]) {94      this.statusCode = arguments[1];95    } else {96      this.statusCode = body;97      body = arguments[1];98    }99  }100101  switch (typeof body) {102    // response status103    case 'number':104      this.get('Content-Type') || this.type('txt');105      this.statusCode = body;106      body = http.STATUS_CODES[body];107      break;108    // string defaulting to html109    case 'string':110      if (!this.get('Content-Type')) {111        this.charset = this.charset || 'utf-8';112        this.type('html');113      }114      break;115    case 'boolean':116    case 'object':117      if (null == body) {118        body = '';119      } else if (Buffer.isBuffer(body)) {120        this.get('Content-Type') || this.type('bin');121      } else {122        return this.json(body);123      }124      break;125  }126127  // populate Content-Length128  if (undefined !== body && !this.get('Content-Length')) {129    this.set('Content-Length', len = Buffer.isBuffer(body)130      ? body.length131      : Buffer.byteLength(body));132  }133134  // ETag support135  // TODO: W/ support136  if (app.settings.etag && len && 'GET' == req.method) {137    if (!this.get('ETag')) {138      this.set('ETag', etag(body));139    }140  }141142  // freshness143  if (req.fresh) this.statusCode = 304;144145  // strip irrelevant headers146  if (204 == this.statusCode || 304 == this.statusCode) {147    this.removeHeader('Content-Type');148    this.removeHeader('Content-Length');149    this.removeHeader('Transfer-Encoding');150    body = '';151  }152153  // respond154  this.end(head ? null : body);155  return this;156};157158/**159 * Send JSON response.160 *161 * Examples:162 *163 *     res.json(null);164 *     res.json({ user: 'tj' });165 *     res.json(500, 'oh noes!');166 *     res.json(404, 'I dont have that');167 *168 * @param {Mixed} obj or status169 * @param {Mixed} obj170 * @return {ServerResponse}171 * @api public172 */173174res.json = function(obj){175  // allow status / body176  if (2 == arguments.length) {177    // res.json(body, status) backwards compat178    if ('number' == typeof arguments[1]) {179      this.statusCode = arguments[1];180    } else {181      this.statusCode = obj;182      obj = arguments[1];183    }184  }185186  // settings187  var app = this.app;188  var replacer = app.get('json replacer');189  var spaces = app.get('json spaces');190  var body = JSON.stringify(obj, replacer, spaces);191192  // content-type193  this.charset = this.charset || 'utf-8';194  this.get('Content-Type') || this.set('Content-Type', 'application/json');195196  return this.send(body);197};198199/**200 * Send JSON response with JSONP callback support.201 *202 * Examples:203 *204 *     res.jsonp(null);205 *     res.jsonp({ user: 'tj' });206 *     res.jsonp(500, 'oh noes!');207 *     res.jsonp(404, 'I dont have that');208 *209 * @param {Mixed} obj or status210 * @param {Mixed} obj211 * @return {ServerResponse}212 * @api public213 */214215res.jsonp = function(obj){216  // allow status / body217  if (2 == arguments.length) {218    // res.json(body, status) backwards compat219    if ('number' == typeof arguments[1]) {220      this.statusCode = arguments[1];221    } else {222      this.statusCode = obj;223      obj = arguments[1];224    }225  }226227  // settings228  var app = this.app;229  var replacer = app.get('json replacer');230  var spaces = app.get('json spaces');231  var body = JSON.stringify(obj, replacer, spaces)232    .replace(/\u2028/g, '\\u2028')233    .replace(/\u2029/g, '\\u2029');234  var callback = this.req.query[app.get('jsonp callback name')];235236  // content-type237  this.charset = this.charset || 'utf-8';238  this.set('Content-Type', 'application/json');239240  // fixup callback241  if (Array.isArray(callback)) {242    callback = callback[0];243  }244245  // jsonp246  if (callback && 'string' === typeof callback) {247    this.set('Content-Type', 'text/javascript');248    var cb = callback.replace(/[^\[\]\w$.]/g, '');249    body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');';250  }251252  return this.send(body);253};254255/**256 * Transfer the file at the given `path`.257 *258 * Automatically sets the _Content-Type_ response header field.259 * The callback `fn(err)` is invoked when the transfer is complete260 * or when an error occurs. Be sure to check `res.sentHeader`261 * if you wish to attempt responding, as the header and some data262 * may have already been transferred.263 *264 * Options:265 *266 *   - `maxAge` defaulting to 0267 *   - `root`   root directory for relative filenames268 *269 * Examples:270 *271 *  The following example illustrates how `res.sendfile()` may272 *  be used as an alternative for the `static()` middleware for273 *  dynamic situations. The code backing `res.sendfile()` is actually274 *  the same code, so HTTP cache support etc is identical.275 *276 *     app.get('/user/:uid/photos/:file', function(req, res){277 *       var uid = req.params.uid278 *         , file = req.params.file;279 *280 *       req.user.mayViewFilesFrom(uid, function(yes){281 *         if (yes) {282 *           res.sendfile('/uploads/' + uid + '/' + file);283 *         } else {284 *           res.send(403, 'Sorry! you cant see that.');285 *         }286 *       });287 *     });288 *289 * @param {String} path290 * @param {Object|Function} options or fn291 * @param {Function} fn292 * @api public293 */294295res.sendfile = function(path, options, fn){296  var self = this297    , req = self.req298    , next = this.req.next299    , options = options || {}300    , done;301302  // support function as second arg303  if ('function' == typeof options) {304    fn = options;305    options = {};306  }307308  // socket errors309  req.socket.on('error', error);310311  // errors312  function error(err) {313    if (done) return;314    done = true;315316    // clean up317    cleanup();318    if (!self.headerSent) self.removeHeader('Content-Disposition');319320    // callback available321    if (fn) return fn(err);322323    // list in limbo if there's no callback324    if (self.headerSent) return;325326    // delegate327    next(err);328  }329330  // streaming331  function stream(stream) {332    if (done) return;333    cleanup();334    if (fn) stream.on('end', fn);335  }336337  // cleanup338  function cleanup() {339    req.socket.removeListener('error', error);340  }341342  // transfer343  var file = send(req, path);344  if (options.root) file.root(options.root);345  file.maxage(options.maxAge || 0);346  file.on('error', error);347  file.on('directory', next);348  file.on('stream', stream);349  file.pipe(this);350  this.on('finish', cleanup);351};352353/**354 * Transfer the file at the given `path` as an attachment.355 *356 * Optionally providing an alternate attachment `filename`,357 * and optional callback `fn(err)`. The callback is invoked358 * when the data transfer is complete, or when an error has359 * ocurred. Be sure to check `res.headerSent` if you plan to respond.360 *361 * This method uses `res.sendfile()`.362 *363 * @param {String} path364 * @param {String|Function} filename or fn365 * @param {Function} fn366 * @api public367 */368369res.download = function(path, filename, fn){370  // support function as second arg371  if ('function' == typeof filename) {372    fn = filename;373    filename = null;374  }375376  filename = filename || path;377  this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"');378  return this.sendfile(path, fn);379};380381/**382 * Set _Content-Type_ response header with `type` through `mime.lookup()`383 * when it does not contain "/", or set the Content-Type to `type` otherwise.384 *385 * Examples:386 *387 *     res.type('.html');388 *     res.type('html');389 *     res.type('json');390 *     res.type('application/json');391 *     res.type('png');392 *393 * @param {String} type394 * @return {ServerResponse} for chaining395 * @api public396 */397398res.contentType =399res.type = function(type){400  return this.set('Content-Type', ~type.indexOf('/')401    ? type402    : mime.lookup(type));403};404405/**406 * Respond to the Acceptable formats using an `obj`407 * of mime-type callbacks.408 *409 * This method uses `req.accepted`, an array of410 * acceptable types ordered by their quality values.411 * When "Accept" is not present the _first_ callback412 * is invoked, otherwise the first match is used. When413 * no match is performed the server responds with414 * 406 "Not Acceptable".415 *416 * Content-Type is set for you, however if you choose417 * you may alter this within the callback using `res.type()`418 * or `res.set('Content-Type', ...)`.419 *420 *    res.format({421 *      'text/plain': function(){422 *        res.send('hey');423 *      },424 *425 *      'text/html': function(){426 *        res.send('<p>hey</p>');427 *      },428 *429 *      'appliation/json': function(){430 *        res.send({ message: 'hey' });431 *      }432 *    });433 *434 * In addition to canonicalized MIME types you may435 * also use extnames mapped to these types:436 *437 *    res.format({438 *      text: function(){439 *        res.send('hey');440 *      },441 *442 *      html: function(){443 *        res.send('<p>hey</p>');444 *      },445 *446 *      json: function(){447 *        res.send({ message: 'hey' });448 *      }449 *    });450 *451 * By default Express passes an `Error`452 * with a `.status` of 406 to `next(err)`453 * if a match is not made. If you provide454 * a `.default` callback it will be invoked455 * instead.456 *457 * @param {Object} obj458 * @return {ServerResponse} for chaining459 * @api public460 */461462res.format = function(obj){463  var req = this.req464    , next = req.next;465466  var fn = obj.default;467  if (fn) delete obj.default;468  var keys = Object.keys(obj);469470  var key = req.accepts(keys);471472  this.vary("Accept");473474  if (key) {475    var type = normalizeType(key).value;476    var charset = mime.charsets.lookup(type);477    if (charset) type += '; charset=' + charset;478    this.set('Content-Type', type);479    obj[key](req, this, next);480  } else if (fn) {481    fn();482  } else {483    var err = new Error('Not Acceptable');484    err.status = 406;485    err.types = normalizeTypes(keys).map(function(o){ return o.value });486    next(err);487  }488489  return this;490};491492/**493 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.494 *495 * @param {String} filename496 * @return {ServerResponse}497 * @api public498 */499500res.attachment = function(filename){501  if (filename) this.type(extname(filename));502  this.set('Content-Disposition', filename503    ? 'attachment; filename="' + basename(filename) + '"'504    : 'attachment');505  return this;506};507508/**509 * Set header `field` to `val`, or pass510 * an object of header fields.511 *512 * Examples:513 *514 *    res.set('Foo', ['bar', 'baz']);515 *    res.set('Accept', 'application/json');516 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });517 *518 * Aliased as `res.header()`.519 *520 * @param {String|Object|Array} field521 * @param {String} val522 * @return {ServerResponse} for chaining523 * @api public524 */525526res.set =527res.header = function(field, val){528  if (2 == arguments.length) {529    if (Array.isArray(val)) val = val.map(String);530    else val = String(val);531    this.setHeader(field, val);532  } else {533    for (var key in field) {534      this.set(key, field[key]);535    }536  }537  return this;538};539540/**541 * Get value for header `field`.542 *543 * @param {String} field544 * @return {String}545 * @api public546 */547548res.get = function(field){549  return this.getHeader(field);550};551552/**553 * Clear cookie `name`.554 *555 * @param {String} name556 * @param {Object} options557 * @param {ServerResponse} for chaining558 * @api public559 */560561res.clearCookie = function(name, options){562  var opts = { expires: new Date(1), path: '/' };563  return this.cookie(name, '', options564    ? utils.merge(opts, options)565    : opts);566};567568/**569 * Set cookie `name` to `val`, with the given `options`.570 *571 * Options:572 *573 *    - `maxAge`   max-age in milliseconds, converted to `expires`574 *    - `signed`   sign the cookie575 *    - `path`     defaults to "/"576 *577 * Examples:578 *579 *    // "Remember Me" for 15 minutes580 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });581 *582 *    // save as above583 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })584 *585 * @param {String} name586 * @param {String|Object} val587 * @param {Options} options588 * @api public589 */590591res.cookie = function(name, val, options){592  options = utils.merge({}, options);593  var secret = this.req.secret;594  var signed = options.signed;595  if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');596  if ('number' == typeof val) val = val.toString();597  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);598  if (signed) val = 's:' + sign(val, secret);599  if ('maxAge' in options) {600    options.expires = new Date(Date.now() + options.maxAge);601    options.maxAge /= 1000;602  }603  if (null == options.path) options.path = '/';604  this.set('Set-Cookie', cookie.serialize(name, String(val), options));605  return this;606};607608609/**610 * Set the location header to `url`.611 *612 * The given `url` can also be "back", which redirects613 * to the _Referrer_ or _Referer_ headers or "/".614 *615 * Examples:616 *617 *    res.location('/foo/bar').;618 *    res.location('http://example.com');619 *    res.location('../login'); // /blog/post/1 -> /blog/login620 *621 * Mounting:622 *623 *   When an application is mounted and `res.location()`624 *   is given a path that does _not_ lead with "/" it becomes625 *   relative to the mount-point. For example if the application626 *   is mounted at "/blog", the following would become "/blog/login".627 *628 *      res.location('login');629 *630 *   While the leading slash would result in a location of "/login":631 *632 *      res.location('/login');633 *634 * @param {String} url635 * @api public636 */637638res.location = function(url){639  var app = this.app640    , req = this.req641    , path;642643  // "back" is an alias for the referrer644  if ('back' == url) url = req.get('Referrer') || '/';645646  // relative647  if (!~url.indexOf('://') && 0 != url.indexOf('//')) {648    // relative to path649    if ('.' == url[0]) {650      path = req.originalUrl.split('?')[0];651      path = path + ('/' == path[path.length - 1] ? '' : '/');652      url = resolve(path, url);653      // relative to mount-point654    } else if ('/' != url[0]) {655      path = app.path();656      url = path + '/' + url;657    }658  }659660  // Respond661  this.set('Location', url);662  return this;663};664665/**666 * Redirect to the given `url` with optional response `status`667 * defaulting to 302.668 *669 * The resulting `url` is determined by `res.location()`, so670 * it will play nicely with mounted apps, relative paths,671 * `"back"` etc.672 *673 * Examples:674 *675 *    res.redirect('/foo/bar');676 *    res.redirect('http://example.com');677 *    res.redirect(301, 'http://example.com');678 *    res.redirect('http://example.com', 301);679 *    res.redirect('../login'); // /blog/post/1 -> /blog/login680 *681 * @param {String} url682 * @param {Number} code683 * @api public684 */685686res.redirect = function(url){687  var head = 'HEAD' == this.req.method688    , status = 302689    , body;690691  // allow status / url692  if (2 == arguments.length) {693    if ('number' == typeof url) {694      status = url;695      url = arguments[1];696    } else {697      status = arguments[1];698    }699  }700701  // Set location header702  this.location(url);703  url = this.get('Location');704705  // Support text/{plain,html} by default706  this.format({707    text: function(){708      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);709    },710711    html: function(){712      var u = utils.escape(url);713      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';714    },715716    default: function(){717      body = '';718    }719  });720721  // Respond722  this.statusCode = status;723  this.set('Content-Length', Buffer.byteLength(body));724  this.end(head ? null : body);725};726727/**728 * Add `field` to Vary. If already present in the Vary set, then729 * this call is simply ignored.730 *731 * @param {Array|String} field732 * @param {ServerResponse} for chaining733 * @api public734 */735736res.vary = function(field){737  var self = this;738739  // nothing740  if (!field) return this;741742  // array743  if (Array.isArray(field)) {744    field.forEach(function(field){745      self.vary(field);746    });747    return;748  }749750  var vary = this.get('Vary');751752  // append753  if (vary) {754    vary = vary.split(/ *, */);755    if (!~vary.indexOf(field)) vary.push(field);756    this.set('Vary', vary.join(', '));757    return this;758  }759760  // set761  this.set('Vary', field);762  return this;763};764765/**766 * Render `view` with the given `options` and optional callback `fn`.767 * When a callback function is given a response will _not_ be made768 * automatically, otherwise a response of _200_ and _text/html_ is given.769 *770 * Options:771 *772 *  - `cache`     boolean hinting to the engine it should cache773 *  - `filename`  filename of the view being rendered774 *775 * @param  {String} view776 * @param  {Object|Function} options or callback function777 * @param  {Function} fn778 * @api public779 */780781res.render = function(view, options, fn){782  var self = this783    , options = options || {}784    , req = this.req785    , app = req.app;786787  // support callback function as second arg788  if ('function' == typeof options) {789    fn = options, options = {};790  }791792  // merge res.locals793  options._locals = self.locals;794795  // default callback to respond796  fn = fn || function(err, str){797    if (err) return req.next(err);798    self.send(str);799  };800801  // render802  app.render(view, options, fn);803};