application.js
This file
Path
lib/application.js
630 lines · 13.5 KiB · JavaScript
Last changed by
Merge tag '4.16.2'Douglas Christopher Wilsonbefore adoption62e12fe
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 methods = require('methods');18var debug = require('debug')('express:application');19var View = require('./view');20var http = require('http');21var compileETag = require('./utils').compileETag;22var compileQueryParser = require('./utils').compileQueryParser;23var compileTrust = require('./utils').compileTrust;24var flatten = require('array-flatten');25var merge = require('utils-merge');26var resolve = require('path').resolve;27var Router = require('router');28var setPrototypeOf = require('setprototypeof')29var slice = Array.prototype.slice;3031/**32 * Application prototype.33 */3435var app = exports = module.exports = {};3637/**38 * Variable for trust proxy inheritance back-compat39 * @private40 */4142var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';4344/**45 * Initialize the server.46 *47 * - setup default configuration48 * - setup default middleware49 * - setup route reflection methods50 *51 * @private52 */5354app.init = function init() {55 var router = null;5657 this.cache = {};58 this.engines = {};59 this.settings = {};6061 this.defaultConfiguration();6263 // Setup getting to lazily add base router64 Object.defineProperty(this, 'router', {65 configurable: true,66 enumerable: true,67 get: function getrouter() {68 if (router === null) {69 router = new Router({70 caseSensitive: this.enabled('case sensitive routing'),71 strict: this.enabled('strict routing')72 });73 }7475 return router;76 }77 });78};7980/**81 * Initialize application configuration.82 * @private83 */8485app.defaultConfiguration = function defaultConfiguration() {86 var env = process.env.NODE_ENV || 'development';8788 // default settings89 this.enable('x-powered-by');90 this.set('etag', 'weak');91 this.set('env', env);92 this.set('query parser', 'extended');93 this.set('subdomain offset', 2);94 this.set('trust proxy', false);9596 // trust proxy inherit back-compat97 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {98 configurable: true,99 value: true100 });101102 debug('booting in %s mode', env);103104 this.on('mount', function onmount(parent) {105 // inherit trust proxy106 if (this.settings[trustProxyDefaultSymbol] === true107 && typeof parent.settings['trust proxy fn'] === 'function') {108 delete this.settings['trust proxy'];109 delete this.settings['trust proxy fn'];110 }111112 // inherit protos113 setPrototypeOf(this.request, parent.request)114 setPrototypeOf(this.response, parent.response)115 setPrototypeOf(this.engines, parent.engines)116 setPrototypeOf(this.settings, parent.settings)117 });118119 // setup locals120 this.locals = Object.create(null);121122 // top-most app is mounted at /123 this.mountpath = '/';124125 // default locals126 this.locals.settings = this.settings;127128 // default configuration129 this.set('view', View);130 this.set('views', resolve('views'));131 this.set('jsonp callback name', 'callback');132133 if (env === 'production') {134 this.enable('view cache');135 }136};137138/**139 * Dispatch a req, res pair into the application. Starts pipeline processing.140 *141 * If no callback is provided, then default error handlers will respond142 * in the event of an error bubbling through the stack.143 *144 * @private145 */146147app.handle = function handle(req, res, callback) {148 // final handler149 var done = callback || finalhandler(req, res, {150 env: this.get('env'),151 onerror: logerror.bind(this)152 });153154 // set powered by header155 if (this.enabled('x-powered-by')) {156 res.setHeader('X-Powered-By', 'Express');157 }158159 // set circular references160 req.res = res;161 res.req = req;162163 // alter the prototypes164 setPrototypeOf(req, this.request)165 setPrototypeOf(res, this.response)166167 // setup locals168 if (!res.locals) {169 res.locals = Object.create(null);170 }171172 this.router.handle(req, res, done);173};174175/**176 * Proxy `Router#use()` to add middleware to the app router.177 * See Router#use() documentation for details.178 *179 * If the _fn_ parameter is an express app, then it will be180 * mounted at the _route_ specified.181 *182 * @public183 */184185app.use = function use(fn) {186 var offset = 0;187 var path = '/';188189 // default path to '/'190 // disambiguate app.use([fn])191 if (typeof fn !== 'function') {192 var arg = fn;193194 while (Array.isArray(arg) && arg.length !== 0) {195 arg = arg[0];196 }197198 // first arg is the path199 if (typeof arg !== 'function') {200 offset = 1;201 path = fn;202 }203 }204205 var fns = flatten(slice.call(arguments, offset));206207 if (fns.length === 0) {208 throw new TypeError('app.use() requires a middleware function')209 }210211 // get router212 var router = this.router;213214 fns.forEach(function (fn) {215 // non-express app216 if (!fn || !fn.handle || !fn.set) {217 return router.use(path, fn);218 }219220 debug('.use app under %s', path);221 fn.mountpath = path;222 fn.parent = this;223224 // restore .app property on req and res225 router.use(path, function mounted_app(req, res, next) {226 var orig = req.app;227 fn.handle(req, res, function (err) {228 setPrototypeOf(req, orig.request)229 setPrototypeOf(res, orig.response)230 next(err);231 });232 });233234 // mounted an app235 fn.emit('mount', this);236 }, this);237238 return this;239};240241/**242 * Proxy to the app `Router#route()`243 * Returns a new `Route` instance for the _path_.244 *245 * Routes are isolated middleware stacks for specific paths.246 * See the Route api docs for details.247 *248 * @public249 */250251app.route = function route(path) {252 return this.router.route(path);253};254255/**256 * Register the given template engine callback `fn`257 * as `ext`.258 *259 * By default will `require()` the engine based on the260 * file extension. For example if you try to render261 * a "foo.ejs" file Express will invoke the following internally:262 *263 * app.engine('ejs', require('ejs').__express);264 *265 * For engines that do not provide `.__express` out of the box,266 * or if you wish to "map" a different extension to the template engine267 * you may use this method. For example mapping the EJS template engine to268 * ".html" files:269 *270 * app.engine('html', require('ejs').renderFile);271 *272 * In this case EJS provides a `.renderFile()` method with273 * the same signature that Express expects: `(path, options, callback)`,274 * though note that it aliases this method as `ejs.__express` internally275 * so if you're using ".ejs" extensions you dont need to do anything.276 *277 * Some template engines do not follow this convention, the278 * [Consolidate.js](https://github.com/tj/consolidate.js)279 * library was created to map all of node's popular template280 * engines to follow this convention, thus allowing them to281 * work seamlessly within Express.282 *283 * @param {String} ext284 * @param {Function} fn285 * @return {app} for chaining286 * @public287 */288289app.engine = function engine(ext, fn) {290 if (typeof fn !== 'function') {291 throw new Error('callback function required');292 }293294 // get file extension295 var extension = ext[0] !== '.'296 ? '.' + ext297 : ext;298299 // store engine300 this.engines[extension] = fn;301302 return this;303};304305/**306 * Proxy to `Router#param()` with one added api feature. The _name_ parameter307 * can be an array of names.308 *309 * See the Router#param() docs for more details.310 *311 * @param {String|Array} name312 * @param {Function} fn313 * @return {app} for chaining314 * @public315 */316317app.param = function param(name, fn) {318 if (Array.isArray(name)) {319 for (var i = 0; i < name.length; i++) {320 this.param(name[i], fn);321 }322323 return this;324 }325326 this.router.param(name, fn);327328 return this;329};330331/**332 * Assign `setting` to `val`, or return `setting`'s value.333 *334 * app.set('foo', 'bar');335 * app.set('foo');336 * // => "bar"337 *338 * Mounted servers inherit their parent server's settings.339 *340 * @param {String} setting341 * @param {*} [val]342 * @return {Server} for chaining343 * @public344 */345346app.set = function set(setting, val) {347 if (arguments.length === 1) {348 // app.get(setting)349 return this.settings[setting];350 }351352 debug('set "%s" to %o', setting, val);353354 // set value355 this.settings[setting] = val;356357 // trigger matched settings358 switch (setting) {359 case 'etag':360 this.set('etag fn', compileETag(val));361 break;362 case 'query parser':363 this.set('query parser fn', compileQueryParser(val));364 break;365 case 'trust proxy':366 this.set('trust proxy fn', compileTrust(val));367368 // trust proxy inherit back-compat369 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {370 configurable: true,371 value: false372 });373374 break;375 }376377 return this;378};379380/**381 * Return the app's absolute pathname382 * based on the parent(s) that have383 * mounted it.384 *385 * For example if the application was386 * mounted as "/admin", which itself387 * was mounted as "/blog" then the388 * return value would be "/blog/admin".389 *390 * @return {String}391 * @private392 */393394app.path = function path() {395 return this.parent396 ? this.parent.path() + this.mountpath397 : '';398};399400/**401 * Check if `setting` is enabled (truthy).402 *403 * app.enabled('foo')404 * // => false405 *406 * app.enable('foo')407 * app.enabled('foo')408 * // => true409 *410 * @param {String} setting411 * @return {Boolean}412 * @public413 */414415app.enabled = function enabled(setting) {416 return Boolean(this.set(setting));417};418419/**420 * Check if `setting` is disabled.421 *422 * app.disabled('foo')423 * // => true424 *425 * app.enable('foo')426 * app.disabled('foo')427 * // => false428 *429 * @param {String} setting430 * @return {Boolean}431 * @public432 */433434app.disabled = function disabled(setting) {435 return !this.set(setting);436};437438/**439 * Enable `setting`.440 *441 * @param {String} setting442 * @return {app} for chaining443 * @public444 */445446app.enable = function enable(setting) {447 return this.set(setting, true);448};449450/**451 * Disable `setting`.452 *453 * @param {String} setting454 * @return {app} for chaining455 * @public456 */457458app.disable = function disable(setting) {459 return this.set(setting, false);460};461462/**463 * Delegate `.VERB(...)` calls to `router.VERB(...)`.464 */465466methods.forEach(function(method){467 app[method] = function(path){468 if (method === 'get' && arguments.length === 1) {469 // app.get(setting)470 return this.set(path);471 }472473 var route = this.route(path);474 route[method].apply(route, slice.call(arguments, 1));475 return this;476 };477});478479/**480 * Special-cased "all" method, applying the given route `path`,481 * middleware, and callback to _every_ HTTP method.482 *483 * @param {String} path484 * @param {Function} ...485 * @return {app} for chaining486 * @public487 */488489app.all = function all(path) {490 var route = this.route(path);491 var args = slice.call(arguments, 1);492493 for (var i = 0; i < methods.length; i++) {494 route[methods[i]].apply(route, args);495 }496497 return this;498};499500/**501 * Render the given view `name` name with `options`502 * and a callback accepting an error and the503 * rendered template string.504 *505 * Example:506 *507 * app.render('email', { name: 'Tobi' }, function(err, html){508 * // ...509 * })510 *511 * @param {String} name512 * @param {Object|Function} options or fn513 * @param {Function} callback514 * @public515 */516517app.render = function render(name, options, callback) {518 var cache = this.cache;519 var done = callback;520 var engines = this.engines;521 var opts = options;522 var renderOptions = {};523 var view;524525 // support callback function as second arg526 if (typeof options === 'function') {527 done = options;528 opts = {};529 }530531 // merge app.locals532 merge(renderOptions, this.locals);533534 // merge options._locals535 if (opts._locals) {536 merge(renderOptions, opts._locals);537 }538539 // merge options540 merge(renderOptions, opts);541542 // set .cache unless explicitly provided543 if (renderOptions.cache == null) {544 renderOptions.cache = this.enabled('view cache');545 }546547 // primed cache548 if (renderOptions.cache) {549 view = cache[name];550 }551552 // view553 if (!view) {554 var View = this.get('view');555556 view = new View(name, {557 defaultEngine: this.get('view engine'),558 root: this.get('views'),559 engines: engines560 });561562 if (!view.path) {563 var dirs = Array.isArray(view.root) && view.root.length > 1564 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'565 : 'directory "' + view.root + '"'566 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);567 err.view = view;568 return done(err);569 }570571 // prime the cache572 if (renderOptions.cache) {573 cache[name] = view;574 }575 }576577 // render578 tryRender(view, renderOptions, done);579};580581/**582 * Listen for connections.583 *584 * A node `http.Server` is returned, with this585 * application (which is a `Function`) as its586 * callback. If you wish to create both an HTTP587 * and HTTPS server you may do so with the "http"588 * and "https" modules as shown here:589 *590 * var http = require('http')591 * , https = require('https')592 * , express = require('express')593 * , app = express();594 *595 * http.createServer(app).listen(80);596 * https.createServer({ ... }, app).listen(443);597 *598 * @return {http.Server}599 * @public600 */601602app.listen = function listen() {603 var server = http.createServer(this);604 return server.listen.apply(server, arguments);605};606607/**608 * Log error using console.error.609 *610 * @param {Error} err611 * @private612 */613614function logerror(err) {615 /* istanbul ignore next */616 if (this.get('env') !== 'test') console.error(err.stack || err.toString());617}618619/**620 * Try rendering a view.621 * @private622 */623624function tryRender(view, options, callback) {625 try {626 view.render(options, callback);627 } catch (err) {628 callback(err);629 }630}