application.js
This file
Path
lib/application.js
558 lines · 12.1 KiB · JavaScript
Last changed by
Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
History of this fileTake it
1/**2 * Module dependencies.3 */45var finalhandler = require('finalhandler');6var flatten = require('./utils').flatten;7var mixin = require('utils-merge');8var Router = require('./router');9var methods = require('methods');10var middleware = require('./middleware/init');11var query = require('./middleware/query');12var debug = require('debug')('express:application');13var View = require('./view');14var http = require('http');15var compileETag = require('./utils').compileETag;16var compileQueryParser = require('./utils').compileQueryParser;17var compileTrust = require('./utils').compileTrust;18var deprecate = require('depd')('express');19var resolve = require('path').resolve;20var slice = Array.prototype.slice;2122/**23 * Application prototype.24 */2526var app = exports = module.exports = {};2728/**29 * Initialize the server.30 *31 * - setup default configuration32 * - setup default middleware33 * - setup route reflection methods34 *35 * @api private36 */3738app.init = function(){39 this.cache = {};40 this.settings = {};41 this.engines = {};42 this.defaultConfiguration();43};4445/**46 * Initialize application configuration.47 *48 * @api private49 */5051app.defaultConfiguration = function(){52 // default settings53 this.enable('x-powered-by');54 this.set('etag', 'weak');55 var env = process.env.NODE_ENV || 'development';56 this.set('env', env);57 this.set('query parser', 'extended');58 this.set('subdomain offset', 2);59 this.set('trust proxy', false);6061 debug('booting in %s mode', env);6263 // inherit protos64 this.on('mount', function(parent){65 this.request.__proto__ = parent.request;66 this.response.__proto__ = parent.response;67 this.engines.__proto__ = parent.engines;68 this.settings.__proto__ = parent.settings;69 });7071 // setup locals72 this.locals = Object.create(null);7374 // top-most app is mounted at /75 this.mountpath = '/';7677 // default locals78 this.locals.settings = this.settings;7980 // default configuration81 this.set('view', View);82 this.set('views', resolve('views'));83 this.set('jsonp callback name', 'callback');8485 if (env === 'production') {86 this.enable('view cache');87 }8889 Object.defineProperty(this, 'router', {90 get: function() {91 throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');92 }93 });94};9596/**97 * lazily adds the base router if it has not yet been added.98 *99 * We cannot add the base router in the defaultConfiguration because100 * it reads app settings which might be set after that has run.101 *102 * @api private103 */104app.lazyrouter = function() {105 if (!this._router) {106 this._router = new Router({107 caseSensitive: this.enabled('case sensitive routing'),108 strict: this.enabled('strict routing')109 });110111 this._router.use(query(this.get('query parser fn')));112 this._router.use(middleware.init(this));113 }114};115116/**117 * Dispatch a req, res pair into the application. Starts pipeline processing.118 *119 * If no _done_ callback is provided, then default error handlers will respond120 * in the event of an error bubbling through the stack.121 *122 * @api private123 */124125app.handle = function(req, res, done) {126 var router = this._router;127128 // final handler129 done = done || finalhandler(req, res, {130 env: this.get('env'),131 onerror: logerror.bind(this)132 });133134 // no routes135 if (!router) {136 debug('no routes defined on app');137 done();138 return;139 }140141 router.handle(req, res, done);142};143144/**145 * Proxy `Router#use()` to add middleware to the app router.146 * See Router#use() documentation for details.147 *148 * If the _fn_ parameter is an express app, then it will be149 * mounted at the _route_ specified.150 *151 * @api public152 */153154app.use = function use(fn) {155 var offset = 0;156 var path = '/';157 var self = this;158159 // default path to '/'160 if (typeof fn !== 'function') {161 offset = 1;162 path = fn;163 }164165 var fns = flatten(slice.call(arguments, offset));166167 if (fns.length === 0) {168 throw new TypeError('app.use() requires middleware functions');169 }170171 // setup router172 this.lazyrouter();173 var router = this._router;174175 fns.forEach(function (fn) {176 // non-express app177 if (!fn || !fn.handle || !fn.set) {178 return router.use(path, fn);179 }180181 debug('.use app under %s', path);182 fn.mountpath = path;183 fn.parent = self;184185 // restore .app property on req and res186 router.use(path, function mounted_app(req, res, next) {187 var orig = req.app;188 fn.handle(req, res, function (err) {189 req.__proto__ = orig.request;190 res.__proto__ = orig.response;191 next(err);192 });193 });194195 // mounted an app196 fn.emit('mount', self);197 });198199 return this;200};201202/**203 * Proxy to the app `Router#route()`204 * Returns a new `Route` instance for the _path_.205 *206 * Routes are isolated middleware stacks for specific paths.207 * See the Route api docs for details.208 *209 * @api public210 */211212app.route = function(path){213 this.lazyrouter();214 return this._router.route(path);215};216217/**218 * Register the given template engine callback `fn`219 * as `ext`.220 *221 * By default will `require()` the engine based on the222 * file extension. For example if you try to render223 * a "foo.jade" file Express will invoke the following internally:224 *225 * app.engine('jade', require('jade').__express);226 *227 * For engines that do not provide `.__express` out of the box,228 * or if you wish to "map" a different extension to the template engine229 * you may use this method. For example mapping the EJS template engine to230 * ".html" files:231 *232 * app.engine('html', require('ejs').renderFile);233 *234 * In this case EJS provides a `.renderFile()` method with235 * the same signature that Express expects: `(path, options, callback)`,236 * though note that it aliases this method as `ejs.__express` internally237 * so if you're using ".ejs" extensions you dont need to do anything.238 *239 * Some template engines do not follow this convention, the240 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)241 * library was created to map all of node's popular template242 * engines to follow this convention, thus allowing them to243 * work seamlessly within Express.244 *245 * @param {String} ext246 * @param {Function} fn247 * @return {app} for chaining248 * @api public249 */250251app.engine = function(ext, fn){252 if ('function' != typeof fn) throw new Error('callback function required');253 if ('.' != ext[0]) ext = '.' + ext;254 this.engines[ext] = fn;255 return this;256};257258/**259 * Proxy to `Router#param()` with one added api feature. The _name_ parameter260 * can be an array of names.261 *262 * See the Router#param() docs for more details.263 *264 * @param {String|Array} name265 * @param {Function} fn266 * @return {app} for chaining267 * @api public268 */269270app.param = function(name, fn){271 var self = this;272 self.lazyrouter();273274 if (Array.isArray(name)) {275 name.forEach(function(key) {276 self.param(key, fn);277 });278 return this;279 }280281 self._router.param(name, fn);282 return this;283};284285/**286 * Assign `setting` to `val`, or return `setting`'s value.287 *288 * app.set('foo', 'bar');289 * app.get('foo');290 * // => "bar"291 *292 * Mounted servers inherit their parent server's settings.293 *294 * @param {String} setting295 * @param {*} [val]296 * @return {Server} for chaining297 * @api public298 */299300app.set = function(setting, val){301 if (arguments.length === 1) {302 // app.get(setting)303 return this.settings[setting];304 }305306 // set value307 this.settings[setting] = val;308309 // trigger matched settings310 switch (setting) {311 case 'etag':312 debug('compile etag %s', val);313 this.set('etag fn', compileETag(val));314 break;315 case 'query parser':316 debug('compile query parser %s', val);317 this.set('query parser fn', compileQueryParser(val));318 break;319 case 'trust proxy':320 debug('compile trust proxy %s', val);321 this.set('trust proxy fn', compileTrust(val));322 break;323 }324325 return this;326};327328/**329 * Return the app's absolute pathname330 * based on the parent(s) that have331 * mounted it.332 *333 * For example if the application was334 * mounted as "/admin", which itself335 * was mounted as "/blog" then the336 * return value would be "/blog/admin".337 *338 * @return {String}339 * @api private340 */341342app.path = function(){343 return this.parent344 ? this.parent.path() + this.mountpath345 : '';346};347348/**349 * Check if `setting` is enabled (truthy).350 *351 * app.enabled('foo')352 * // => false353 *354 * app.enable('foo')355 * app.enabled('foo')356 * // => true357 *358 * @param {String} setting359 * @return {Boolean}360 * @api public361 */362363app.enabled = function(setting){364 return !!this.set(setting);365};366367/**368 * Check if `setting` is disabled.369 *370 * app.disabled('foo')371 * // => true372 *373 * app.enable('foo')374 * app.disabled('foo')375 * // => false376 *377 * @param {String} setting378 * @return {Boolean}379 * @api public380 */381382app.disabled = function(setting){383 return !this.set(setting);384};385386/**387 * Enable `setting`.388 *389 * @param {String} setting390 * @return {app} for chaining391 * @api public392 */393394app.enable = function(setting){395 return this.set(setting, true);396};397398/**399 * Disable `setting`.400 *401 * @param {String} setting402 * @return {app} for chaining403 * @api public404 */405406app.disable = function(setting){407 return this.set(setting, false);408};409410/**411 * Delegate `.VERB(...)` calls to `router.VERB(...)`.412 */413414methods.forEach(function(method){415 app[method] = function(path){416 if ('get' == method && 1 == arguments.length) return this.set(path);417418 this.lazyrouter();419420 var route = this._router.route(path);421 route[method].apply(route, slice.call(arguments, 1));422 return this;423 };424});425426/**427 * Special-cased "all" method, applying the given route `path`,428 * middleware, and callback to _every_ HTTP method.429 *430 * @param {String} path431 * @param {Function} ...432 * @return {app} for chaining433 * @api public434 */435436app.all = function(path){437 this.lazyrouter();438439 var route = this._router.route(path);440 var args = slice.call(arguments, 1);441 methods.forEach(function(method){442 route[method].apply(route, args);443 });444445 return this;446};447448// del -> delete alias449450app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');451452/**453 * Render the given view `name` name with `options`454 * and a callback accepting an error and the455 * rendered template string.456 *457 * Example:458 *459 * app.render('email', { name: 'Tobi' }, function(err, html){460 * // ...461 * })462 *463 * @param {String} name464 * @param {String|Function} options or fn465 * @param {Function} fn466 * @api public467 */468469app.render = function(name, options, fn){470 var opts = {};471 var cache = this.cache;472 var engines = this.engines;473 var view;474475 // support callback function as second arg476 if ('function' == typeof options) {477 fn = options, options = {};478 }479480 // merge app.locals481 mixin(opts, this.locals);482483 // merge options._locals484 if (options._locals) mixin(opts, options._locals);485486 // merge options487 mixin(opts, options);488489 // set .cache unless explicitly provided490 opts.cache = null == opts.cache491 ? this.enabled('view cache')492 : opts.cache;493494 // primed cache495 if (opts.cache) view = cache[name];496497 // view498 if (!view) {499 view = new (this.get('view'))(name, {500 defaultEngine: this.get('view engine'),501 root: this.get('views'),502 engines: engines503 });504505 if (!view.path) {506 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');507 err.view = view;508 return fn(err);509 }510511 // prime the cache512 if (opts.cache) cache[name] = view;513 }514515 // render516 try {517 view.render(opts, fn);518 } catch (err) {519 fn(err);520 }521};522523/**524 * Listen for connections.525 *526 * A node `http.Server` is returned, with this527 * application (which is a `Function`) as its528 * callback. If you wish to create both an HTTP529 * and HTTPS server you may do so with the "http"530 * and "https" modules as shown here:531 *532 * var http = require('http')533 * , https = require('https')534 * , express = require('express')535 * , app = express();536 *537 * http.createServer(app).listen(80);538 * https.createServer({ ... }, app).listen(443);539 *540 * @return {http.Server}541 * @api public542 */543544app.listen = function(){545 var server = http.createServer(this);546 return server.listen.apply(server, arguments);547};548549/**550* Log error using console.error.551*552* @param {Error} err553* @api public554*/555556function logerror(err){557 if (this.get('env') !== 'test') console.error(err.stack || err.toString());558}