application.js
This file
Path
lib/application.js
537 lines · 11.6 KiB · JavaScript
Last changed by
fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288
History of this fileTake it
The walk stopped after 200 commits: lines older than 2e68ddb point at it.
expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
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');Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 6–13why, one step back6var mixin = require('utils-merge');7var Router = require('./router');8var methods = require('methods');9var middleware = require('./middleware/init');10var query = require('./middleware/query');11var debug = require('debug')('express:application');12var View = require('./view');13var http = require('http');Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 14why, one step back14var compileETag = require('./utils').compileETag;Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 15why, one step back15var compileTrust = require('./utils').compileTrust;Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 16why, one step back16var deprecate = require('depd')('express');Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48
line 17why, one step back17var resolve = require('path').resolve;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 18–50why, one step back1819/**20 * Application prototype.21 */2223var app = exports = module.exports = {};2425/**26 * Initialize the server.27 *28 * - setup default configuration29 * - setup default middleware30 * - setup route reflection methods31 *32 * @api private33 */3435app.init = function(){36 this.cache = {};37 this.settings = {};38 this.engines = {};39 this.defaultConfiguration();40};4142/**43 * Initialize application configuration.44 *45 * @api private46 */4748app.defaultConfiguration = function(){49 // default settings50 this.enable('x-powered-by');Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 51why, one step back51 this.set('etag', 'weak');remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 52–53why, one step back52 var env = process.env.NODE_ENV || 'development';53 this.set('env', env);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 54why, one step back54 this.set('subdomain offset', 2);Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 55why, one step back55 this.set('trust proxy', false);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 56why, one step back56remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 57why, one step back57 debug('booting in %s mode', env);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 58–67why, one step back5859 // 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 // setup localsMerge pull request #1908 from visionmedia/locals-objectRoman Shtylmanbefore adoption991c2a9
line 68why, one step back68 this.locals = Object.create(null);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 69why, one step back69remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 70–72why, one step back70 // top-most app is mounted at /71 this.mountpath = '/';72expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 73–77why, one step back73 // default locals74 this.locals.settings = this.settings;7576 // default configuration77 this.set('view', View);Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48
line 78why, one step back78 this.set('views', resolve('views'));expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 79–80why, one step back79 this.set('jsonp callback name', 'callback');80remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 81why, one step back81 if (env === 'production') {expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 82why, one step back82 this.enable('view cache');Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0
line 83why, one step back83 }remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 84–89why, one step back8485 Object.defineProperty(this, 'router', {86 get: function() {87 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.');88 }89 });expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 90–92why, one step back90};9192/**remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 93why, one step back93 * lazily adds the base router if it has not yet been added.expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 94why, one step back94 *remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 95–106why, one step back95 * We cannot add the base router in the defaultConfiguration because96 * it reads app settings which might be set after that has run.97 *98 * @api private99 */100app.lazyrouter = function() {101 if (!this._router) {102 this._router = new Router({103 caseSensitive: this.enabled('case sensitive routing'),104 strict: this.enabled('strict routing')105 });106remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
line 107why, one step back107 this._router.use(query());remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 108–121why, one step back108 this._router.use(middleware.init(this));109 }110};111112/**113 * Dispatch a req, res pair into the application. Starts pipeline processing.114 *115 * If no _done_ callback is provided, then default error handlers will respond116 * in the event of an error bubbling through the stack.117 *118 * @api private119 */120121app.handle = function(req, res, done) {fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288
lines 122–123why, one step back122 var router = this._router;123use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
lines 124–127why, one step back124 // final handler125 done = done || finalhandler(req, res, {126 env: this.get('env'),127 onerror: logerror.bind(this)remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 128why, one step back128 });use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
line 129why, one step back129fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288
lines 130–137why, one step back130 // no routes131 if (!router) {132 debug('no routes defined on app');133 done();134 return;135 }136137 router.handle(req, res, done);remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 138–146why, one step back138};139140/**141 * Proxy `Router#use()` to add middleware to the app router.142 * See Router#use() documentation for details.143 *144 * If the _fn_ parameter is an express app, then it will be145 * mounted at the _route_ specified.146 *expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 147–150why, one step back147 * @api public148 */149150app.use = function(route, fn){remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 151why, one step back151 var mount_app;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 152–156why, one step back152153 // default route to '/'154 if ('string' != typeof route) fn = route, route = '/';155156 // express appremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 157why, one step back157 if (fn.handle && fn.set) mount_app = fn;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 158–159why, one step back158159 // restore .app property on req and resremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 160–162why, one step back160 if (mount_app) {161 debug('.use app under %s', route);162 mount_app.mountpath = route;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 163–164why, one step back163 fn = function(req, res, next) {164 var orig = req.app;remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 165why, one step back165 mount_app.handle(req, res, function(err) {expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 166–172why, one step back166 req.__proto__ = orig.request;167 res.__proto__ = orig.response;168 next(err);169 });170 };171 }172remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 173–174why, one step back173 this.lazyrouter();174 this._router.use(route, fn);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 175–176why, one step back175176 // mounted an appremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 177–179why, one step back177 if (mount_app) {178 mount_app.parent = this;179 mount_app.emit('mount', this);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 180–185why, one step back180 }181182 return this;183};184185/**remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 186–195why, one step back186 * Proxy to the app `Router#route()`187 * Returns a new `Route` instance for the _path_.188 *189 * Routes are isolated middleware stacks for specific paths.190 * See the Route api docs for details.191 *192 * @api public193 */194195app.route = function(path){implement app.route()Roman Shtylmanbefore adoption0719e5f
lines 196–197why, one step back196 this.lazyrouter();197 return this._router.route(path);remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 198–200why, one step back198};199200/**expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 201–241why, one step back201 * Register the given template engine callback `fn`202 * as `ext`.203 *204 * By default will `require()` the engine based on the205 * file extension. For example if you try to render206 * a "foo.jade" file Express will invoke the following internally:207 *208 * app.engine('jade', require('jade').__express);209 *210 * For engines that do not provide `.__express` out of the box,211 * or if you wish to "map" a different extension to the template engine212 * you may use this method. For example mapping the EJS template engine to213 * ".html" files:214 *215 * app.engine('html', require('ejs').renderFile);216 *217 * In this case EJS provides a `.renderFile()` method with218 * the same signature that Express expects: `(path, options, callback)`,219 * though note that it aliases this method as `ejs.__express` internally220 * so if you're using ".ejs" extensions you dont need to do anything.221 *222 * Some template engines do not follow this convention, the223 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)224 * library was created to map all of node's popular template225 * engines to follow this convention, thus allowing them to226 * work seamlessly within Express.227 *228 * @param {String} ext229 * @param {Function} fn230 * @return {app} for chaining231 * @api public232 */233234app.engine = function(ext, fn){235 if ('function' != typeof fn) throw new Error('callback function required');236 if ('.' != ext[0]) ext = '.' + ext;237 this.engines[ext] = fn;238 return this;239};240241/**remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 242–243why, one step back242 * Proxy to `Router#param()` with one added api feature. The _name_ parameter243 * can be an array of names.expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 244why, one step back244 *remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 245why, one step back245 * See the Router#param() docs for more details.expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 246–253why, one step back246 *247 * @param {String|Array} name248 * @param {Function} fn249 * @return {app} for chaining250 * @api public251 */252253app.param = function(name, fn){remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 254–255why, one step back254 var self = this;255 self.lazyrouter();expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 256–257why, one step back256257 if (Array.isArray(name)) {remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 258–259why, one step back258 name.forEach(function(key) {259 self.param(key, fn);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 260why, one step back260 });remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 261why, one step back261 return this;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 262–263why, one step back262 }263remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 264why, one step back264 self._router.param(name, fn);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 265–277why, one step back265 return this;266};267268/**269 * Assign `setting` to `val`, or return `setting`'s value.270 *271 * app.set('foo', 'bar');272 * app.get('foo');273 * // => "bar"274 *275 * Mounted servers inherit their parent server's settings.276 *277 * @param {String} settingMerge pull request #1890 from oliversalzburg/patch-1TJ Holowaychukbefore adoption827dfed
line 278why, one step back278 * @param {*} [val]expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 279–283why, one step back279 * @return {Server} for chaining280 * @api public281 */282283app.set = function(setting, val){Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 284–285why, one step back284 if (arguments.length === 1) {285 // app.get(setting)expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 286why, one step back286 return this.settings[setting];Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 287why, one step back287 }Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 288why, one step back288Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 289–290why, one step back289 // set value290 this.settings[setting] = val;Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 291why, one step back291Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 292–301why, one step back292 // trigger matched settings293 switch (setting) {294 case 'etag':295 debug('compile etag %s', val);296 this.set('etag fn', compileETag(val));297 break;298 case 'trust proxy':299 debug('compile trust proxy %s', val);300 this.set('trust proxy fn', compileTrust(val));301 break;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 302why, one step back302 }Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 303–304why, one step back303304 return this;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 305–322why, one step back305};306307/**308 * Return the app's absolute pathname309 * based on the parent(s) that have310 * mounted it.311 *312 * For example if the application was313 * mounted as "/admin", which itself314 * was mounted as "/blog" then the315 * return value would be "/blog/admin".316 *317 * @return {String}318 * @api private319 */320321app.path = function(){322 return this.parentremove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
line 323why, one step back323 ? this.parent.path() + this.mountpathexpose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 324–394why, one step back324 : '';325};326327/**328 * Check if `setting` is enabled (truthy).329 *330 * app.enabled('foo')331 * // => false332 *333 * app.enable('foo')334 * app.enabled('foo')335 * // => true336 *337 * @param {String} setting338 * @return {Boolean}339 * @api public340 */341342app.enabled = function(setting){343 return !!this.set(setting);344};345346/**347 * Check if `setting` is disabled.348 *349 * app.disabled('foo')350 * // => true351 *352 * app.enable('foo')353 * app.disabled('foo')354 * // => false355 *356 * @param {String} setting357 * @return {Boolean}358 * @api public359 */360361app.disabled = function(setting){362 return !this.set(setting);363};364365/**366 * Enable `setting`.367 *368 * @param {String} setting369 * @return {app} for chaining370 * @api public371 */372373app.enable = function(setting){374 return this.set(setting, true);375};376377/**378 * Disable `setting`.379 *380 * @param {String} setting381 * @return {app} for chaining382 * @api public383 */384385app.disable = function(setting){386 return this.set(setting, false);387};388389/**390 * Delegate `.VERB(...)` calls to `router.VERB(...)`.391 */392393methods.forEach(function(method){394 app[method] = function(path){Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
line 395why, one step back395 if ('get' == method && 1 == arguments.length) return this.set(path);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 396why, one step back396Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
lines 397–399why, one step back397 this.lazyrouter();398399 var route = this._router.route(path);support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 400why, one step back400 route[method].apply(route, [].slice.call(arguments, 1));expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 401–415why, one step back401 return this;402 };403});404405/**406 * Special-cased "all" method, applying the given route `path`,407 * middleware, and callback to _every_ HTTP method.408 *409 * @param {String} path410 * @param {Function} ...411 * @return {app} for chaining412 * @api public413 */414415app.all = function(path){Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
lines 416–418why, one step back416 this.lazyrouter();417418 var route = this._router.route(path);support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 419why, one step back419 var args = [].slice.call(arguments, 1);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
line 420why, one step back420 methods.forEach(function(method){support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 421why, one step back421 route[method].apply(route, args);remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a
lines 422–423why, one step back422 });423expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 424–428why, one step back424 return this;425};426427// del -> delete alias428Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 429why, one step back429app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 430–448why, one step back430431/**432 * Render the given view `name` name with `options`433 * and a callback accepting an error and the434 * rendered template string.435 *436 * Example:437 *438 * app.render('email', { name: 'Tobi' }, function(err, html){439 * // ...440 * })441 *442 * @param {String} name443 * @param {String|Function} options or fn444 * @param {Function} fn445 * @api public446 */447448app.render = function(name, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 449–452why, one step back449 var opts = {};450 var cache = this.cache;451 var engines = this.engines;452 var view;expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 453–459why, one step back453454 // support callback function as second arg455 if ('function' == typeof options) {456 fn = options, options = {};457 }458459 // merge app.localsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 460why, one step back460 mixin(opts, this.locals);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 461–462why, one step back461462 // merge options._localsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 463why, one step back463 if (options._locals) mixin(opts, options._locals);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 464–465why, one step back464465 // merge optionsuse utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f
line 466why, one step back466 mixin(opts, options);expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 467–484why, one step back467468 // set .cache unless explicitly provided469 opts.cache = null == opts.cache470 ? this.enabled('view cache')471 : opts.cache;472473 // primed cache474 if (opts.cache) view = cache[name];475476 // view477 if (!view) {478 view = new (this.get('view'))(name, {479 defaultEngine: this.get('view engine'),480 root: this.get('views'),481 engines: engines482 });483484 if (!view.path) {Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1
line 485why, one step back485 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');expose connect.middleware using Object.getOwnPropertyDescriptor()Jonathan Ongbefore adoption2e68ddb
lines 486–526why, one step back486 err.view = view;487 return fn(err);488 }489490 // prime the cache491 if (opts.cache) cache[name] = view;492 }493494 // render495 try {496 view.render(opts, fn);497 } catch (err) {498 fn(err);499 }500};501502/**503 * Listen for connections.504 *505 * A node `http.Server` is returned, with this506 * application (which is a `Function`) as its507 * callback. If you wish to create both an HTTP508 * and HTTPS server you may do so with the "http"509 * and "https" modules as shown here:510 *511 * var http = require('http')512 * , https = require('https')513 * , express = require('express')514 * , app = express();515 *516 * http.createServer(app).listen(80);517 * https.createServer({ ... }, app).listen(443);518 *519 * @return {http.Server}520 * @api public521 */522523app.listen = function(){524 var server = http.createServer(this);525 return server.listen.apply(server, arguments);526};use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
lines 527–537why, one step back527528/**529* Log error using console.error.530*531* @param {Error} err532* @api public533*/534535function logerror(err){536 if (this.get('env') !== 'test') console.error(err.stack || err.toString());537}