application.js
This file
Path
lib/application.js
629 lines · 13.4 KiB · JavaScript
Last changed by
Merge tag '4.13.1'Douglas Christopher Wilsonbefore adoptionb309b87
History of this fileTake 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'use strict';1011/**12 * Module dependencies.13 * @private14 */1516var finalhandler = require('finalhandler');17var Router = require('./router');18var methods = require('methods');19var debug = require('debug')('express:application');20var View = require('./view');21var http = require('http');22var compileETag = require('./utils').compileETag;23var compileQueryParser = require('./utils').compileQueryParser;24var compileTrust = require('./utils').compileTrust;25var flatten = require('array-flatten');26var merge = require('utils-merge');27var resolve = require('path').resolve;28var slice = Array.prototype.slice;2930/**31 * Application prototype.32 */3334var app = exports = module.exports = {};3536/**37 * Variable for trust proxy inheritance back-compat38 * @private39 */4041var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';4243/**44 * Initialize the server.45 *46 * - setup default configuration47 * - setup default middleware48 * - setup route reflection methods49 *50 * @private51 */5253app.init = function init() {54 var router = null;5556 this.cache = {};57 this.engines = {};58 this.settings = {};5960 this.defaultConfiguration();6162 // Setup getting to lazily add base router63 Object.defineProperty(this, 'router', {64 configurable: true,65 enumerable: true,66 get: function getrouter() {67 if (router === null) {68 router = new Router({69 caseSensitive: this.enabled('case sensitive routing'),70 strict: this.enabled('strict routing')71 });72 }7374 return router;75 }76 });77};7879/**80 * Initialize application configuration.81 * @private82 */8384app.defaultConfiguration = function defaultConfiguration() {85 var env = process.env.NODE_ENV || 'development';8687 // default settings88 this.enable('x-powered-by');89 this.set('etag', 'weak');90 this.set('env', env);91 this.set('query parser', 'extended');92 this.set('subdomain offset', 2);93 this.set('trust proxy', false);9495 // trust proxy inherit back-compat96 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {97 configurable: true,98 value: true99 });100101 debug('booting in %s mode', env);102103 this.on('mount', function onmount(parent) {104 // inherit trust proxy105 if (this.settings[trustProxyDefaultSymbol] === true106 && typeof parent.settings['trust proxy fn'] === 'function') {107 delete this.settings['trust proxy'];108 delete this.settings['trust proxy fn'];109 }110111 // inherit protos112 this.request.__proto__ = parent.request;113 this.response.__proto__ = parent.response;114 this.engines.__proto__ = parent.engines;115 this.settings.__proto__ = parent.settings;116 });117118 // setup locals119 this.locals = Object.create(null);120121 // top-most app is mounted at /122 this.mountpath = '/';123124 // default locals125 this.locals.settings = this.settings;126127 // default configuration128 this.set('view', View);129 this.set('views', resolve('views'));130 this.set('jsonp callback name', 'callback');131132 if (env === 'production') {133 this.enable('view cache');134 }135};136137/**138 * Dispatch a req, res pair into the application. Starts pipeline processing.139 *140 * If no callback is provided, then default error handlers will respond141 * in the event of an error bubbling through the stack.142 *143 * @private144 */145146app.handle = function handle(req, res, callback) {147 // final handler148 var done = callback || finalhandler(req, res, {149 env: this.get('env'),150 onerror: logerror.bind(this)151 });152153 // set powered by header154 if (this.enabled('x-powered-by')) {155 res.setHeader('X-Powered-By', 'Express');156 }157158 // set circular references159 req.res = res;160 res.req = req;161162 // alter the prototypes163 req.__proto__ = this.request;164 res.__proto__ = this.response;165166 // setup locals167 if (!res.locals) {168 res.locals = Object.create(null);169 }170171 this.router.handle(req, res, done);172};173174/**175 * Proxy `Router#use()` to add middleware to the app router.176 * See Router#use() documentation for details.177 *178 * If the _fn_ parameter is an express app, then it will be179 * mounted at the _route_ specified.180 *181 * @public182 */183184app.use = function use(fn) {185 var offset = 0;186 var path = '/';187188 // default path to '/'189 // disambiguate app.use([fn])190 if (typeof fn !== 'function') {191 var arg = fn;192193 while (Array.isArray(arg) && arg.length !== 0) {194 arg = arg[0];195 }196197 // first arg is the path198 if (typeof arg !== 'function') {199 offset = 1;200 path = fn;201 }202 }203204 var fns = flatten(slice.call(arguments, offset));205206 if (fns.length === 0) {207 throw new TypeError('app.use() requires middleware functions');208 }209210 // get router211 var router = this.router;212213 fns.forEach(function (fn) {214 // non-express app215 if (!fn || !fn.handle || !fn.set) {216 return router.use(path, fn);217 }218219 debug('.use app under %s', path);220 fn.mountpath = path;221 fn.parent = this;222223 // restore .app property on req and res224 router.use(path, function mounted_app(req, res, next) {225 var orig = req.app;226 fn.handle(req, res, function (err) {227 req.__proto__ = orig.request;228 res.__proto__ = orig.response;229 next(err);230 });231 });232233 // mounted an app234 fn.emit('mount', this);235 }, this);236237 return this;238};239240/**241 * Proxy to the app `Router#route()`242 * Returns a new `Route` instance for the _path_.243 *244 * Routes are isolated middleware stacks for specific paths.245 * See the Route api docs for details.246 *247 * @public248 */249250app.route = function route(path) {251 return this.router.route(path);252};253254/**255 * Register the given template engine callback `fn`256 * as `ext`.257 *258 * By default will `require()` the engine based on the259 * file extension. For example if you try to render260 * a "foo.jade" file Express will invoke the following internally:261 *262 * app.engine('jade', require('jade').__express);263 *264 * For engines that do not provide `.__express` out of the box,265 * or if you wish to "map" a different extension to the template engine266 * you may use this method. For example mapping the EJS template engine to267 * ".html" files:268 *269 * app.engine('html', require('ejs').renderFile);270 *271 * In this case EJS provides a `.renderFile()` method with272 * the same signature that Express expects: `(path, options, callback)`,273 * though note that it aliases this method as `ejs.__express` internally274 * so if you're using ".ejs" extensions you dont need to do anything.275 *276 * Some template engines do not follow this convention, the277 * [Consolidate.js](https://github.com/tj/consolidate.js)278 * library was created to map all of node's popular template279 * engines to follow this convention, thus allowing them to280 * work seamlessly within Express.281 *282 * @param {String} ext283 * @param {Function} fn284 * @return {app} for chaining285 * @public286 */287288app.engine = function engine(ext, fn) {289 if (typeof fn !== 'function') {290 throw new Error('callback function required');291 }292293 // get file extension294 var extension = ext[0] !== '.'295 ? '.' + ext296 : ext;297298 // store engine299 this.engines[extension] = fn;300301 return this;302};303304/**305 * Proxy to `Router#param()` with one added api feature. The _name_ parameter306 * can be an array of names.307 *308 * See the Router#param() docs for more details.309 *310 * @param {String|Array} name311 * @param {Function} fn312 * @return {app} for chaining313 * @public314 */315316app.param = function param(name, fn) {317 if (Array.isArray(name)) {318 for (var i = 0; i < name.length; i++) {319 this.param(name[i], fn);320 }321322 return this;323 }324325 this.router.param(name, fn);326327 return this;328};329330/**331 * Assign `setting` to `val`, or return `setting`'s value.332 *333 * app.set('foo', 'bar');334 * app.get('foo');335 * // => "bar"336 *337 * Mounted servers inherit their parent server's settings.338 *339 * @param {String} setting340 * @param {*} [val]341 * @return {Server} for chaining342 * @public343 */344345app.set = function set(setting, val) {346 if (arguments.length === 1) {347 // app.get(setting)348 return this.settings[setting];349 }350351 debug('set "%s" to %o', setting, val);352353 // set value354 this.settings[setting] = val;355356 // trigger matched settings357 switch (setting) {358 case 'etag':359 this.set('etag fn', compileETag(val));360 break;361 case 'query parser':362 this.set('query parser fn', compileQueryParser(val));363 break;364 case 'trust proxy':365 this.set('trust proxy fn', compileTrust(val));366367 // trust proxy inherit back-compat368 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {369 configurable: true,370 value: false371 });372373 break;374 }375376 return this;377};378379/**380 * Return the app's absolute pathname381 * based on the parent(s) that have382 * mounted it.383 *384 * For example if the application was385 * mounted as "/admin", which itself386 * was mounted as "/blog" then the387 * return value would be "/blog/admin".388 *389 * @return {String}390 * @private391 */392393app.path = function path() {394 return this.parent395 ? this.parent.path() + this.mountpath396 : '';397};398399/**400 * Check if `setting` is enabled (truthy).401 *402 * app.enabled('foo')403 * // => false404 *405 * app.enable('foo')406 * app.enabled('foo')407 * // => true408 *409 * @param {String} setting410 * @return {Boolean}411 * @public412 */413414app.enabled = function enabled(setting) {415 return Boolean(this.set(setting));416};417418/**419 * Check if `setting` is disabled.420 *421 * app.disabled('foo')422 * // => true423 *424 * app.enable('foo')425 * app.disabled('foo')426 * // => false427 *428 * @param {String} setting429 * @return {Boolean}430 * @public431 */432433app.disabled = function disabled(setting) {434 return !this.set(setting);435};436437/**438 * Enable `setting`.439 *440 * @param {String} setting441 * @return {app} for chaining442 * @public443 */444445app.enable = function enable(setting) {446 return this.set(setting, true);447};448449/**450 * Disable `setting`.451 *452 * @param {String} setting453 * @return {app} for chaining454 * @public455 */456457app.disable = function disable(setting) {458 return this.set(setting, false);459};460461/**462 * Delegate `.VERB(...)` calls to `router.VERB(...)`.463 */464465methods.forEach(function(method){466 app[method] = function(path){467 if (method === 'get' && arguments.length === 1) {468 // app.get(setting)469 return this.set(path);470 }471472 var route = this.route(path);473 route[method].apply(route, slice.call(arguments, 1));474 return this;475 };476});477478/**479 * Special-cased "all" method, applying the given route `path`,480 * middleware, and callback to _every_ HTTP method.481 *482 * @param {String} path483 * @param {Function} ...484 * @return {app} for chaining485 * @public486 */487488app.all = function all(path) {489 var route = this.route(path);490 var args = slice.call(arguments, 1);491492 for (var i = 0; i < methods.length; i++) {493 route[methods[i]].apply(route, args);494 }495496 return this;497};498499/**500 * Render the given view `name` name with `options`501 * and a callback accepting an error and the502 * rendered template string.503 *504 * Example:505 *506 * app.render('email', { name: 'Tobi' }, function(err, html){507 * // ...508 * })509 *510 * @param {String} name511 * @param {String|Function} options or fn512 * @param {Function} callback513 * @public514 */515516app.render = function render(name, options, callback) {517 var cache = this.cache;518 var done = callback;519 var engines = this.engines;520 var opts = options;521 var renderOptions = {};522 var view;523524 // support callback function as second arg525 if (typeof options === 'function') {526 done = options;527 opts = {};528 }529530 // merge app.locals531 merge(renderOptions, this.locals);532533 // merge options._locals534 if (opts._locals) {535 merge(renderOptions, opts._locals);536 }537538 // merge options539 merge(renderOptions, opts);540541 // set .cache unless explicitly provided542 if (renderOptions.cache == null) {543 renderOptions.cache = this.enabled('view cache');544 }545546 // primed cache547 if (renderOptions.cache) {548 view = cache[name];549 }550551 // view552 if (!view) {553 var View = this.get('view');554555 view = new View(name, {556 defaultEngine: this.get('view engine'),557 root: this.get('views'),558 engines: engines559 });560561 if (!view.path) {562 var dirs = Array.isArray(view.root) && view.root.length > 1563 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'564 : 'directory "' + view.root + '"'565 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);566 err.view = view;567 return done(err);568 }569570 // prime the cache571 if (renderOptions.cache) {572 cache[name] = view;573 }574 }575576 // render577 tryRender(view, renderOptions, done);578};579580/**581 * Listen for connections.582 *583 * A node `http.Server` is returned, with this584 * application (which is a `Function`) as its585 * callback. If you wish to create both an HTTP586 * and HTTPS server you may do so with the "http"587 * and "https" modules as shown here:588 *589 * var http = require('http')590 * , https = require('https')591 * , express = require('express')592 * , app = express();593 *594 * http.createServer(app).listen(80);595 * https.createServer({ ... }, app).listen(443);596 *597 * @return {http.Server}598 * @public599 */600601app.listen = function listen() {602 var server = http.createServer(this);603 return server.listen.apply(server, arguments);604};605606/**607 * Log error using console.error.608 *609 * @param {Error} err610 * @private611 */612613function logerror(err) {614 /* istanbul ignore next */615 if (this.get('env') !== 'test') console.error(err.stack || err.toString());616}617618/**619 * Try rendering a view.620 * @private621 */622623function tryRender(view, options, callback) {624 try {625 view.render(options, callback);626 } catch (err) {627 callback(err);628 }629}