Skip to content
Myr

application.js

This file

Path

lib/application.js

593 lines · 12.9 KiB · JavaScript

Last changed by

Merge tag '4.12.0'Douglas Christopher Wilsonbefore adoptionf6ec710

History of this file

Take it

The walk stopped after 200 commits: lines older than 3136e98 point at it.

Merge tag '4.12.0'Douglas Christopher Wilsonbefore adoptionf6ec710

lines 1–8why, one step back
1/*!
2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */8

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 9–10why, one step back
9/**
10 * Module dependencies.

Merge tag '4.12.0'Douglas Christopher Wilsonbefore adoptionf6ec710

line 11why, one step back
11 * @api private

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 12–14why, one step back
12 */
1314var finalhandler = require('finalhandler');

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 15why, one step back
15var flatten = require('./utils').flatten;

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 16–21why, one step back
16var Router = require('./router');
17var methods = require('methods');18var debug = require('debug')('express:application');19var View = require('./view');20var http = require('http');21var compileETag = require('./utils').compileETag;

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

line 22why, one step back
22var compileQueryParser = require('./utils').compileQueryParser;

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

line 23why, one step back
23var compileTrust = require('./utils').compileTrust;

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 24why, one step back
24var merge = require('utils-merge');

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

line 25why, one step back
25var resolve = require('path').resolve;

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 26why, one step back
26var slice = Array.prototype.slice;

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 27–34why, one step back
27
28/**29 * Application prototype.30 */3132var app = exports = module.exports = {};3334/**

Merge tag '4.12.0'Douglas Christopher Wilsonbefore adoptionf6ec710

lines 35–41why, one step back
35 * Variable for trust proxy inheritance back-compat
36 * @api private37 */3839var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';4041/**

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 42–51why, one step back
42 * Initialize the server.
43 *44 * - setup default configuration45 * - setup default middleware46 * - setup route reflection methods47 *48 * @api private49 */5051app.init = function(){

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

lines 52–53why, one step back
52 var router = null;
53

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 54–57why, one step back
54 this.cache = {};
55 this.settings = {};56 this.engines = {};57 this.defaultConfiguration();

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

lines 58–73why, one step back
58
59 // Setup getting to lazily add base router60 Object.defineProperty(this, 'router', {61 configurable: true,62 enumerable: true,63 get: function getrouter() {64 if (router === null) {65 router = new Router({66 caseSensitive: this.enabled('case sensitive routing'),67 strict: this.enabled('strict routing')68 });69 }7071 return router;72 }73 });

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 74–87why, one step back
74};
7576/**77 * Initialize application configuration.78 *79 * @api private80 */8182app.defaultConfiguration = function(){83 // default settings84 this.enable('x-powered-by');85 this.set('etag', 'weak');86 var env = process.env.NODE_ENV || 'development';87 this.set('env', env);

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

line 88why, one step back
88 this.set('query parser', 'extended');

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 89–91why, one step back
89 this.set('subdomain offset', 2);
90 this.set('trust proxy', false);91

Merge tag '4.12.0'Douglas Christopher Wilsonbefore adoptionf6ec710

lines 92–97why, one step back
92 // trust proxy inherit back-compat
93 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {94 configurable: true,95 value: true96 });97

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 98–99why, one step back
98 debug('booting in %s mode', env);
99

Merge tag '4.12.0'Douglas Christopher Wilsonbefore adoptionf6ec710

lines 100–108why, one step back
100 this.on('mount', function onmount(parent) {
101 // inherit trust proxy102 if (this.settings[trustProxyDefaultSymbol] === true103 && typeof parent.settings['trust proxy fn'] === 'function') {104 delete this.settings['trust proxy'];105 delete this.settings['trust proxy fn'];106 }107108 // inherit protos

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 109–149why, one step back
109 this.request.__proto__ = parent.request;
110 this.response.__proto__ = parent.response;111 this.engines.__proto__ = parent.engines;112 this.settings.__proto__ = parent.settings;113 });114115 // setup locals116 this.locals = Object.create(null);117118 // top-most app is mounted at /119 this.mountpath = '/';120121 // default locals122 this.locals.settings = this.settings;123124 // default configuration125 this.set('view', View);126 this.set('views', resolve('views'));127 this.set('jsonp callback name', 'callback');128129 if (env === 'production') {130 this.enable('view cache');131 }132};133134/**135 * Dispatch a req, res pair into the application. Starts pipeline processing.136 *137 * If no _done_ callback is provided, then default error handlers will respond138 * in the event of an error bubbling through the stack.139 *140 * @api private141 */142143app.handle = function(req, res, done) {144 // final handler145 done = done || finalhandler(req, res, {146 env: this.get('env'),147 onerror: logerror.bind(this)148 });149

Refactor away init middlewareDouglas Christopher Wilsonbefore adoption78e5054

lines 150–165why, one step back
150 // set powered by header
151 if (this.enabled('x-powered-by')) {152 res.setHeader('X-Powered-By', 'Express');153 }154155 // set circular references156 req.res = res;157 res.req = req;158159 // alter the prototypes160 req.__proto__ = this.request;161 res.__proto__ = this.response;162163 // setup locals164 if (!res.locals) {165 res.locals = Object.create(null);

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 166–167why, one step back
166 }
167

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

line 168why, one step back
168 this.router.handle(req, res, done);

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 169–180why, one step back
169};
170171/**172 * Proxy `Router#use()` to add middleware to the app router.173 * See Router#use() documentation for details.174 *175 * If the _fn_ parameter is an express app, then it will be176 * mounted at the _route_ specified.177 *178 * @api public179 */180

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

lines 181–183why, one step back
181app.use = function use(fn) {
182 var offset = 0;183 var path = '/';

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

line 184why, one step back
184

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 185why, one step back
185 // default path to '/'

Fix app.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoptioncf41a8f

line 186why, one step back
186 // disambiguate app.use([fn])

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 187why, one step back
187 if (typeof fn !== 'function') {

Fix app.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoptioncf41a8f

lines 188–193why, one step back
188 var arg = fn;
189190 while (Array.isArray(arg) && arg.length !== 0) {191 arg = arg[0];192 }193

Fix regression for empty string path in app.useDouglas Christopher Wilsonbefore adoption3c1a964

lines 194–195why, one step back
194 // first arg is the path
195 if (typeof arg !== 'function') {

Fix app.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoptioncf41a8f

lines 196–198why, one step back
196 offset = 1;
197 path = fn;198 }

Support non-string path in app.use(path, fn)Douglas Christopher Wilsonbefore adoption1c3bd36

line 199why, one step back
199 }

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

line 200why, one step back
200

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

lines 201–206why, one step back
201 var fns = flatten(slice.call(arguments, offset));
202203 if (fns.length === 0) {204 throw new TypeError('app.use() requires middleware functions');205 }206

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

lines 207–208why, one step back
207 // get router
208 var router = this.router;

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

line 209why, one step back
209

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

lines 210–214why, one step back
210 fns.forEach(function (fn) {
211 // non-express app212 if (!fn || !fn.handle || !fn.set) {213 return router.use(path, fn);214 }

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

line 215why, one step back
215

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

lines 216–217why, one step back
216 debug('.use app under %s', path);
217 fn.mountpath = path;

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

line 218why, one step back
218 fn.parent = this;

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 219why, one step back
219

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

line 220why, one step back
220 // restore .app property on req and res

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 221why, one step back
221 router.use(path, function mounted_app(req, res, next) {

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

line 222why, one step back
222 var orig = req.app;

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 223why, one step back
223 fn.handle(req, res, function (err) {

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 224–227why, one step back
224 req.__proto__ = orig.request;
225 res.__proto__ = orig.response;226 next(err);227 });

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

line 228why, one step back
228 });

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

line 229why, one step back
229

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

line 230why, one step back
230 // mounted an app

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

lines 231–232why, one step back
231 fn.emit('mount', this);
232 }, this);

Accept multiple callbacks to app.use()Douglas Christopher Wilsonbefore adoption997a558

line 233why, one step back
233

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 234–246why, one step back
234 return this;
235};236237/**238 * Proxy to the app `Router#route()`239 * Returns a new `Route` instance for the _path_.240 *241 * Routes are isolated middleware stacks for specific paths.242 * See the Route api docs for details.243 *244 * @api public245 */246

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

lines 247–248why, one step back
247app.route = function route(path) {
248 return this.router.route(path);

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 249–273why, one step back
249};
250251/**252 * Register the given template engine callback `fn`253 * as `ext`.254 *255 * By default will `require()` the engine based on the256 * file extension. For example if you try to render257 * a "foo.jade" file Express will invoke the following internally:258 *259 * app.engine('jade', require('jade').__express);260 *261 * For engines that do not provide `.__express` out of the box,262 * or if you wish to "map" a different extension to the template engine263 * you may use this method. For example mapping the EJS template engine to264 * ".html" files:265 *266 * app.engine('html', require('ejs').renderFile);267 *268 * In this case EJS provides a `.renderFile()` method with269 * the same signature that Express expects: `(path, options, callback)`,270 * though note that it aliases this method as `ejs.__express` internally271 * so if you're using ".ejs" extensions you dont need to do anything.272 *273 * Some template engines do not follow this convention, the

docs: visionmedia is now tj on GithubDouglas Christopher Wilsonbefore adoptione9539fc

line 274why, one step back
274 * [Consolidate.js](https://github.com/tj/consolidate.js)

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 275–303why, one step back
275 * library was created to map all of node's popular template
276 * engines to follow this convention, thus allowing them to277 * work seamlessly within Express.278 *279 * @param {String} ext280 * @param {Function} fn281 * @return {app} for chaining282 * @api public283 */284285app.engine = function(ext, fn){286 if ('function' != typeof fn) throw new Error('callback function required');287 if ('.' != ext[0]) ext = '.' + ext;288 this.engines[ext] = fn;289 return this;290};291292/**293 * Proxy to `Router#param()` with one added api feature. The _name_ parameter294 * can be an array of names.295 *296 * See the Router#param() docs for more details.297 *298 * @param {String|Array} name299 * @param {Function} fn300 * @return {app} for chaining301 * @api public302 */303

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

line 304why, one step back
304app.param = function param(name, fn) {

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

line 305why, one step back
305 if (Array.isArray(name)) {

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

lines 306–308why, one step back
306 for (var i = 0; i < name.length; i++) {
307 this.param(name[i], fn);308 }

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 309–311why, one step back
309 return this;
310 }311

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

line 312why, one step back
312 this.router.param(name, fn);

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 313–344why, one step back
313 return this;
314};315316/**317 * Assign `setting` to `val`, or return `setting`'s value.318 *319 * app.set('foo', 'bar');320 * app.get('foo');321 * // => "bar"322 *323 * Mounted servers inherit their parent server's settings.324 *325 * @param {String} setting326 * @param {*} [val]327 * @return {Server} for chaining328 * @api public329 */330331app.set = function(setting, val){332 if (arguments.length === 1) {333 // app.get(setting)334 return this.settings[setting];335 }336337 // set value338 this.settings[setting] = val;339340 // trigger matched settings341 switch (setting) {342 case 'etag':343 debug('compile etag %s', val);344 this.set('etag fn', compileETag(val));

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

lines 345–348why, one step back
345 break;
346 case 'query parser':347 debug('compile query parser %s', val);348 this.set('query parser fn', compileQueryParser(val));

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 349–352why, one step back
349 break;
350 case 'trust proxy':351 debug('compile trust proxy %s', val);352 this.set('trust proxy fn', compileTrust(val));

Merge tag '4.12.0'Douglas Christopher Wilsonbefore adoptionf6ec710

lines 353–359why, one step back
353
354 // trust proxy inherit back-compat355 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {356 configurable: true,357 value: false358 });359

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 360–455why, one step back
360 break;
361 }362363 return this;364};365366/**367 * Return the app's absolute pathname368 * based on the parent(s) that have369 * mounted it.370 *371 * For example if the application was372 * mounted as "/admin", which itself373 * was mounted as "/blog" then the374 * return value would be "/blog/admin".375 *376 * @return {String}377 * @api private378 */379380app.path = function(){381 return this.parent382 ? this.parent.path() + this.mountpath383 : '';384};385386/**387 * Check if `setting` is enabled (truthy).388 *389 * app.enabled('foo')390 * // => false391 *392 * app.enable('foo')393 * app.enabled('foo')394 * // => true395 *396 * @param {String} setting397 * @return {Boolean}398 * @api public399 */400401app.enabled = function(setting){402 return !!this.set(setting);403};404405/**406 * Check if `setting` is disabled.407 *408 * app.disabled('foo')409 * // => true410 *411 * app.enable('foo')412 * app.disabled('foo')413 * // => false414 *415 * @param {String} setting416 * @return {Boolean}417 * @api public418 */419420app.disabled = function(setting){421 return !this.set(setting);422};423424/**425 * Enable `setting`.426 *427 * @param {String} setting428 * @return {app} for chaining429 * @api public430 */431432app.enable = function(setting){433 return this.set(setting, true);434};435436/**437 * Disable `setting`.438 *439 * @param {String} setting440 * @return {app} for chaining441 * @api public442 */443444app.disable = function(setting){445 return this.set(setting, false);446};447448/**449 * Delegate `.VERB(...)` calls to `router.VERB(...)`.450 */451452methods.forEach(function(method){453 app[method] = function(path){454 if ('get' == method && 1 == arguments.length) return this.set(path);455

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

line 456why, one step back
456 var route = this.route(path);

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 457why, one step back
457 route[method].apply(route, slice.call(arguments, 1));

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 458–472why, one step back
458 return this;
459 };460});461462/**463 * Special-cased "all" method, applying the given route `path`,464 * middleware, and callback to _every_ HTTP method.465 *466 * @param {String} path467 * @param {Function} ...468 * @return {app} for chaining469 * @api public470 */471472app.all = function(path){

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

line 473why, one step back
473 var route = this.route(path);

Support mounted app as any argument to app.use()Fabien Franzenbefore adoption17cea29

line 474why, one step back
474 var args = slice.call(arguments, 1);

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 475–510why, one step back
475 methods.forEach(function(method){
476 route[method].apply(route, args);477 });478479 return this;480};481482/**483 * Render the given view `name` name with `options`484 * and a callback accepting an error and the485 * rendered template string.486 *487 * Example:488 *489 * app.render('email', { name: 'Tobi' }, function(err, html){490 * // ...491 * })492 *493 * @param {String} name494 * @param {String|Function} options or fn495 * @param {Function} fn496 * @api public497 */498499app.render = function(name, options, fn){500 var opts = {};501 var cache = this.cache;502 var engines = this.engines;503 var view;504505 // support callback function as second arg506 if ('function' == typeof options) {507 fn = options, options = {};508 }509510 // merge app.locals

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 511why, one step back
511 merge(opts, this.locals);

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 512–513why, one step back
512
513 // merge options._locals

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

lines 514–516why, one step back
514 if (options._locals) {
515 merge(opts, options._locals);516 }

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 517–518why, one step back
517
518 // merge options

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 519why, one step back
519 merge(opts, options);

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 520–537why, one step back
520
521 // set .cache unless explicitly provided522 opts.cache = null == opts.cache523 ? this.enabled('view cache')524 : opts.cache;525526 // primed cache527 if (opts.cache) view = cache[name];528529 // view530 if (!view) {531 view = new (this.get('view'))(name, {532 defaultEngine: this.get('view engine'),533 root: this.get('views'),534 engines: engines535 });536537 if (!view.path) {

Add support for app.set('views', array)Douglas Christopher Wilsonbefore adoption6614352

lines 538–541why, one step back
538 var dirs = Array.isArray(view.root) && view.root.length > 1
539 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'540 : 'directory "' + view.root + '"'541 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 542–587why, one step back
542 err.view = view;
543 return fn(err);544 }545546 // prime the cache547 if (opts.cache) cache[name] = view;548 }549550 // render551 try {552 view.render(opts, fn);553 } catch (err) {554 fn(err);555 }556};557558/**559 * Listen for connections.560 *561 * A node `http.Server` is returned, with this562 * application (which is a `Function`) as its563 * callback. If you wish to create both an HTTP564 * and HTTPS server you may do so with the "http"565 * and "https" modules as shown here:566 *567 * var http = require('http')568 * , https = require('https')569 * , express = require('express')570 * , app = express();571 *572 * http.createServer(app).listen(80);573 * https.createServer({ ... }, app).listen(443);574 *575 * @return {http.Server}576 * @api public577 */578579app.listen = function(){580 var server = http.createServer(this);581 return server.listen.apply(server, arguments);582};583584/**585* Log error using console.error.586*587* @param {Error} err

Merge tag '4.11.2'Douglas Christopher Wilsonbefore adoptiona9ef9e1

line 588why, one step back
588* @api private

deps: send@0.5.0Douglas Christopher Wilsonbefore adoption3136e98

lines 589–593why, one step back
589*/
590591function logerror(err){592 if (this.get('env') !== 'test') console.error(err.stack || err.toString());593}