Skip to content
Myr

application.js

This file

Path

lib/application.js

538 lines · 12.0 KiB · JavaScript

Last changed by

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

History of this file

Take it

1/**2 * Module dependencies.3 */45var connect = require('connect')6  , Router = require('./router')7  , methods = require('methods')8  , middleware = require('./middleware')9  , debug = require('debug')('express:application')10  , locals = require('./utils').locals11  , compileTrust = require('./utils').compileTrust12  , View = require('./view')13  , utils = connect.utils14  , deprecate = require('./utils').deprecate15  , http = require('http');1617/**18 * Application prototype.19 */2021var app = exports = module.exports = {};2223/**24 * Initialize the server.25 *26 *   - setup default configuration27 *   - setup default middleware28 *   - setup route reflection methods29 *30 * @api private31 */3233app.init = function(){34  this.cache = {};35  this.settings = {};36  this.engines = {};37  this.defaultConfiguration();38};3940/**41 * Initialize application configuration.42 *43 * @api private44 */4546app.defaultConfiguration = function(){47  // default settings48  this.enable('x-powered-by');49  this.enable('etag');50  this.set('env', process.env.NODE_ENV || 'development');51  this.set('subdomain offset', 2);52  this.set('trust proxy', false);53  debug('booting in %s mode', this.get('env'));5455  // implicit middleware56  this.use(connect.query());57  this.use(middleware.init(this));5859  // inherit protos60  this.on('mount', function(parent){61    this.request.__proto__ = parent.request;62    this.response.__proto__ = parent.response;63    this.engines.__proto__ = parent.engines;64    this.settings.__proto__ = parent.settings;65  });6667  // router68  this._router = new Router(this);69  this.routes = this._router.map;70  this.__defineGetter__('router', function(){71    this._usedRouter = true;72    this._router.caseSensitive = this.enabled('case sensitive routing');73    this._router.strict = this.enabled('strict routing');74    return this._router.middleware;75  });7677  // setup locals78  this.locals = locals(this);7980  // default locals81  this.locals.settings = this.settings;8283  // default configuration84  this.set('view', View);85  this.set('views', process.cwd() + '/views');86  this.set('jsonp callback name', 'callback');8788  this.configure('development', function(){89    this.set('json spaces', 2);90  });9192  this.configure('production', function(){93    this.enable('view cache');94  });95};9697/**98 * Proxy `connect#use()` to apply settings to99 * mounted applications.100 *101 * @param {String|Function|Server} route102 * @param {Function|Server} fn103 * @return {app} for chaining104 * @api public105 */106107app.use = function(route, fn){108  var app;109110  // default route to '/'111  if ('string' != typeof route) fn = route, route = '/';112113  // express app114  if (fn.handle && fn.set) app = fn;115116  // restore .app property on req and res117  if (app) {118    app.route = route;119    fn = function(req, res, next) {120      var orig = req.app;121      app.handle(req, res, function(err){122        req.__proto__ = orig.request;123        res.__proto__ = orig.response;124        next(err);125      });126    };127  }128129  connect.proto.use.call(this, route, fn);130131  // mounted an app132  if (app) {133    app.parent = this;134    app.emit('mount', this);135  }136137  return this;138};139140/**141 * Register the given template engine callback `fn`142 * as `ext`.143 *144 * By default will `require()` the engine based on the145 * file extension. For example if you try to render146 * a "foo.jade" file Express will invoke the following internally:147 *148 *     app.engine('jade', require('jade').__express);149 *150 * For engines that do not provide `.__express` out of the box,151 * or if you wish to "map" a different extension to the template engine152 * you may use this method. For example mapping the EJS template engine to153 * ".html" files:154 *155 *     app.engine('html', require('ejs').renderFile);156 *157 * In this case EJS provides a `.renderFile()` method with158 * the same signature that Express expects: `(path, options, callback)`,159 * though note that it aliases this method as `ejs.__express` internally160 * so if you're using ".ejs" extensions you dont need to do anything.161 *162 * Some template engines do not follow this convention, the163 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)164 * library was created to map all of node's popular template165 * engines to follow this convention, thus allowing them to166 * work seamlessly within Express.167 *168 * @param {String} ext169 * @param {Function} fn170 * @return {app} for chaining171 * @api public172 */173174app.engine = function(ext, fn){175  if ('function' != typeof fn) throw new Error('callback function required');176  if ('.' != ext[0]) ext = '.' + ext;177  this.engines[ext] = fn;178  return this;179};180181/**182 * Map the given param placeholder `name`(s) to the given callback(s).183 *184 * Parameter mapping is used to provide pre-conditions to routes185 * which use normalized placeholders. For example a _:user_id_ parameter186 * could automatically load a user's information from the database without187 * any additional code,188 *189 * The callback uses the same signature as middleware, the only difference190 * being that the value of the placeholder is passed, in this case the _id_191 * of the user. Once the `next()` function is invoked, just like middleware192 * it will continue on to execute the route, or subsequent parameter functions.193 *194 *      app.param('user_id', function(req, res, next, id){195 *        User.find(id, function(err, user){196 *          if (err) {197 *            next(err);198 *          } else if (user) {199 *            req.user = user;200 *            next();201 *          } else {202 *            next(new Error('failed to load user'));203 *          }204 *        });205 *      });206 *207 * @param {String|Array} name208 * @param {Function} fn209 * @return {app} for chaining210 * @api public211 */212213app.param = function(name, fn){214  var self = this215    , fns = [].slice.call(arguments, 1);216217  // array218  if (Array.isArray(name)) {219    name.forEach(function(name){220      fns.forEach(function(fn){221        self.param(name, fn);222      });223    });224  // param logic225  } else if ('function' == typeof name) {226    this._router.param(name);227  // single228  } else {229    if (':' == name[0]) name = name.substr(1);230    fns.forEach(function(fn){231      self._router.param(name, fn);232    });233  }234235  return this;236};237238/**239 * Assign `setting` to `val`, or return `setting`'s value.240 *241 *    app.set('foo', 'bar');242 *    app.get('foo');243 *    // => "bar"244 *245 * Mounted servers inherit their parent server's settings.246 *247 * @param {String} setting248 * @param {*} [val]249 * @return {Server} for chaining250 * @api public251 */252253app.set = function(setting, val){254  if (1 == arguments.length) {255    return this.settings[setting];256  } else {257    this.settings[setting] = val;258259    if (setting === 'trust proxy') {260      debug('compile trust proxy %j', val);261      this.set('trust proxy fn', compileTrust(val));262    }263264    return this;265  }266};267268/**269 * Return the app's absolute pathname270 * based on the parent(s) that have271 * mounted it.272 *273 * For example if the application was274 * mounted as "/admin", which itself275 * was mounted as "/blog" then the276 * return value would be "/blog/admin".277 *278 * @return {String}279 * @api private280 */281282app.path = function(){283  return this.parent284    ? this.parent.path() + this.route285    : '';286};287288/**289 * Check if `setting` is enabled (truthy).290 *291 *    app.enabled('foo')292 *    // => false293 *294 *    app.enable('foo')295 *    app.enabled('foo')296 *    // => true297 *298 * @param {String} setting299 * @return {Boolean}300 * @api public301 */302303app.enabled = function(setting){304  return !!this.set(setting);305};306307/**308 * Check if `setting` is disabled.309 *310 *    app.disabled('foo')311 *    // => true312 *313 *    app.enable('foo')314 *    app.disabled('foo')315 *    // => false316 *317 * @param {String} setting318 * @return {Boolean}319 * @api public320 */321322app.disabled = function(setting){323  return !this.set(setting);324};325326/**327 * Enable `setting`.328 *329 * @param {String} setting330 * @return {app} for chaining331 * @api public332 */333334app.enable = function(setting){335  return this.set(setting, true);336};337338/**339 * Disable `setting`.340 *341 * @param {String} setting342 * @return {app} for chaining343 * @api public344 */345346app.disable = function(setting){347  return this.set(setting, false);348};349350/**351 * Configure callback for zero or more envs,352 * when no `env` is specified that callback will353 * be invoked for all environments. Any combination354 * can be used multiple times, in any order desired.355 *356 * Examples:357 *358 *    app.configure(function(){359 *      // executed for all envs360 *    });361 *362 *    app.configure('stage', function(){363 *      // executed staging env364 *    });365 *366 *    app.configure('stage', 'production', function(){367 *      // executed for stage and production368 *    });369 *370 * Note:371 *372 *  These callbacks are invoked immediately, and373 *  are effectively sugar for the following:374 *375 *     var env = process.env.NODE_ENV || 'development';376 *377 *      switch (env) {378 *        case 'development':379 *          ...380 *          break;381 *        case 'stage':382 *          ...383 *          break;384 *        case 'production':385 *          ...386 *          break;387 *      }388 *389 * @param {String} env...390 * @param {Function} fn391 * @return {app} for chaining392 * @api public393 */394395app.configure = function(env, fn){396  var envs = 'all'397    , args = [].slice.call(arguments);398  fn = args.pop();399  if (args.length) envs = args;400  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);401  return this;402};403404/**405 * Delegate `.VERB(...)` calls to `router.VERB(...)`.406 */407408methods.forEach(function(method){409  app[method] = function(path){410    if ('get' == method && 1 == arguments.length) return this.set(path);411412    // if no router attached yet, attach the router413    if (!this._usedRouter) this.use(this.router);414415    // setup route416    this._router[method].apply(this._router, arguments);417    return this;418  };419});420421/**422 * Special-cased "all" method, applying the given route `path`,423 * middleware, and callback to _every_ HTTP method.424 *425 * @param {String} path426 * @param {Function} ...427 * @return {app} for chaining428 * @api public429 */430431app.all = function(path){432  var args = arguments;433  methods.forEach(function(method){434    app[method].apply(this, args);435  }, this);436  return this;437};438439// del -> delete alias440441app.del = deprecate(app.delete, 'app.del: Use app.delete instead');442443/**444 * Render the given view `name` name with `options`445 * and a callback accepting an error and the446 * rendered template string.447 *448 * Example:449 *450 *    app.render('email', { name: 'Tobi' }, function(err, html){451 *      // ...452 *    })453 *454 * @param {String} name455 * @param {String|Function} options or fn456 * @param {Function} fn457 * @api public458 */459460app.render = function(name, options, fn){461  var opts = {}462    , cache = this.cache463    , engines = this.engines464    , view;465466  // support callback function as second arg467  if ('function' == typeof options) {468    fn = options, options = {};469  }470471  // merge app.locals472  utils.merge(opts, this.locals);473474  // merge options._locals475  if (options._locals) utils.merge(opts, options._locals);476477  // merge options478  utils.merge(opts, options);479480  // set .cache unless explicitly provided481  opts.cache = null == opts.cache482    ? this.enabled('view cache')483    : opts.cache;484485  // primed cache486  if (opts.cache) view = cache[name];487488  // view489  if (!view) {490    view = new (this.get('view'))(name, {491      defaultEngine: this.get('view engine'),492      root: this.get('views'),493      engines: engines494    });495496    if (!view.path) {497      var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');498      err.view = view;499      return fn(err);500    }501502    // prime the cache503    if (opts.cache) cache[name] = view;504  }505506  // render507  try {508    view.render(opts, fn);509  } catch (err) {510    fn(err);511  }512};513514/**515 * Listen for connections.516 *517 * A node `http.Server` is returned, with this518 * application (which is a `Function`) as its519 * callback. If you wish to create both an HTTP520 * and HTTPS server you may do so with the "http"521 * and "https" modules as shown here:522 *523 *    var http = require('http')524 *      , https = require('https')525 *      , express = require('express')526 *      , app = express();527 *528 *    http.createServer(app).listen(80);529 *    https.createServer({ ... }, app).listen(443);530 *531 * @return {http.Server}532 * @api public533 */534535app.listen = function(){536  var server = http.createServer(this);537  return server.listen.apply(server, arguments);538};