application.js
This file
Path
lib/application.js
554 lines · 12.1 KiB · JavaScript
Last changed by
Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
History of this fileTake it
The walk stopped after 200 commits: lines older than 9bc63d9 point at it.
move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
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;Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
line 15why, one step back15var compileQueryParser = require('./utils').compileQueryParser;Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 16why, one step back16var compileTrust = require('./utils').compileTrust;Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 17why, one step back17var deprecate = require('depd')('express');Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48
line 18why, one step back18var resolve = require('path').resolve;move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 19–51why, one step back1920/**21 * Application prototype.22 */2324var app = exports = module.exports = {};2526/**27 * Initialize the server.28 *29 * - setup default configuration30 * - setup default middleware31 * - setup route reflection methods32 *33 * @api private34 */3536app.init = function(){37 this.cache = {};38 this.settings = {};39 this.engines = {};40 this.defaultConfiguration();41};4243/**44 * Initialize application configuration.45 *46 * @api private47 */4849app.defaultConfiguration = function(){50 // default settings51 this.enable('x-powered-by');Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 52why, one step back52 this.set('etag', 'weak');move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 53–54why, one step back53 var env = process.env.NODE_ENV || 'development';54 this.set('env', env);Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
line 55why, one step back55 this.set('query parser', 'extended');move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 56why, one step back56 this.set('subdomain offset', 2);Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 57why, one step back57 this.set('trust proxy', false);move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 58–79why, one step back5859 debug('booting in %s mode', env);6061 // inherit protos62 this.on('mount', function(parent){63 this.request.__proto__ = parent.request;64 this.response.__proto__ = parent.response;65 this.engines.__proto__ = parent.engines;66 this.settings.__proto__ = parent.settings;67 });6869 // setup locals70 this.locals = Object.create(null);7172 // top-most app is mounted at /73 this.mountpath = '/';7475 // default locals76 this.locals.settings = this.settings;7778 // default configuration79 this.set('view', View);Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48
line 80why, one step back80 this.set('views', resolve('views'));move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 81–108why, one step back81 this.set('jsonp callback name', 'callback');8283 if (env === 'production') {84 this.enable('view cache');85 }8687 Object.defineProperty(this, 'router', {88 get: function() {89 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.');90 }91 });92};9394/**95 * lazily adds the base router if it has not yet been added.96 *97 * We cannot add the base router in the defaultConfiguration because98 * it reads app settings which might be set after that has run.99 *100 * @api private101 */102app.lazyrouter = function() {103 if (!this._router) {104 this._router = new Router({105 caseSensitive: this.enabled('case sensitive routing'),106 strict: this.enabled('strict routing')107 });108Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
line 109why, one step back109 this._router.use(query(this.get('query parser fn')));move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 110–123why, one step back110 this._router.use(middleware.init(this));111 }112};113114/**115 * Dispatch a req, res pair into the application. Starts pipeline processing.116 *117 * If no _done_ callback is provided, then default error handlers will respond118 * in the event of an error bubbling through the stack.119 *120 * @api private121 */122123app.handle = function(req, res, done) {fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288
lines 124–125why, one step back124 var router = this._router;125use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
lines 126–129why, one step back126 // final handler127 done = done || finalhandler(req, res, {128 env: this.get('env'),129 onerror: logerror.bind(this)move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 130why, one step back130 });use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
line 131why, one step back131fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288
lines 132–139why, one step back132 // no routes133 if (!router) {134 debug('no routes defined on app');135 done();136 return;137 }138139 router.handle(req, res, done);move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 140–151why, one step back140};141142/**143 * Proxy `Router#use()` to add middleware to the app router.144 * See Router#use() documentation for details.145 *146 * If the _fn_ parameter is an express app, then it will be147 * mounted at the _route_ specified.148 *149 * @api public150 */151Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 152why, one step back152app.use = function use(path, fn) {move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 153why, one step back153 var mount_app;Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 154why, one step back154 var mount_path;move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 155why, one step back155Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
lines 156–163why, one step back156 // check for .use(path, app) or .use(app) signature157 if (arguments.length <= 2) {158 mount_path = typeof path === 'string'159 ? path160 : '/';161 mount_app = typeof path === 'function'162 ? path163 : fn;Support non-string path in app.use(path, fn)Douglas Christopher Wilsonbefore adoption1c3bd36
line 164why, one step back164 }move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 165why, one step back165Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
lines 166–168why, one step back166 // setup router167 this.lazyrouter();168 var router = this._router;move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 169why, one step back169Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
lines 170–172why, one step back170 // express app171 if (mount_app && mount_app.handle && mount_app.set) {172 debug('.use app under %s', mount_path);Fix subapp.mountpath regression for app.use(subapp)Douglas Christopher Wilsonbefore adoption3e32721
line 173why, one step back173 mount_app.mountpath = mount_path;Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
lines 174–177why, one step back174 mount_app.parent = this;175176 // restore .app property on req and res177 router.use(mount_path, function mounted_app(req, res, next) {move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 178–183why, one step back178 var orig = req.app;179 mount_app.handle(req, res, function(err) {180 req.__proto__ = orig.request;181 res.__proto__ = orig.response;182 next(err);183 });Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 184why, one step back184 });move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 185why, one step back185Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 186why, one step back186 // mounted an appmove `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 187why, one step back187 mount_app.emit('mount', this);Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
lines 188–189why, one step back188189 return this;move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 190why, one step back190 }Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
lines 191–193why, one step back191192 // pass-through use193 router.use.apply(router, arguments);move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 194–208why, one step back194195 return this;196};197198/**199 * Proxy to the app `Router#route()`200 * Returns a new `Route` instance for the _path_.201 *202 * Routes are isolated middleware stacks for specific paths.203 * See the Route api docs for details.204 *205 * @api public206 */207208app.route = function(path){implement app.route()Roman Shtylmanbefore adoption0719e5f
lines 209–210why, one step back209 this.lazyrouter();210 return this._router.route(path);move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 211–296why, one step back211};212213/**214 * Register the given template engine callback `fn`215 * as `ext`.216 *217 * By default will `require()` the engine based on the218 * file extension. For example if you try to render219 * a "foo.jade" file Express will invoke the following internally:220 *221 * app.engine('jade', require('jade').__express);222 *223 * For engines that do not provide `.__express` out of the box,224 * or if you wish to "map" a different extension to the template engine225 * you may use this method. For example mapping the EJS template engine to226 * ".html" files:227 *228 * app.engine('html', require('ejs').renderFile);229 *230 * In this case EJS provides a `.renderFile()` method with231 * the same signature that Express expects: `(path, options, callback)`,232 * though note that it aliases this method as `ejs.__express` internally233 * so if you're using ".ejs" extensions you dont need to do anything.234 *235 * Some template engines do not follow this convention, the236 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)237 * library was created to map all of node's popular template238 * engines to follow this convention, thus allowing them to239 * work seamlessly within Express.240 *241 * @param {String} ext242 * @param {Function} fn243 * @return {app} for chaining244 * @api public245 */246247app.engine = function(ext, fn){248 if ('function' != typeof fn) throw new Error('callback function required');249 if ('.' != ext[0]) ext = '.' + ext;250 this.engines[ext] = fn;251 return this;252};253254/**255 * Proxy to `Router#param()` with one added api feature. The _name_ parameter256 * can be an array of names.257 *258 * See the Router#param() docs for more details.259 *260 * @param {String|Array} name261 * @param {Function} fn262 * @return {app} for chaining263 * @api public264 */265266app.param = function(name, fn){267 var self = this;268 self.lazyrouter();269270 if (Array.isArray(name)) {271 name.forEach(function(key) {272 self.param(key, fn);273 });274 return this;275 }276277 self._router.param(name, fn);278 return this;279};280281/**282 * Assign `setting` to `val`, or return `setting`'s value.283 *284 * app.set('foo', 'bar');285 * app.get('foo');286 * // => "bar"287 *288 * Mounted servers inherit their parent server's settings.289 *290 * @param {String} setting291 * @param {*} [val]292 * @return {Server} for chaining293 * @api public294 */295296app.set = function(setting, val){Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 297–298why, one step back297 if (arguments.length === 1) {298 // app.get(setting)move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 299why, one step back299 return this.settings[setting];Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
line 300why, one step back300 }Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 301why, one step back301Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 302–303why, one step back302 // set value303 this.settings[setting] = val;Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c
line 304why, one step back304Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 305–309why, one step back305 // trigger matched settings306 switch (setting) {307 case 'etag':308 debug('compile etag %s', val);309 this.set('etag fn', compileETag(val));Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
lines 310–313why, one step back310 break;311 case 'query parser':312 debug('compile query parser %s', val);313 this.set('query parser fn', compileQueryParser(val));Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 314–318why, one step back314 break;315 case 'trust proxy':316 debug('compile trust proxy %s', val);317 this.set('trust proxy fn', compileTrust(val));318 break;move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 319why, one step back319 }Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d
lines 320–321why, one step back320321 return this;move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 322–411why, one step back322};323324/**325 * Return the app's absolute pathname326 * based on the parent(s) that have327 * mounted it.328 *329 * For example if the application was330 * mounted as "/admin", which itself331 * was mounted as "/blog" then the332 * return value would be "/blog/admin".333 *334 * @return {String}335 * @api private336 */337338app.path = function(){339 return this.parent340 ? this.parent.path() + this.mountpath341 : '';342};343344/**345 * Check if `setting` is enabled (truthy).346 *347 * app.enabled('foo')348 * // => false349 *350 * app.enable('foo')351 * app.enabled('foo')352 * // => true353 *354 * @param {String} setting355 * @return {Boolean}356 * @api public357 */358359app.enabled = function(setting){360 return !!this.set(setting);361};362363/**364 * Check if `setting` is disabled.365 *366 * app.disabled('foo')367 * // => true368 *369 * app.enable('foo')370 * app.disabled('foo')371 * // => false372 *373 * @param {String} setting374 * @return {Boolean}375 * @api public376 */377378app.disabled = function(setting){379 return !this.set(setting);380};381382/**383 * Enable `setting`.384 *385 * @param {String} setting386 * @return {app} for chaining387 * @api public388 */389390app.enable = function(setting){391 return this.set(setting, true);392};393394/**395 * Disable `setting`.396 *397 * @param {String} setting398 * @return {app} for chaining399 * @api public400 */401402app.disable = function(setting){403 return this.set(setting, false);404};405406/**407 * Delegate `.VERB(...)` calls to `router.VERB(...)`.408 */409410methods.forEach(function(method){411 app[method] = function(path){Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
line 412why, one step back412 if ('get' == method && 1 == arguments.length) return this.set(path);move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 413why, one step back413Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
lines 414–416why, one step back414 this.lazyrouter();415416 var route = this._router.route(path);support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 417why, one step back417 route[method].apply(route, [].slice.call(arguments, 1));move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 418–432why, one step back418 return this;419 };420});421422/**423 * Special-cased "all" method, applying the given route `path`,424 * middleware, and callback to _every_ HTTP method.425 *426 * @param {String} path427 * @param {Function} ...428 * @return {app} for chaining429 * @api public430 */431432app.all = function(path){Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916
lines 433–435why, one step back433 this.lazyrouter();434435 var route = this._router.route(path);support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 436why, one step back436 var args = [].slice.call(arguments, 1);move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
line 437why, one step back437 methods.forEach(function(method){support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854
line 438why, one step back438 route[method].apply(route, args);move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 439–445why, one step back439 });440441 return this;442};443444// del -> delete alias445Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 446why, one step back446app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 447–465why, one step back447448/**449 * Render the given view `name` name with `options`450 * and a callback accepting an error and the451 * rendered template string.452 *453 * Example:454 *455 * app.render('email', { name: 'Tobi' }, function(err, html){456 * // ...457 * })458 *459 * @param {String} name460 * @param {String|Function} options or fn461 * @param {Function} fn462 * @api public463 */464465app.render = function(name, options, fn){Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874
lines 466–469why, one step back466 var opts = {};467 var cache = this.cache;468 var engines = this.engines;469 var view;move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9
lines 470–543why, one step back470471 // support callback function as second arg472 if ('function' == typeof options) {473 fn = options, options = {};474 }475476 // merge app.locals477 mixin(opts, this.locals);478479 // merge options._locals480 if (options._locals) mixin(opts, options._locals);481482 // merge options483 mixin(opts, options);484485 // set .cache unless explicitly provided486 opts.cache = null == opts.cache487 ? this.enabled('view cache')488 : opts.cache;489490 // primed cache491 if (opts.cache) view = cache[name];492493 // view494 if (!view) {495 view = new (this.get('view'))(name, {496 defaultEngine: this.get('view engine'),497 root: this.get('views'),498 engines: engines499 });500501 if (!view.path) {502 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');503 err.view = view;504 return fn(err);505 }506507 // prime the cache508 if (opts.cache) cache[name] = view;509 }510511 // render512 try {513 view.render(opts, fn);514 } catch (err) {515 fn(err);516 }517};518519/**520 * Listen for connections.521 *522 * A node `http.Server` is returned, with this523 * application (which is a `Function`) as its524 * callback. If you wish to create both an HTTP525 * and HTTPS server you may do so with the "http"526 * and "https" modules as shown here:527 *528 * var http = require('http')529 * , https = require('https')530 * , express = require('express')531 * , app = express();532 *533 * http.createServer(app).listen(80);534 * https.createServer({ ... }, app).listen(443);535 *536 * @return {http.Server}537 * @api public538 */539540app.listen = function(){541 var server = http.createServer(this);542 return server.listen.apply(server, arguments);543};use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
lines 544–554why, one step back544545/**546* Log error using console.error.547*548* @param {Error} err549* @api public550*/551552function logerror(err){553 if (this.get('env') !== 'test') console.error(err.stack || err.toString());554}