Skip to content
Myr

response.js

This file

Path

lib/response.js

720 lines · 16.5 KiB · JavaScript

Last changed by

fix jsonp whitespace escape. Closes #1132Guillermo Rauchbefore adoption64a2349

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.extname19  , join = path.join;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  return this.set('Link', Object.keys(links).map(function(rel){59    return '<' + links[rel] + '>; rel="' + rel + '"';60  }).join(', '));61};6263/**64 * Send a response.65 *66 * Examples:67 *68 *     res.send(new Buffer('wahoo'));69 *     res.send({ some: 'json' });70 *     res.send('<p>some html</p>');71 *     res.send(404, 'Sorry, cant find that');72 *     res.send(404);73 *74 * @param {Mixed} body or status75 * @param {Mixed} body76 * @return {ServerResponse}77 * @api public78 */7980res.send = function(body){81  var req = this.req82    , head = 'HEAD' == req.method83    , len;8485  // allow status / body86  if (2 == arguments.length) {87    // res.send(body, status) backwards compat88    if ('number' != typeof body && 'number' == typeof arguments[1]) {89      this.statusCode = arguments[1];90    } else {91      this.statusCode = body;92      body = arguments[1];93    }94  }9596  switch (typeof body) {97    // response status98    case 'number':99      this.get('Content-Type') || this.type('txt');100      this.statusCode = body;101      body = http.STATUS_CODES[body];102      break;103    // string defaulting to html104    case 'string':105      if (!this.get('Content-Type')) {106        this.charset = this.charset || 'utf-8';107        this.type('html');108      }109      break;110    case 'boolean':111    case 'object':112      if (null == body) {113        body = '';114      } else if (Buffer.isBuffer(body)) {115        this.get('Content-Type') || this.type('bin');116      } else {117        return this.json(body);118      }119      break;120  }121122  // populate Content-Length123  if (undefined !== body && !this.get('Content-Length')) {124    this.set('Content-Length', len = Buffer.isBuffer(body)125      ? body.length126      : Buffer.byteLength(body));127  }128129  // ETag support130  // TODO: W/ support131  if (len > 1024) {132    if (!this.get('ETag')) {133      this.set('ETag', etag(body));134    }135  }136137  // freshness138  if (req.fresh) this.statusCode = 304;139140  // strip irrelevant headers141  if (204 == this.statusCode || 304 == this.statusCode) {142    this.removeHeader('Content-Type');143    this.removeHeader('Content-Length');144    this.removeHeader('Transfer-Encoding');145    body = '';146  }147148  // respond149  this.end(head ? null : body);150  return this;151};152153/**154 * Send JSON response.155 *156 * Examples:157 *158 *     res.json(null);159 *     res.json({ user: 'tj' });160 *     res.json(500, 'oh noes!');161 *     res.json(404, 'I dont have that');162 *163 * @param {Mixed} obj or status164 * @param {Mixed} obj165 * @return {ServerResponse}166 * @api public167 */168169res.json = function(obj){170  // allow status / body171  if (2 == arguments.length) {172    // res.json(body, status) backwards compat173    if ('number' == typeof arguments[1]) {174      this.statusCode = arguments[1];175    } else {176      this.statusCode = obj;177      obj = arguments[1];178    }179  }180181  // settings182  var app = this.app;183  var replacer = app.get('json replacer');184  var spaces = app.get('json spaces');185  var body = JSON.stringify(obj, replacer, spaces);186187  // content-type188  this.charset = this.charset || 'utf-8';189  this.get('Content-Type') || this.set('Content-Type', 'application/json');190  191  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.charset = this.charset || 'utf-8';233  this.set('Content-Type', 'application/json');234  235  // jsonp236  if (callback) {237    this.set('Content-Type', 'text/javascript');238    var cb = callback.replace(/[^\[\]\w$.]/g, '');239    body = cb + ' && ' + 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.headerSent) self.removeHeader('Content-Disposition');309310    // callback available311    if (fn) return fn(err);312313    // list in limbo if there's no callback314    if (self.headerSent) return;315316    // delegate317    next(err);318  }319320  // streaming321  function stream() {322    if (done) return;323    cleanup();324    if (fn) self.on('finish', 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.headerSent` 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.set('Vary', 'Accept');463464  if (key) {465    this.set('Content-Type', normalizeType(key));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);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('Accept', 'application/json');502 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });503 *504 * Aliased as `res.header()`. 505 *506 * @param {String|Object} field507 * @param {String} val508 * @return {ServerResponse} for chaining509 * @api public510 */511512res.set = 513res.header = function(field, val){514  if (2 == arguments.length) {515    this.setHeader(field, '' + val);516  } else {517    for (var key in field) {518      this.setHeader(key, '' + field[key]);519    }520  }521  return this;522};523524/**525 * Get value for header `field`.526 *527 * @param {String} field528 * @return {String}529 * @api public530 */531532res.get = function(field){533  return this.getHeader(field);534};535536/**537 * Clear cookie `name`.538 *539 * @param {String} name540 * @param {Object} options541 * @param {ServerResponse} for chaining542 * @api public543 */544545res.clearCookie = function(name, options){546  var opts = { expires: new Date(1), path: '/' };547  return this.cookie(name, '', options548    ? utils.merge(opts, options)549    : opts);550};551552/**553 * Set cookie `name` to `val`, with the given `options`.554 *555 * Options:556 *557 *    - `maxAge`   max-age in milliseconds, converted to `expires`558 *    - `signed`   sign the cookie559 *    - `path`     defaults to "/"560 *561 * Examples:562 *563 *    // "Remember Me" for 15 minutes564 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });565 *566 *    // save as above567 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })568 *569 * @param {String} name570 * @param {String|Object} val571 * @param {Options} options572 * @api public573 */574575res.cookie = function(name, val, options){576  options = options || {};577  var secret = this.req.secret;578  var signed = options.signed;579  if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies');580  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);581  if (signed) val = 's:' + sign(val, secret);582  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);583  if (null == options.path) options.path = '/';584  options.maxAge /= 1000;585  this.set('Set-Cookie', cookie.serialize(name, String(val), options));586  return this;587};588589/**590 * Redirect to the given `url` with optional response `status`591 * defaulting to 302.592 *593 * The given `url` can also be the name of a mapped url, for594 * example by default express supports "back" which redirects595 * to the _Referrer_ or _Referer_ headers or "/".596 *597 * Examples:598 *599 *    res.redirect('/foo/bar');600 *    res.redirect('http://example.com');601 *    res.redirect(301, 'http://example.com');602 *    res.redirect('http://example.com', 301);603 *    res.redirect('../login'); // /blog/post/1 -> /blog/login604 *605 * Mounting:606 *607 *   When an application is mounted, and `res.redirect()`608 *   is given a path that does _not_ lead with "/". For 609 *   example suppose a "blog" app is mounted at "/blog",610 *   the following redirect would result in "/blog/login":611 *612 *      res.redirect('login');613 *614 *   While the leading slash would result in a redirect to "/login":615 *616 *      res.redirect('/login');617 *618 * @param {String} url619 * @param {Number} code620 * @api public621 */622623res.redirect = function(url){624  var app = this.app625    , req = this.req626    , head = 'HEAD' == req.method627    , status = 302628    , body;629630  // allow status / url631  if (2 == arguments.length) {632    if ('number' == typeof url) {633      status = url;634      url = arguments[1];635    } else {636      status = arguments[1];637    }638  }639640  // setup redirect map641  var map = { back: req.get('Referrer') || '/' };642643  // perform redirect644  url = map[url] || url;645646  // relative647  if (!~url.indexOf('://') && 0 != url.indexOf('//')) {648    var path = app.path();649650    // relative to path651    if ('.' == url[0]) {652      url = req.path + '/' + url;653    // relative to mount-point654    } else if ('/' != url[0]) {655      url = path + '/' + url;656    }657  }658659  // Support text/{plain,html} by default660  this.format({661    text: function(){662      body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);663    },664665    html: function(){666      var u = utils.escape(url);667      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';668    },669670    default: function(){671      body = '';672    }673  });674675  // Respond676  this.statusCode = status;677  this.set('Location', url);678  this.set('Content-Length', Buffer.byteLength(body));679  this.end(head ? null : body);680};681682/**683 * Render `view` with the given `options` and optional callback `fn`.684 * When a callback function is given a response will _not_ be made685 * automatically, otherwise a response of _200_ and _text/html_ is given.686 *687 * Options:688 *689 *  - `cache`     boolean hinting to the engine it should cache690 *  - `filename`  filename of the view being rendered691 *692 * @param  {String} view693 * @param  {Object|Function} options or callback function694 * @param  {Function} fn695 * @api public696 */697698res.render = function(view, options, fn){699  var self = this700    , options = options || {}701    , req = this.req702    , app = req.app;703704  // support callback function as second arg705  if ('function' == typeof options) {706    fn = options, options = {};707  }708709  // merge res.locals710  options._locals = self.locals;711712  // default callback to respond713  fn = fn || function(err, str){714    if (err) return req.next(err);715    self.send(str);716  };717718  // render719  app.render(view, options, fn);720};