Skip to content
Myr

application.js

This file

Path

lib/application.js

591 lines · 13.2 KiB · JavaScript

Last changed by

Fix "trust proxy" setting to inherit when app is mountedDouglas Christopher Wilsonbefore adoptionb40e74d

History of this file

Take it

1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */89/**10 * Module dependencies.11 * @api private12 */1314var connect = require('connect')15  , Router = require('./router')16  , methods = require('methods')17  , middleware = require('./middleware')18  , debug = require('debug')('express:application')19  , locals = require('./utils').locals20  , compileETag = require('./utils').compileETag21  , compileTrust = require('./utils').compileTrust22  , View = require('./view')23  , http = require('http');24var deprecate = require('depd')('express');25var merge = require('utils-merge');2627/**28 * Application prototype.29 */3031var app = exports = module.exports = {};3233/**34 * Variable for trust proxy inheritance back-compat35 * @api private36 */3738var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';3940/**41 * Initialize the server.42 *43 *   - setup default configuration44 *   - setup default middleware45 *   - setup route reflection methods46 *47 * @api private48 */4950app.init = function(){51  this.cache = {};52  this.settings = {};53  this.engines = {};54  this.defaultConfiguration();55};5657/**58 * Initialize application configuration.59 *60 * @api private61 */6263app.defaultConfiguration = function(){64  // default settings65  this.enable('x-powered-by');66  this.set('etag', 'weak');67  var env = process.env.NODE_ENV || 'development';68  this.set('env', env);69  this.set('subdomain offset', 2);70  this.set('trust proxy', false);7172  // trust proxy inherit back-compat73  Object.defineProperty(this.settings, trustProxyDefaultSymbol, {74    configurable: true,75    value: true76  });7778  debug('booting in %s mode', env);7980  // implicit middleware81  this.use(connect.query());82  this.use(middleware.init(this));8384  this.on('mount', function onmount(parent) {85    // inherit trust proxy86    if (this.settings[trustProxyDefaultSymbol] === true87      && typeof parent.settings['trust proxy fn'] === 'function') {88      delete this.settings['trust proxy'];89      delete this.settings['trust proxy fn'];90    }9192    // inherit protos93    this.request.__proto__ = parent.request;94    this.response.__proto__ = parent.response;95    this.engines.__proto__ = parent.engines;96    this.settings.__proto__ = parent.settings;97  });9899  // router100  this._router = new Router(this);101  this.routes = this._router.map;102  this.__defineGetter__('router', function(){103    this._usedRouter = true;104    this._router.caseSensitive = this.enabled('case sensitive routing');105    this._router.strict = this.enabled('strict routing');106    return this._router.middleware;107  });108109  // setup locals110  this.locals = locals(this);111112  // default locals113  this.locals.settings = this.settings;114115  // default configuration116  this.set('view', View);117  this.set('views', process.cwd() + '/views');118  this.set('jsonp callback name', 'callback');119120  if (env === 'development') {121    this.set('json spaces', 2);122  }123124  if (env === 'production') {125    this.enable('view cache');126  }127};128129/**130 * Proxy `connect#use()` to apply settings to131 * mounted applications.132 *133 * @param {String|Function|Server} route134 * @param {Function|Server} fn135 * @return {app} for chaining136 * @api public137 */138139app.use = function(route, fn){140  var app;141142  // default route to '/'143  if ('string' != typeof route) fn = route, route = '/';144145  // express app146  if (fn.handle && fn.set) app = fn;147148  // restore .app property on req and res149  if (app) {150    app.route = route;151    fn = function(req, res, next) {152      var orig = req.app;153      app.handle(req, res, function(err){154        req.__proto__ = orig.request;155        res.__proto__ = orig.response;156        next(err);157      });158    };159  }160161  connect.proto.use.call(this, route, fn);162163  // mounted an app164  if (app) {165    app.parent = this;166    app.emit('mount', this);167  }168169  return this;170};171172/**173 * Register the given template engine callback `fn`174 * as `ext`.175 *176 * By default will `require()` the engine based on the177 * file extension. For example if you try to render178 * a "foo.jade" file Express will invoke the following internally:179 *180 *     app.engine('jade', require('jade').__express);181 *182 * For engines that do not provide `.__express` out of the box,183 * or if you wish to "map" a different extension to the template engine184 * you may use this method. For example mapping the EJS template engine to185 * ".html" files:186 *187 *     app.engine('html', require('ejs').renderFile);188 *189 * In this case EJS provides a `.renderFile()` method with190 * the same signature that Express expects: `(path, options, callback)`,191 * though note that it aliases this method as `ejs.__express` internally192 * so if you're using ".ejs" extensions you dont need to do anything.193 *194 * Some template engines do not follow this convention, the195 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)196 * library was created to map all of node's popular template197 * engines to follow this convention, thus allowing them to198 * work seamlessly within Express.199 *200 * @param {String} ext201 * @param {Function} fn202 * @return {app} for chaining203 * @api public204 */205206app.engine = function(ext, fn){207  if ('function' != typeof fn) throw new Error('callback function required');208  if ('.' != ext[0]) ext = '.' + ext;209  this.engines[ext] = fn;210  return this;211};212213/**214 * Map the given param placeholder `name`(s) to the given callback(s).215 *216 * Parameter mapping is used to provide pre-conditions to routes217 * which use normalized placeholders. For example a _:user_id_ parameter218 * could automatically load a user's information from the database without219 * any additional code,220 *221 * The callback uses the same signature as middleware, the only difference222 * being that the value of the placeholder is passed, in this case the _id_223 * of the user. Once the `next()` function is invoked, just like middleware224 * it will continue on to execute the route, or subsequent parameter functions.225 *226 *      app.param('user_id', function(req, res, next, id){227 *        User.find(id, function(err, user){228 *          if (err) {229 *            next(err);230 *          } else if (user) {231 *            req.user = user;232 *            next();233 *          } else {234 *            next(new Error('failed to load user'));235 *          }236 *        });237 *      });238 *239 * @param {String|Array} name240 * @param {Function} fn241 * @return {app} for chaining242 * @api public243 */244245app.param = function(name, fn){246  var self = this247    , fns = [].slice.call(arguments, 1);248249  // array250  if (Array.isArray(name)) {251    name.forEach(function(name){252      fns.forEach(function(fn){253        self.param(name, fn);254      });255    });256  // param logic257  } else if ('function' == typeof name) {258    this._router.param(name);259  // single260  } else {261    if (':' == name[0]) name = name.substr(1);262    fns.forEach(function(fn){263      self._router.param(name, fn);264    });265  }266267  return this;268};269270/**271 * Assign `setting` to `val`, or return `setting`'s value.272 *273 *    app.set('foo', 'bar');274 *    app.get('foo');275 *    // => "bar"276 *277 * Mounted servers inherit their parent server's settings.278 *279 * @param {String} setting280 * @param {*} [val]281 * @return {Server} for chaining282 * @api public283 */284285app.set = function(setting, val){286  if (arguments.length === 1) {287    // app.get(setting)288    return this.settings[setting];289  }290291  // set value292  this.settings[setting] = val;293294  // trigger matched settings295  switch (setting) {296    case 'etag':297      debug('compile etag %s', val);298      this.set('etag fn', compileETag(val));299      break;300    case 'trust proxy':301      debug('compile trust proxy %s', val);302      this.set('trust proxy fn', compileTrust(val));303304      // trust proxy inherit back-compat305      Object.defineProperty(this.settings, trustProxyDefaultSymbol, {306        configurable: true,307        value: false308      });309310      break;311  }312313  return this;314};315316/**317 * Return the app's absolute pathname318 * based on the parent(s) that have319 * mounted it.320 *321 * For example if the application was322 * mounted as "/admin", which itself323 * was mounted as "/blog" then the324 * return value would be "/blog/admin".325 *326 * @return {String}327 * @api private328 */329330app.path = function(){331  return this.parent332    ? this.parent.path() + this.route333    : '';334};335336/**337 * Check if `setting` is enabled (truthy).338 *339 *    app.enabled('foo')340 *    // => false341 *342 *    app.enable('foo')343 *    app.enabled('foo')344 *    // => true345 *346 * @param {String} setting347 * @return {Boolean}348 * @api public349 */350351app.enabled = function(setting){352  return !!this.set(setting);353};354355/**356 * Check if `setting` is disabled.357 *358 *    app.disabled('foo')359 *    // => true360 *361 *    app.enable('foo')362 *    app.disabled('foo')363 *    // => false364 *365 * @param {String} setting366 * @return {Boolean}367 * @api public368 */369370app.disabled = function(setting){371  return !this.set(setting);372};373374/**375 * Enable `setting`.376 *377 * @param {String} setting378 * @return {app} for chaining379 * @api public380 */381382app.enable = function(setting){383  return this.set(setting, true);384};385386/**387 * Disable `setting`.388 *389 * @param {String} setting390 * @return {app} for chaining391 * @api public392 */393394app.disable = function(setting){395  return this.set(setting, false);396};397398/**399 * Configure callback for zero or more envs,400 * when no `env` is specified that callback will401 * be invoked for all environments. Any combination402 * can be used multiple times, in any order desired.403 *404 * Examples:405 *406 *    app.configure(function(){407 *      // executed for all envs408 *    });409 *410 *    app.configure('stage', function(){411 *      // executed staging env412 *    });413 *414 *    app.configure('stage', 'production', function(){415 *      // executed for stage and production416 *    });417 *418 * Note:419 *420 *  These callbacks are invoked immediately, and421 *  are effectively sugar for the following:422 *423 *     var env = process.env.NODE_ENV || 'development';424 *425 *      switch (env) {426 *        case 'development':427 *          ...428 *          break;429 *        case 'stage':430 *          ...431 *          break;432 *        case 'production':433 *          ...434 *          break;435 *      }436 *437 * @param {String} env...438 * @param {Function} fn439 * @return {app} for chaining440 * @api public441 */442443app.configure = function(env, fn){444  var envs = 'all'445    , args = [].slice.call(arguments);446  fn = args.pop();447  if (args.length) envs = args;448  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);449  return this;450};451452app.configure = deprecate.function(app.configure,453  'app.configure: Check app.get(\'env\') in an if statement');454455/**456 * Delegate `.VERB(...)` calls to `router.VERB(...)`.457 */458459methods.forEach(function(method){460  app[method] = function(path){461    if ('get' == method && 1 == arguments.length) return this.set(path);462463    // if no router attached yet, attach the router464    if (!this._usedRouter) this.use(this.router);465466    // setup route467    this._router[method].apply(this._router, arguments);468    return this;469  };470});471472/**473 * Special-cased "all" method, applying the given route `path`,474 * middleware, and callback to _every_ HTTP method.475 *476 * @param {String} path477 * @param {Function} ...478 * @return {app} for chaining479 * @api public480 */481482app.all = function(path){483  var args = arguments;484  methods.forEach(function(method){485    app[method].apply(this, args);486  }, this);487  return this;488};489490// del -> delete alias491492app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');493494/**495 * Render the given view `name` name with `options`496 * and a callback accepting an error and the497 * rendered template string.498 *499 * Example:500 *501 *    app.render('email', { name: 'Tobi' }, function(err, html){502 *      // ...503 *    })504 *505 * @param {String} name506 * @param {String|Function} options or fn507 * @param {Function} fn508 * @api public509 */510511app.render = function(name, options, fn){512  var opts = {}513    , cache = this.cache514    , engines = this.engines515    , view;516517  // support callback function as second arg518  if ('function' == typeof options) {519    fn = options, options = {};520  }521522  // merge app.locals523  merge(opts, this.locals);524525  // merge options._locals526  if (options._locals) {527    merge(opts, options._locals);528  }529530  // merge options531  merge(opts, options);532533  // set .cache unless explicitly provided534  opts.cache = null == opts.cache535    ? this.enabled('view cache')536    : opts.cache;537538  // primed cache539  if (opts.cache) view = cache[name];540541  // view542  if (!view) {543    view = new (this.get('view'))(name, {544      defaultEngine: this.get('view engine'),545      root: this.get('views'),546      engines: engines547    });548549    if (!view.path) {550      var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');551      err.view = view;552      return fn(err);553    }554555    // prime the cache556    if (opts.cache) cache[name] = view;557  }558559  // render560  try {561    view.render(opts, fn);562  } catch (err) {563    fn(err);564  }565};566567/**568 * Listen for connections.569 *570 * A node `http.Server` is returned, with this571 * application (which is a `Function`) as its572 * callback. If you wish to create both an HTTP573 * and HTTPS server you may do so with the "http"574 * and "https" modules as shown here:575 *576 *    var http = require('http')577 *      , https = require('https')578 *      , express = require('express')579 *      , app = express();580 *581 *    http.createServer(app).listen(80);582 *    https.createServer({ ... }, app).listen(443);583 *584 * @return {http.Server}585 * @api public586 */587588app.listen = function(){589  var server = http.createServer(this);590  return server.listen.apply(server, arguments);591};