Skip to content
Myr

application.js

This file

Path

lib/application.js

548 lines · 11.8 KiB · JavaScript

Last changed by

Fix subapp.mountpath regression for app.use(subapp)Douglas Christopher Wilsonbefore adoption3e32721

History of this file

Take 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 back
1/**
2 * Module dependencies.3 */4

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

line 5why, one step back
5var finalhandler = require('finalhandler');

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 6–13why, one step back
6var 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 back
14var compileETag = require('./utils').compileETag;

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

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

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

line 16why, one step back
16var deprecate = require('depd')('express');

Use path.resolve for views dir instead of concatNick Heinerbefore adoption253ce48

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

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 18–50why, one step back
18
19/**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 back
51 this.set('etag', 'weak');

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 52–54why, one step back
52 var env = process.env.NODE_ENV || 'development';
53 this.set('env', env);54 this.set('subdomain offset', 2);

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 55why, one step back
55 this.set('trust proxy', false);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 56–77why, one step back
56
57 debug('booting in %s mode', env);5859 // 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 locals68 this.locals = Object.create(null);6970 // top-most app is mounted at /71 this.mountpath = '/';7273 // 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 back
78 this.set('views', resolve('views'));

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 79–106why, one step back
79 this.set('jsonp callback name', 'callback');
8081 if (env === 'production') {82 this.enable('view cache');83 }8485 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 });90};9192/**93 * lazily adds the base router if it has not yet been added.94 *95 * 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 });106

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

line 107why, one step back
107 this._router.use(query());

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 108–121why, one step back
108 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 back
122 var router = this._router;
123

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 124–127why, one step back
124 // final handler
125 done = done || finalhandler(req, res, {126 env: this.get('env'),127 onerror: logerror.bind(this)

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 128why, one step back
128 });

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

line 129why, one step back
129

fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288

lines 130–137why, one step back
130 // no routes
131 if (!router) {132 debug('no routes defined on app');133 done();134 return;135 }136137 router.handle(req, res, done);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 138–149why, one step back
138};
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 *147 * @api public148 */149

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

line 150why, one step back
150app.use = function use(path, fn) {

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 151why, one step back
151 var mount_app;

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

line 152why, one step back
152 var mount_path;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 153why, one step back
153

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

lines 154–161why, one step back
154 // check for .use(path, app) or .use(app) signature
155 if (arguments.length <= 2) {156 mount_path = typeof path === 'string'157 ? path158 : '/';159 mount_app = typeof path === 'function'160 ? path161 : fn;

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

line 162why, one step back
162 }

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 163why, one step back
163

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

lines 164–166why, one step back
164 // setup router
165 this.lazyrouter();166 var router = this._router;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 167why, one step back
167

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

lines 168–170why, one step back
168 // express app
169 if (mount_app && mount_app.handle && mount_app.set) {170 debug('.use app under %s', mount_path);

Fix subapp.mountpath regression for app.use(subapp)Douglas Christopher Wilsonbefore adoption3e32721

line 171why, one step back
171 mount_app.mountpath = mount_path;

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

lines 172–175why, one step back
172 mount_app.parent = this;
173174 // restore .app property on req and res175 router.use(mount_path, function mounted_app(req, res, next) {

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 176–181why, one step back
176 var orig = req.app;
177 mount_app.handle(req, res, function(err) {178 req.__proto__ = orig.request;179 res.__proto__ = orig.response;180 next(err);181 });

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

line 182why, one step back
182 });

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 183why, one step back
183

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

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

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 185why, one step back
185 mount_app.emit('mount', this);

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

lines 186–187why, one step back
186
187 return this;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 188why, one step back
188 }

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

lines 189–191why, one step back
189
190 // pass-through use191 router.use.apply(router, arguments);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 192–206why, one step back
192
193 return this;194};195196/**197 * Proxy to the app `Router#route()`198 * Returns a new `Route` instance for the _path_.199 *200 * Routes are isolated middleware stacks for specific paths.201 * See the Route api docs for details.202 *203 * @api public204 */205206app.route = function(path){

implement app.route()Roman Shtylmanbefore adoption0719e5f

lines 207–208why, one step back
207 this.lazyrouter();
208 return this._router.route(path);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 209–294why, one step back
209};
210211/**212 * Register the given template engine callback `fn`213 * as `ext`.214 *215 * By default will `require()` the engine based on the216 * file extension. For example if you try to render217 * a "foo.jade" file Express will invoke the following internally:218 *219 * app.engine('jade', require('jade').__express);220 *221 * For engines that do not provide `.__express` out of the box,222 * or if you wish to "map" a different extension to the template engine223 * you may use this method. For example mapping the EJS template engine to224 * ".html" files:225 *226 * app.engine('html', require('ejs').renderFile);227 *228 * In this case EJS provides a `.renderFile()` method with229 * the same signature that Express expects: `(path, options, callback)`,230 * though note that it aliases this method as `ejs.__express` internally231 * so if you're using ".ejs" extensions you dont need to do anything.232 *233 * Some template engines do not follow this convention, the234 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)235 * library was created to map all of node's popular template236 * engines to follow this convention, thus allowing them to237 * work seamlessly within Express.238 *239 * @param {String} ext240 * @param {Function} fn241 * @return {app} for chaining242 * @api public243 */244245app.engine = function(ext, fn){246 if ('function' != typeof fn) throw new Error('callback function required');247 if ('.' != ext[0]) ext = '.' + ext;248 this.engines[ext] = fn;249 return this;250};251252/**253 * Proxy to `Router#param()` with one added api feature. The _name_ parameter254 * can be an array of names.255 *256 * See the Router#param() docs for more details.257 *258 * @param {String|Array} name259 * @param {Function} fn260 * @return {app} for chaining261 * @api public262 */263264app.param = function(name, fn){265 var self = this;266 self.lazyrouter();267268 if (Array.isArray(name)) {269 name.forEach(function(key) {270 self.param(key, fn);271 });272 return this;273 }274275 self._router.param(name, fn);276 return this;277};278279/**280 * Assign `setting` to `val`, or return `setting`'s value.281 *282 * app.set('foo', 'bar');283 * app.get('foo');284 * // => "bar"285 *286 * Mounted servers inherit their parent server's settings.287 *288 * @param {String} setting289 * @param {*} [val]290 * @return {Server} for chaining291 * @api public292 */293294app.set = function(setting, val){

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 295–296why, one step back
295 if (arguments.length === 1) {
296 // app.get(setting)

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 297why, one step back
297 return this.settings[setting];

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 298why, one step back
298 }

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 299why, one step back
299

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 300–301why, one step back
300 // set value
301 this.settings[setting] = val;

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 302why, one step back
302

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 303–312why, one step back
303 // trigger matched settings
304 switch (setting) {305 case 'etag':306 debug('compile etag %s', val);307 this.set('etag fn', compileETag(val));308 break;309 case 'trust proxy':310 debug('compile trust proxy %s', val);311 this.set('trust proxy fn', compileTrust(val));312 break;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 313why, one step back
313 }

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 314–315why, one step back
314
315 return this;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 316–405why, one step back
316};
317318/**319 * Return the app's absolute pathname320 * based on the parent(s) that have321 * mounted it.322 *323 * For example if the application was324 * mounted as "/admin", which itself325 * was mounted as "/blog" then the326 * return value would be "/blog/admin".327 *328 * @return {String}329 * @api private330 */331332app.path = function(){333 return this.parent334 ? this.parent.path() + this.mountpath335 : '';336};337338/**339 * Check if `setting` is enabled (truthy).340 *341 * app.enabled('foo')342 * // => false343 *344 * app.enable('foo')345 * app.enabled('foo')346 * // => true347 *348 * @param {String} setting349 * @return {Boolean}350 * @api public351 */352353app.enabled = function(setting){354 return !!this.set(setting);355};356357/**358 * Check if `setting` is disabled.359 *360 * app.disabled('foo')361 * // => true362 *363 * app.enable('foo')364 * app.disabled('foo')365 * // => false366 *367 * @param {String} setting368 * @return {Boolean}369 * @api public370 */371372app.disabled = function(setting){373 return !this.set(setting);374};375376/**377 * Enable `setting`.378 *379 * @param {String} setting380 * @return {app} for chaining381 * @api public382 */383384app.enable = function(setting){385 return this.set(setting, true);386};387388/**389 * Disable `setting`.390 *391 * @param {String} setting392 * @return {app} for chaining393 * @api public394 */395396app.disable = function(setting){397 return this.set(setting, false);398};399400/**401 * Delegate `.VERB(...)` calls to `router.VERB(...)`.402 */403404methods.forEach(function(method){405 app[method] = function(path){

Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916

line 406why, one step back
406 if ('get' == method && 1 == arguments.length) return this.set(path);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 407why, one step back
407

Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916

lines 408–410why, one step back
408 this.lazyrouter();
409410 var route = this._router.route(path);

support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854

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

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 412–426why, one step back
412 return this;
413 };414});415416/**417 * Special-cased "all" method, applying the given route `path`,418 * middleware, and callback to _every_ HTTP method.419 *420 * @param {String} path421 * @param {Function} ...422 * @return {app} for chaining423 * @api public424 */425426app.all = function(path){

Revert "fix behavior of multiple app.VERB for the same path"Douglas Christopher Wilsonbefore adoption7f04916

lines 427–429why, one step back
427 this.lazyrouter();
428429 var route = this._router.route(path);

support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854

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

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

line 431why, one step back
431 methods.forEach(function(method){

support arrays as middleware arguments to .VERB and .allRoman Shtylmanbefore adoption1eba854

line 432why, one step back
432 route[method].apply(route, args);

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 433–439why, one step back
433 });
434435 return this;436};437438// del -> delete alias439

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

line 440why, one step back
440app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 441–459why, one step back
441
442/**443 * Render the given view `name` name with `options`444 * and a callback accepting an error and the445 * rendered template string.446 *447 * Example:448 *449 * app.render('email', { name: 'Tobi' }, function(err, html){450 * // ...451 * })452 *453 * @param {String} name454 * @param {String|Function} options or fn455 * @param {Function} fn456 * @api public457 */458459app.render = function(name, options, fn){

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 460–463why, one step back
460 var opts = {};
461 var cache = this.cache;462 var engines = this.engines;463 var view;

move `connect.query()` into our repoRoman Shtylmanbefore adoption9bc63d9

lines 464–537why, one step back
464
465 // support callback function as second arg466 if ('function' == typeof options) {467 fn = options, options = {};468 }469470 // merge app.locals471 mixin(opts, this.locals);472473 // merge options._locals474 if (options._locals) mixin(opts, options._locals);475476 // merge options477 mixin(opts, options);478479 // set .cache unless explicitly provided480 opts.cache = null == opts.cache481 ? this.enabled('view cache')482 : opts.cache;483484 // primed cache485 if (opts.cache) view = cache[name];486487 // view488 if (!view) {489 view = new (this.get('view'))(name, {490 defaultEngine: this.get('view engine'),491 root: this.get('views'),492 engines: engines493 });494495 if (!view.path) {496 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');497 err.view = view;498 return fn(err);499 }500501 // prime the cache502 if (opts.cache) cache[name] = view;503 }504505 // render506 try {507 view.render(opts, fn);508 } catch (err) {509 fn(err);510 }511};512513/**514 * Listen for connections.515 *516 * A node `http.Server` is returned, with this517 * application (which is a `Function`) as its518 * callback. If you wish to create both an HTTP519 * and HTTPS server you may do so with the "http"520 * and "https" modules as shown here:521 *522 * var http = require('http')523 * , https = require('https')524 * , express = require('express')525 * , app = express();526 *527 * http.createServer(app).listen(80);528 * https.createServer({ ... }, app).listen(443);529 *530 * @return {http.Server}531 * @api public532 */533534app.listen = function(){535 var server = http.createServer(this);536 return server.listen.apply(server, arguments);537};

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 538–548why, one step back
538
539/**540* Log error using console.error.541*542* @param {Error} err543* @api public544*/545546function logerror(err){547 if (this.get('env') !== 'test') console.error(err.stack || err.toString());548}