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
The walk stopped after 200 commits: lines older than c054581 point at it.
fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 1–4why, one step back1/**2 * Module dependencies.3 */4use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
line 5why, one step back5var finalhandler = require('finalhandler');Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 6why, one step back6var flatten = require('./utils').flatten;fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 7–14why, one step back7var 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');Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 15why, one step back15var compileETag = require('./utils').compileETag;Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
line 16why, one step back16var compileQueryParser = require('./utils').compileQueryParser;Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 17why, one step back17var compileTrust = require('./utils').compileTrust;Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 18why, one step back18var deprecate = require('depd')('express');Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48
line 19why, one step back19var resolve = require('path').resolve;Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 20why, one step back20var slice = Array.prototype.slice;fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 21–53why, one step back2122/**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');Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 54why, one step back54 this.set('etag', 'weak');fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 55–56why, one step back55 var env = process.env.NODE_ENV || 'development';56 this.set('env', env);Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
line 57why, one step back57 this.set('query parser', 'extended');fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
line 58why, one step back58 this.set('subdomain offset', 2);Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 59why, one step back59 this.set('trust proxy', false);fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 60–81why, one step back6061 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);Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48
line 82why, one step back82 this.set('views', resolve('views'));fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 83–110why, one step back83 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 });110Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
line 111why, one step back111 this._router.use(query(this.get('query parser fn')));fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 112–125why, one step back112 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) {fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288
lines 126–127why, one step back126 var router = this._router;127use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
lines 128–131why, one step back128 // final handler129 done = done || finalhandler(req, res, {130 env: this.get('env'),131 onerror: logerror.bind(this)fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
line 132why, one step back132 });use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
line 133why, one step back133fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288
lines 134–141why, one step back134 // no routes135 if (!router) {136 debug('no routes defined on app');137 done();138 return;139 }140141 router.handle(req, res, done);fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 142–153why, one step back142};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 */153Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
lines 154–157why, one step back154app.use = function use(fn) {155 var offset = 0;156 var path = '/';157 var self = this;fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
line 158why, one step back158Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
lines 159–162why, one step back159 // default path to '/'160 if (typeof fn !== 'function') {161 offset = 1;162 path = fn;Support non-string path in app.use(path, fn)Douglas Christopher Wilsonbefore adoption1c3bd36
line 163why, one step back163 }fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
line 164why, one step back164Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
lines 165–170why, one step back165 var fns = flatten(slice.call(arguments, offset));166167 if (fns.length === 0) {168 throw new TypeError('app.use() requires middleware functions');169 }170Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
lines 171–173why, one step back171 // setup router172 this.lazyrouter();173 var router = this._router;fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
line 174why, one step back174Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
lines 175–179why, one step back175 fns.forEach(function (fn) {176 // non-express app177 if (!fn || !fn.handle || !fn.set) {178 return router.use(path, fn);179 }Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 180why, one step back180Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
lines 181–184why, one step back181 debug('.use app under %s', path);182 fn.mountpath = path;183 fn.parent = self;184Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 185why, one step back185 // restore .app property on req and resSupport mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 186why, one step back186 router.use(path, function mounted_app(req, res, next) {fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
line 187why, one step back187 var orig = req.app;Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 188why, one step back188 fn.handle(req, res, function (err) {fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 189–192why, one step back189 req.__proto__ = orig.request;190 res.__proto__ = orig.response;191 next(err);192 });Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 193why, one step back193 });fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
line 194why, one step back194Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 195why, one step back195 // mounted an appSupport mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
lines 196–197why, one step back196 fn.emit('mount', self);197 });Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 198why, one step back198fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 199–300why, one step back199 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){Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 301–302why, one step back301 if (arguments.length === 1) {302 // app.get(setting)fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
line 303why, one step back303 return this.settings[setting];Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 304why, one step back304 }Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 305why, one step back305Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 306–307why, one step back306 // set value307 this.settings[setting] = val;Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 308why, one step back308Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 309–313why, one step back309 // trigger matched settings310 switch (setting) {311 case 'etag':312 debug('compile etag %s', val);313 this.set('etag fn', compileETag(val));Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
lines 314–317why, one step back314 break;315 case 'query parser':316 debug('compile query parser %s', val);317 this.set('query parser fn', compileQueryParser(val));Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 318–322why, one step back318 break;319 case 'trust proxy':320 debug('compile trust proxy %s', val);321 this.set('trust proxy fn', compileTrust(val));322 break;fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
line 323why, one step back323 }Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 324–325why, one step back324325 return this;fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 326–415why, one step back326};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){Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
line 416why, one step back416 if ('get' == method && 1 == arguments.length) return this.set(path);fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
line 417why, one step back417Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
lines 418–420why, one step back418 this.lazyrouter();419420 var route = this._router.route(path);Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 421why, one step back421 route[method].apply(route, slice.call(arguments, 1));fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 422–436why, one step back422 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){Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
lines 437–439why, one step back437 this.lazyrouter();438439 var route = this._router.route(path);Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 440why, one step back440 var args = slice.call(arguments, 1);fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 441–449why, one step back441 methods.forEach(function(method){442 route[method].apply(route, args);443 });444445 return this;446};447448// del -> delete alias449Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 450why, one step back450app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');fix package.json to reflect supported node versionDouglas Christopher Wilsonbefore adoptionc054581
lines 451–547why, one step back451452/**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};use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
lines 548–558why, one step back548549/**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}