Skip to content
Myr

response.js

This file

Path

lib/response.js

576 lines · 13.0 KiB · JavaScript

Last changed by

Added X-Forwarded-Proto support to `res.redirect()`. Closes #927Tj Holowaychukbefore adoption5757f87

History of this file

Take it

12/*!3 * Express - response4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var fs = require('fs')13  , http = require('http')14  , path = require('path')15  , connect = require('connect')16  , utils = connect.utils17  , statusCodes = http.STATUS_CODES18  , send = connect.static.send19  , mime = require('mime')20  , basename = path.basename21  , join = path.join;2223/**24 * Response prototype.25 */2627var res = module.exports = {28  __proto__: http.ServerResponse.prototype29};3031/**32 * Set status `code`.33 *34 * @param {Number} code35 * @return {ServerResponse}36 * @api public37 */3839res.status = function(code){40  this.statusCode = code;41  return this;42};4344/**45 * Set Cache-Control to the given `type` and `options`.46 *47 * Options:48 *49 *  - `maxAge` in milliseconds50 *51 * @param {String} type52 * @param {Object} options53 * @return {ServerResponse}54 * @api public55 */5657res.cache = function(type, options){58  var val = type;59  options = options || {};60  if (options.maxAge) val += ', max-age=' + (options.maxAge / 1000); 61  return this.set('Cache-Control', val);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.req83    , head = 'HEAD' == req.method;8485  // allow status / body86  if (2 == arguments.length) {87    this.statusCode = body;88    body = arguments[1];89  }9091  switch (typeof body) {92    // response status93    case 'number':94      this.header('Content-Type') || this.contentType('.txt');95      this.statusCode = body;96      body = http.STATUS_CODES[body];97      break;98    // string defaulting to html99    case 'string':100      if (!this.header('Content-Type')) {101        this.charset = this.charset || 'utf-8';102        this.contentType('.html');103      }104      break;105    case 'boolean':106    case 'object':107      if (null == body) {108        body = '';109      } else if (Buffer.isBuffer(body)) {110        this.header('Content-Type') || this.contentType('.bin');111      } else {112        return this.json(body);113      }114      break;115  }116117  // populate Content-Length118  if (undefined !== body && !this.header('Content-Length')) {119    this.header('Content-Length', Buffer.isBuffer(body)120      ? body.length121      : Buffer.byteLength(body));122  }123124  // strip irrelevant headers125  if (204 == this.statusCode || 304 == this.statusCode) {126    this.removeHeader('Content-Type');127    this.removeHeader('Content-Length');128    body = '';129  }130131  // respond132  this.end(head ? null : body);133  return this;134};135136/**137 * Send JSON response.138 *139 * Examples:140 *141 *     res.json(null);142 *     res.json({ user: 'tj' });143 *     res.json(500, 'oh noes!');144 *     res.json(404, 'I dont have that');145 *146 * @param {Mixed} obj or status147 * @param {Mixed} obj148 * @return {ServerResponse}149 * @api public150 */151152res.json = function(obj){153  // allow status / body154  if (2 == arguments.length) {155    this.statusCode = obj;156    obj = arguments[1];157  }158159  var body = JSON.stringify(obj)160    , callback = this.req.query.callback161    , jsonp = this.app.enabled('jsonp callback');162163  this.charset = this.charset || 'utf-8';164  this.header('Content-Type', 'application/json');165166  if (callback && jsonp) {167    this.header('Content-Type', 'text/javascript');168    body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';169  }170171  return this.send(body);172};173174/**175 * Transfer the file at the given `path`.176 * 177 * Automatically sets the _Content-Type_ response header field.178 * The callback `fn(err)` is invoked when the transfer is complete179 * or when an error occurs. Be sure to check `res.sentHeader`180 * if you wish to attempt responding, as the header and some data181 * may have already been transferred.182 *183 * Options:184 *185 *   - `maxAge` defaulting to 0186 *   - `root`   root directory for relative filenames187 *188 * @param {String} path189 * @param {Object|Function} options or fn190 * @param {Function} fn191 * @api public192 */193194res.sendfile = function(path, options, fn){195  var self = this196    , req = self.req197    , next = this.req.next198    , options = options || {};199200  // support function as second arg201  if ('function' == typeof options) {202    fn = options;203    options = {};204  }205206  // callback207  options.callback = function(err){208    if (err) {209      // cast ENOENT210      if ('ENOENT' == err.code) err = 404;211212      // coerce numeric error to an Error213      // TODO: remove214      // TODO: remove docs for headerSent?215      if ('number' == typeof err) err = utils.error(err);216217      // ditch content-disposition to prevent funky responses218      if (!self.headerSent) self.removeHeader('Content-Disposition');219220      // woot! callback available221      if (fn) return fn(err);222223      // lost in limbo if there's no callback224      if (self.headerSent) return;225226      return req.next(err);227    }228229    fn && fn();230  };231232  // transfer233  options.path = encodeURIComponent(path);234  send(this.req, this, next, options);235};236237/**238 * Transfer the file at the given `path` as an attachment.239 *240 * Optionally providing an alternate attachment `filename`,241 * and optional callback `fn(err)`. The callback is invoked242 * when the data transfer is complete, or when an error has243 * ocurred. Be sure to check `res.headerSent` if you plan to respond.244 *245 * @param {String} path246 * @param {String|Function} filename or fn247 * @param {Function} fn248 * @api public249 */250251res.download = function(path, filename, fn){252  // support function as second arg253  if ('function' == typeof filename) {254    fn = filename;255    filename = null;256  }257258  return this.attachment(filename || path).sendfile(path, fn);259};260261/**262 * Set _Content-Type_ response header passed through `mime.lookup()`.263 *264 * Examples:265 *266 *     var filename = 'path/to/image.png';267 *     res.contentType(filename);268 *     // res.headers['Content-Type'] is now "image/png"269 *270 *     res.contentType('.html');271 *     res.contentType('html');272 *     res.contentType('json');273 *     res.contentType('png');274 *     res.type('png');275 *276 * @param {String} type277 * @return {ServerResponse} for chaining278 * @api public279 */280281res.contentType =282res.type = function(type){283  return this.header('Content-Type', mime.lookup(type));284};285286/**287 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.288 *289 * @param {String} filename290 * @return {ServerResponse}291 * @api public292 */293294res.attachment = function(filename){295  if (filename) this.type(filename);296  this.header('Content-Disposition', filename297    ? 'attachment; filename="' + basename(filename) + '"'298    : 'attachment');299  return this;300};301302/**303 * Set header `field` to `val`, or pass304 * an object of of header fields.305 *306 * Examples:307 *308 *    res.set('Accept', 'application/json');309 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });310 *311 * @param {String|Object} field312 * @param {String} val313 * @return {ServerResponse} for chaining314 * @api public315 */316317res.set = function(field, val){318  if (2 == arguments.length) {319    this.setHeader(field, val);320  } else {321    for (var key in field) {322      this.setHeader(key, field[key]);323    }324  }325  return this;326};327328/**329 * Get value for header `field`.330 *331 * @param {String} field332 * @return {String}333 * @api public334 */335336res.get = function(field){337  return this.getHeader(field);338};339340/**341 * Set or get response header `field` with optional `val`.342 *343 * @param {String} name344 * @param {String} val345 * @return {ServerResponse} for chaining346 * @api public347 */348349res.header = function(field, val){350  if (1 == arguments.length) return this.getHeader(field);351  this.setHeader(field, val);352  return this;353};354355/**356 * Clear cookie `name`.357 *358 * @param {String} name359 * @param {Object} options360 * @param {ServerResponse} for chaining361 * @api public362 */363364res.clearCookie = function(name, options){365  var opts = { expires: new Date(1), path: '/' };366  return this.cookie(name, '', options367    ? utils.merge(opts, options)368    : opts);369};370371/**372 * Set a signed cookie with the given `name` and `val`.373 * See `res.cookie()` for details.374 *375 * @param {String} name376 * @param {String|Object} val377 * @param {Object} options378 * @api public379 */380381res.signedCookie = function(name, val, options){382  var secret = this.req.secret;383  if (!secret) throw new Error('connect.cookieParser("secret") required for signed cookies');384  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);385  val = utils.sign(val, secret);386  return this.cookie(name, val, options);387};388389/**390 * Set cookie `name` to `val`, with the given `options`.391 *392 * Options:393 *394 *    - `maxAge`   max-age in milliseconds, converted to `expires`395 *    - `path`     defaults to "/"396 *397 * Examples:398 *399 *    // "Remember Me" for 15 minutes400 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });401 *402 *    // save as above403 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })404 *405 * @param {String} name406 * @param {String|Object} val407 * @param {Options} options408 * @api public409 */410411res.cookie = function(name, val, options){412  options = options || {};413  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);414  if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);415  if (undefined === options.path) options.path = '/';416  var cookie = utils.serializeCookie(name, val, options);417  this.header('Set-Cookie', cookie);418  return this;419};420421/**422 * Redirect to the given `url` with optional response `status`423 * defaulting to 302.424 *425 * The given `url` can also be the name of a mapped url, for426 * example by default express supports "back" which redirects427 * to the _Referrer_ or _Referer_ headers or "/".428 *429 * Examples:430 *431 *    res.redirect('/foo/bar');432 *    res.redirect('http://example.com');433 *    res.redirect(301, 'http://example.com');434 *435 * Mounting:436 *437 *   When an application is mounted, and `res.redirect()`438 *   is given a path that does _not_ lead with "/". For 439 *   example suppose a "blog" app is mounted at "/blog",440 *   the following redirect would result in "/blog/login":441 *442 *      res.redirect('login');443 *444 *   While the leading slash would result in a redirect to "/login":445 *446 *      res.redirect('/login');447 *448 * @param {String} url449 * @param {Number} code450 * @api public451 */452453res.redirect = function(url){454  var app = this.app455    , req = this.req456    , head = 'HEAD' == req.method457    , status = 302458    , body;459460  // allow status / url461  if (2 == arguments.length) {462    status = url;463    url = arguments[1];464  }465466  // setup redirect map467  var map = { back: req.header('Referrer', '/') };468469  // perform redirect470  url = map[url] || url;471472  // relative473  if (!~url.indexOf('://')) {474    var path = app.path();475476    // relative to path477    if (0 == url.indexOf('./') || 0 == url.indexOf('..')) {478      url = req.path + '/' + url;479    // relative to mount-point480    } else if ('/' != url[0]) {481      url = path + '/' + url;482    }483484    // Absolute485    var host = req.header('Host')486      , proto = req.header('X-Forwarded-Proto')487      , tls = 'https' == proto || req.secure;488489    url = 'http' + (tls ? 's' : '') + '://' + host + url;490  }491492  // Support text/{plain,html} by default493  if (req.accepts('html')) {494    body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';495    this.header('Content-Type', 'text/html');496  } else {497    body = statusCodes[status] + '. Redirecting to ' + url;498    this.header('Content-Type', 'text/plain');499  }500501  // Respond502  this.statusCode = status;503  this.header('Location', url);504  this.end(head ? null : body);505};506507/**508 * Render `view` with the given `options` and optional callback `fn`.509 * When a callback function is given a response will _not_ be made510 * automatically, otherwise a response of _200_ and _text/html_ is given.511 *512 * Options:513 *  514 *  - `status`    Response status code (`res.statusCode`)515 *  - `charset`   Set the charset (`res.charset`)516 *517 * Reserved locals:518 *519 *  - `cache`     boolean hinting to the engine it should cache520 *  - `filename`  filename of the view being rendered521 *522 * @param  {String} view523 * @param  {Object|Function} options or callback function524 * @param  {Function} fn525 * @api public526 */527528res.render = function(view, options, fn){529  var self = this530    , options = options || {}531    , req = this.req532    , app = req.app;533534  // support callback function as second arg535  if ('function' == typeof options) {536    fn = options, options = {};537  }538539  function render() {540    // merge res.locals541    options.locals = self.locals;542543    // default callback to respond544    fn = fn || function(err, str){545      if (err) return req.next(err);546      self.send(str);547    };548549    // render550    app.render(view, options, fn);551  }552553  // invoke view callbacks554  var callbacks = app.viewCallbacks555    , pending = callbacks.length556    , len = pending557    , done;558559  if (len) {560    for (var i = 0; i < len; ++i) {561      callbacks[i](req, self, function(err){562        if (done) return;563564        if (err) {565          req.next(err);566          done = true;567          return;568        }569570        --pending || render();571      });572    }573  } else {574    render();575  }576};