application.js
This file
Path
lib/application.js
563 lines · 12.2 KiB · JavaScript
Last changed by
Change req.query to a getterDouglas Christopher Wilsonbefore adoptiondcc4eaa
History of this fileTake it
The walk stopped after 200 commits: lines older than 3205f68 point at it.
deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
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;deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 7–13why, one step back7var Router = require('./router');8var methods = require('methods');9var middleware = require('./middleware/init');10var debug = require('debug')('express:application');11var View = require('./view');12var http = require('http');13var compileETag = require('./utils').compileETag;Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
line 14why, one step back14var compileQueryParser = require('./utils').compileQueryParser;deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
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');Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
line 17why, one step back17var merge = require('utils-merge');deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
line 18why, one step back18var resolve = require('path').resolve;Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 19why, one step back19var slice = Array.prototype.slice;deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 20–55why, one step back2021/**22 * Application prototype.23 */2425var app = exports = module.exports = {};2627/**28 * Initialize the server.29 *30 * - setup default configuration31 * - setup default middleware32 * - setup route reflection methods33 *34 * @api private35 */3637app.init = function(){38 this.cache = {};39 this.settings = {};40 this.engines = {};41 this.defaultConfiguration();42};4344/**45 * Initialize application configuration.46 *47 * @api private48 */4950app.defaultConfiguration = function(){51 // default settings52 this.enable('x-powered-by');53 this.set('etag', 'weak');54 var env = process.env.NODE_ENV || 'development';55 this.set('env', env);Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25
line 56why, one step back56 this.set('query parser', 'extended');deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 57–117why, one step back57 this.set('subdomain offset', 2);58 this.set('trust proxy', false);5960 debug('booting in %s mode', env);6162 // inherit protos63 this.on('mount', function(parent){64 this.request.__proto__ = parent.request;65 this.response.__proto__ = parent.response;66 this.engines.__proto__ = parent.engines;67 this.settings.__proto__ = parent.settings;68 });6970 // setup locals71 this.locals = Object.create(null);7273 // top-most app is mounted at /74 this.mountpath = '/';7576 // default locals77 this.locals.settings = this.settings;7879 // default configuration80 this.set('view', View);81 this.set('views', resolve('views'));82 this.set('jsonp callback name', 'callback');8384 if (env === 'production') {85 this.enable('view cache');86 }87};8889/**90 * lazily adds the base router if it has not yet been added.91 *92 * We cannot add the base router in the defaultConfiguration because93 * it reads app settings which might be set after that has run.94 *95 * @api private96 */97app.lazyrouter = function() {98 if (!this._router) {99 this._router = new Router({100 caseSensitive: this.enabled('case sensitive routing'),101 strict: this.enabled('strict routing')102 });103104 this._router.use(middleware.init(this));105 }106};107108/**109 * Dispatch a req, res pair into the application. Starts pipeline processing.110 *111 * If no _done_ callback is provided, then default error handlers will respond112 * in the event of an error bubbling through the stack.113 *114 * @api private115 */116117app.handle = function(req, res, done) {fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288
lines 118–119why, one step back118 var router = this._router;119use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
lines 120–123why, one step back120 // final handler121 done = done || finalhandler(req, res, {122 env: this.get('env'),123 onerror: logerror.bind(this)deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
line 124why, one step back124 });use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
line 125why, one step back125fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288
lines 126–133why, one step back126 // no routes127 if (!router) {128 debug('no routes defined on app');129 done();130 return;131 }132133 router.handle(req, res, done);deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 134–145why, one step back134};135136/**137 * Proxy `Router#use()` to add middleware to the app router.138 * See Router#use() documentation for details.139 *140 * If the _fn_ parameter is an express app, then it will be141 * mounted at the _route_ specified.142 *143 * @api public144 */145Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
lines 146–148why, one step back146app.use = function use(fn) {147 var offset = 0;148 var path = '/';deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
line 149why, one step back149Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 150why, one step back150 // default path to '/'Fix app.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoptioncf41a8f
line 151why, one step back151 // disambiguate app.use([fn])Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 152why, one step back152 if (typeof fn !== 'function') {Fix app.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoptioncf41a8f
lines 153–158why, one step back153 var arg = fn;154155 while (Array.isArray(arg) && arg.length !== 0) {156 arg = arg[0];157 }158Fix regression for empty string path in app.useDouglas Christopher Wilsonbefore adoption3c1a964
lines 159–160why, one step back159 // first arg is the path160 if (typeof arg !== 'function') {Fix app.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoptioncf41a8f
lines 161–163why, one step back161 offset = 1;162 path = fn;163 }Support non-string path in app.use(path, fn)Douglas Christopher Wilsonbefore adoption1c3bd36
line 164why, one step back164 }deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
line 165why, one step back165Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
lines 166–171why, one step back166 var fns = flatten(slice.call(arguments, offset));167168 if (fns.length === 0) {169 throw new TypeError('app.use() requires middleware functions');170 }171Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
lines 172–174why, one step back172 // setup router173 this.lazyrouter();174 var router = this._router;deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
line 175why, one step back175Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
lines 176–180why, one step back176 fns.forEach(function (fn) {177 // non-express app178 if (!fn || !fn.handle || !fn.set) {179 return router.use(path, fn);180 }Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 181why, one step back181Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
lines 182–183why, one step back182 debug('.use app under %s', path);183 fn.mountpath = path;Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4
line 184why, one step back184 fn.parent = this;Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 185why, one step back185Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 186why, one step back186 // restore .app property on req and resSupport mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 187why, one step back187 router.use(path, function mounted_app(req, res, next) {deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
line 188why, one step back188 var orig = req.app;Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29
line 189why, one step back189 fn.handle(req, res, function (err) {deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 190–193why, one step back190 req.__proto__ = orig.request;191 res.__proto__ = orig.response;192 next(err);193 });Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 194why, one step back194 });deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
line 195why, one step back195Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 196why, one step back196 // mounted an appPass context to .forEach instead of closurelemmybefore adoptiondfa7ee4
lines 197–198why, one step back197 fn.emit('mount', this);198 }, this);Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558
line 199why, one step back199deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 200–240why, one step back200 return this;201};202203/**204 * Proxy to the app `Router#route()`205 * Returns a new `Route` instance for the _path_.206 *207 * Routes are isolated middleware stacks for specific paths.208 * See the Route api docs for details.209 *210 * @api public211 */212213app.route = function(path){214 this.lazyrouter();215 return this._router.route(path);216};217218/**219 * Register the given template engine callback `fn`220 * as `ext`.221 *222 * By default will `require()` the engine based on the223 * file extension. For example if you try to render224 * a "foo.jade" file Express will invoke the following internally:225 *226 * app.engine('jade', require('jade').__express);227 *228 * For engines that do not provide `.__express` out of the box,229 * or if you wish to "map" a different extension to the template engine230 * you may use this method. For example mapping the EJS template engine to231 * ".html" files:232 *233 * app.engine('html', require('ejs').renderFile);234 *235 * In this case EJS provides a `.renderFile()` method with236 * the same signature that Express expects: `(path, options, callback)`,237 * though note that it aliases this method as `ejs.__express` internally238 * so if you're using ".ejs" extensions you dont need to do anything.239 *240 * Some template engines do not follow this convention, thedocs: visionmedia is now tj on GithubDouglas Christopher Wilsonbefore adoptione9539fc
line 241why, one step back241 * [Consolidate.js](https://github.com/tj/consolidate.js)deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 242–271why, one step back242 * library was created to map all of node's popular template243 * engines to follow this convention, thus allowing them to244 * work seamlessly within Express.245 *246 * @param {String} ext247 * @param {Function} fn248 * @return {app} for chaining249 * @api public250 */251252app.engine = function(ext, fn){253 if ('function' != typeof fn) throw new Error('callback function required');254 if ('.' != ext[0]) ext = '.' + ext;255 this.engines[ext] = fn;256 return this;257};258259/**260 * Proxy to `Router#param()` with one added api feature. The _name_ parameter261 * can be an array of names.262 *263 * See the Router#param() docs for more details.264 *265 * @param {String|Array} name266 * @param {Function} fn267 * @return {app} for chaining268 * @api public269 */270271app.param = function(name, fn){Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4
line 272why, one step back272 this.lazyrouter();deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 273–275why, one step back273274 if (Array.isArray(name)) {275 name.forEach(function(key) {Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4
lines 276–277why, one step back276 this.param(key, fn);277 }, this);deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 278–280why, one step back278 return this;279 }280Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4
line 281why, one step back281 this._router.param(name, fn);deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 282–313why, one step back282 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){301 if (arguments.length === 1) {302 // app.get(setting)303 return this.settings[setting];304 }305306 // set value307 this.settings[setting] = val;308309 // 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));deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 318–420why, 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;323 }324325 return this;326};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){416 if ('get' == method && 1 == arguments.length) return this.set(path);417418 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));deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 422–439why, 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){437 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);deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
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');deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 451–480why, 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.localsMerge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
line 481why, one step back481 merge(opts, this.locals);deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 482–483why, one step back482483 // merge options._localsMerge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
lines 484–486why, one step back484 if (options._locals) {485 merge(opts, options._locals);486 }deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 487–488why, one step back487488 // merge optionsMerge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
line 489why, one step back489 merge(opts, options);deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 490–507why, one step back490491 // set .cache unless explicitly provided492 opts.cache = null == opts.cache493 ? this.enabled('view cache')494 : opts.cache;495496 // primed cache497 if (opts.cache) view = cache[name];498499 // view500 if (!view) {501 view = new (this.get('view'))(name, {502 defaultEngine: this.get('view engine'),503 root: this.get('views'),504 engines: engines505 });506507 if (!view.path) {Add support for app.set('views', array)Douglas Christopher Wilsonbefore adoption6614352
lines 508–511why, one step back508 var dirs = Array.isArray(view.root) && view.root.length > 1509 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'510 : 'directory "' + view.root + '"'511 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68
lines 512–552why, one step back512 err.view = view;513 return fn(err);514 }515516 // prime the cache517 if (opts.cache) cache[name] = view;518 }519520 // render521 try {522 view.render(opts, fn);523 } catch (err) {524 fn(err);525 }526};527528/**529 * Listen for connections.530 *531 * A node `http.Server` is returned, with this532 * application (which is a `Function`) as its533 * callback. If you wish to create both an HTTP534 * and HTTPS server you may do so with the "http"535 * and "https" modules as shown here:536 *537 * var http = require('http')538 * , https = require('https')539 * , express = require('express')540 * , app = express();541 *542 * http.createServer(app).listen(80);543 * https.createServer({ ... }, app).listen(443);544 *545 * @return {http.Server}546 * @api public547 */548549app.listen = function(){550 var server = http.createServer(this);551 return server.listen.apply(server, arguments);552};use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531
lines 553–563why, one step back553554/**555* Log error using console.error.556*557* @param {Error} err558* @api public559*/560561function logerror(err){562 if (this.get('env') !== 'test') console.error(err.stack || err.toString());563}