Skip to content
Myr

application.js

This file

Path

lib/application.js

569 lines · 12.6 KiB · JavaScript

Last changed by

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

History of this file

Take it

The walk stopped after 200 commits: lines older than 929ffb8 point at it.

update connectTJ Holowaychukbefore adoption929ffb8

lines 1–4why, one step back
1/**
2 * Module dependencies.3 */4

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

lines 5–13why, one step back
5var mixin = require('utils-merge');
6var escapeHtml = require('escape-html');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.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

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

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 16–33why, one step back
16
17/**18 * Application prototype.19 */2021var app = exports = module.exports = {};2223/**24 * Initialize the server.25 *26 * - setup default configuration27 * - setup default middleware28 * - setup route reflection methods29 *30 * @api private31 */3233app.init = function(){

fix behavior of multiple app.VERB for the same pathDouglas Christopher Wilsonbefore adoption31b2e2d

line 34why, one step back
34 this._baseRoutes = {};

update connectTJ Holowaychukbefore adoption929ffb8

lines 35–50why, one step back
35 this.cache = {};
36 this.settings = {};37 this.engines = {};38 this.defaultConfiguration();39};4041/**42 * Initialize application configuration.43 *44 * @api private45 */4647app.defaultConfiguration = function(){48 // default settings49 this.enable('x-powered-by');50 this.enable('etag');

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 51–52why, one step back
51 var env = process.env.NODE_ENV || 'development';
52 this.set('env', env);

update connectTJ Holowaychukbefore adoption929ffb8

line 53why, one step back
53 this.set('subdomain offset', 2);

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

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

update connectTJ Holowaychukbefore adoption929ffb8

line 55why, one step back
55

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 56why, one step back
56 debug('booting in %s mode', env);

update connectTJ Holowaychukbefore adoption929ffb8

lines 57–66why, one step back
57
58 // inherit protos59 this.on('mount', function(parent){60 this.request.__proto__ = parent.request;61 this.response.__proto__ = parent.response;62 this.engines.__proto__ = parent.engines;63 this.settings.__proto__ = parent.settings;64 });6566 // setup locals

Merge pull request #1908 from visionmedia/locals-objectRoman Shtylmanbefore adoption991c2a9

line 67why, one step back
67 this.locals = Object.create(null);

update connectTJ Holowaychukbefore adoption929ffb8

line 68why, one step back
68

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 69–71why, one step back
69 // top-most app is mounted at /
70 this.mountpath = '/';71

update connectTJ Holowaychukbefore adoption929ffb8

lines 72–79why, one step back
72 // default locals
73 this.locals.settings = this.settings;7475 // default configuration76 this.set('view', View);77 this.set('views', process.cwd() + '/views');78 this.set('jsonp callback name', 'callback');79

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 80why, one step back
80 if (env === 'production') {

update connectTJ Holowaychukbefore adoption929ffb8

line 81why, one step back
81 this.enable('view cache');

Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0

line 82why, one step back
82 }

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 83–88why, one step back
83
84 Object.defineProperty(this, 'router', {85 get: function() {86 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.');87 }88 });

update connectTJ Holowaychukbefore adoption929ffb8

lines 89–91why, one step back
89};
9091/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 92why, one step back
92 * lazily adds the base router if it has not yet been added.

update connectTJ Holowaychukbefore adoption929ffb8

line 93why, one step back
93 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 94–105why, one step back
94 * We cannot add the base router in the defaultConfiguration because
95 * it reads app settings which might be set after that has run.96 *97 * @api private98 */99app.lazyrouter = function() {100 if (!this._router) {101 this._router = new Router({102 caseSensitive: this.enabled('case sensitive routing'),103 strict: this.enabled('strict routing')104 });105

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 107–144why, one step back
107 this._router.use(middleware.init(this));
108 }109};110111/**112 * Dispatch a req, res pair into the application. Starts pipeline processing.113 *114 * If no _done_ callback is provided, then default error handlers will respond115 * in the event of an error bubbling through the stack.116 *117 * @api private118 */119120app.handle = function(req, res, done) {121 var env = this.get('env');122123 this._router.handle(req, res, function(err) {124 if (done) {125 return done(err);126 }127128 // unhandled error129 if (err) {130 // default to 500131 if (res.statusCode < 400) res.statusCode = 500;132 debug('default %s', res.statusCode);133134 // respect err.status135 if (err.status) res.statusCode = err.status;136137 // production gets a basic error message138 var msg = 'production' == env139 ? http.STATUS_CODES[res.statusCode]140 : err.stack || err.toString();141 msg = escapeHtml(msg);142143 // log to stderr in a non-test env144 if ('test' != env) console.error(err.stack || err.toString());

remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289

line 145why, one step back
145 if (res.headersSent) return req.socket.destroy();

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 146–168why, one step back
146 res.setHeader('Content-Type', 'text/html');
147 res.setHeader('Content-Length', Buffer.byteLength(msg));148 if ('HEAD' == req.method) return res.end();149 res.end(msg);150 return;151 }152153 // 404154 debug('default 404');155 res.statusCode = 404;156 res.setHeader('Content-Type', 'text/html');157 if ('HEAD' == req.method) return res.end();158 res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');159 });160};161162/**163 * Proxy `Router#use()` to add middleware to the app router.164 * See Router#use() documentation for details.165 *166 * If the _fn_ parameter is an express app, then it will be167 * mounted at the _route_ specified.168 *

update connectTJ Holowaychukbefore adoption929ffb8

lines 169–175why, one step back
169 * @param {String|Function|Server} route
170 * @param {Function|Server} fn171 * @return {app} for chaining172 * @api public173 */174175app.use = function(route, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 176why, one step back
176 var mount_app;

update connectTJ Holowaychukbefore adoption929ffb8

lines 177–181why, one step back
177
178 // default route to '/'179 if ('string' != typeof route) fn = route, route = '/';180181 // express app

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 182why, one step back
182 if (fn.handle && fn.set) mount_app = fn;

update connectTJ Holowaychukbefore adoption929ffb8

lines 183–184why, one step back
183
184 // restore .app property on req and res

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 185–187why, one step back
185 if (mount_app) {
186 debug('.use app under %s', route);187 mount_app.mountpath = route;

update connectTJ Holowaychukbefore adoption929ffb8

lines 188–189why, one step back
188 fn = function(req, res, next) {
189 var orig = req.app;

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 190why, one step back
190 mount_app.handle(req, res, function(err) {

update connectTJ Holowaychukbefore adoption929ffb8

lines 191–197why, one step back
191 req.__proto__ = orig.request;
192 res.__proto__ = orig.response;193 next(err);194 });195 };196 }197

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 198–199why, one step back
198 this.lazyrouter();
199 this._router.use(route, fn);

update connectTJ Holowaychukbefore adoption929ffb8

lines 200–201why, one step back
200
201 // mounted an app

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 202–204why, one step back
202 if (mount_app) {
203 mount_app.parent = this;204 mount_app.emit('mount', this);

update connectTJ Holowaychukbefore adoption929ffb8

lines 205–210why, one step back
205 }
206207 return this;208};209210/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 211–220why, one step back
211 * Proxy to the app `Router#route()`
212 * Returns a new `Route` instance for the _path_.213 *214 * Routes are isolated middleware stacks for specific paths.215 * See the Route api docs for details.216 *217 * @api public218 */219220app.route = function(path){

implement app.route()Roman Shtylmanbefore adoption0719e5f

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 223–225why, one step back
223};
224225/**

update connectTJ Holowaychukbefore adoption929ffb8

lines 226–266why, one step back
226 * Register the given template engine callback `fn`
227 * as `ext`.228 *229 * By default will `require()` the engine based on the230 * file extension. For example if you try to render231 * a "foo.jade" file Express will invoke the following internally:232 *233 * app.engine('jade', require('jade').__express);234 *235 * For engines that do not provide `.__express` out of the box,236 * or if you wish to "map" a different extension to the template engine237 * you may use this method. For example mapping the EJS template engine to238 * ".html" files:239 *240 * app.engine('html', require('ejs').renderFile);241 *242 * In this case EJS provides a `.renderFile()` method with243 * the same signature that Express expects: `(path, options, callback)`,244 * though note that it aliases this method as `ejs.__express` internally245 * so if you're using ".ejs" extensions you dont need to do anything.246 *247 * Some template engines do not follow this convention, the248 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)249 * library was created to map all of node's popular template250 * engines to follow this convention, thus allowing them to251 * work seamlessly within Express.252 *253 * @param {String} ext254 * @param {Function} fn255 * @return {app} for chaining256 * @api public257 */258259app.engine = function(ext, fn){260 if ('function' != typeof fn) throw new Error('callback function required');261 if ('.' != ext[0]) ext = '.' + ext;262 this.engines[ext] = fn;263 return this;264};265266/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 267–268why, one step back
267 * Proxy to `Router#param()` with one added api feature. The _name_ parameter
268 * can be an array of names.

update connectTJ Holowaychukbefore adoption929ffb8

line 269why, one step back
269 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 270why, one step back
270 * See the Router#param() docs for more details.

update connectTJ Holowaychukbefore adoption929ffb8

lines 271–278why, one step back
271 *
272 * @param {String|Array} name273 * @param {Function} fn274 * @return {app} for chaining275 * @api public276 */277278app.param = function(name, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 279–280why, one step back
279 var self = this;
280 self.lazyrouter();

update connectTJ Holowaychukbefore adoption929ffb8

lines 281–282why, one step back
281
282 if (Array.isArray(name)) {

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 283–284why, one step back
283 name.forEach(function(key) {
284 self.param(key, fn);

update connectTJ Holowaychukbefore adoption929ffb8

line 285why, one step back
285 });

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 286why, one step back
286 return this;

update connectTJ Holowaychukbefore adoption929ffb8

lines 287–288why, one step back
287 }
288

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 289why, one step back
289 self._router.param(name, fn);

update connectTJ Holowaychukbefore adoption929ffb8

lines 290–302why, one step back
290 return this;
291};292293/**294 * Assign `setting` to `val`, or return `setting`'s value.295 *296 * app.set('foo', 'bar');297 * app.get('foo');298 * // => "bar"299 *300 * Mounted servers inherit their parent server's settings.301 *302 * @param {String} setting

Merge pull request #1890 from oliversalzburg/patch-1TJ Holowaychukbefore adoption827dfed

line 303why, one step back
303 * @param {*} [val]

update connectTJ Holowaychukbefore adoption929ffb8

lines 304–312why, one step back
304 * @return {Server} for chaining
305 * @api public306 */307308app.set = function(setting, val){309 if (1 == arguments.length) {310 return this.settings[setting];311 } else {312 this.settings[setting] = val;

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

lines 313–318why, one step back
313
314 if (setting === 'trust proxy') {315 debug('compile trust proxy %j', val);316 this.set('trust proxy fn', compileTrust(val));317 }318

update connectTJ Holowaychukbefore adoption929ffb8

lines 319–338why, one step back
319 return this;
320 }321};322323/**324 * Return the app's absolute pathname325 * based on the parent(s) that have326 * mounted it.327 *328 * For example if the application was329 * mounted as "/admin", which itself330 * was mounted as "/blog" then the331 * return value would be "/blog/admin".332 *333 * @return {String}334 * @api private335 */336337app.path = function(){338 return this.parent

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 339why, one step back
339 ? this.parent.path() + this.mountpath

update connectTJ Holowaychukbefore adoption929ffb8

lines 340–410why, one step back
340 : '';
341};342343/**344 * Check if `setting` is enabled (truthy).345 *346 * app.enabled('foo')347 * // => false348 *349 * app.enable('foo')350 * app.enabled('foo')351 * // => true352 *353 * @param {String} setting354 * @return {Boolean}355 * @api public356 */357358app.enabled = function(setting){359 return !!this.set(setting);360};361362/**363 * Check if `setting` is disabled.364 *365 * app.disabled('foo')366 * // => true367 *368 * app.enable('foo')369 * app.disabled('foo')370 * // => false371 *372 * @param {String} setting373 * @return {Boolean}374 * @api public375 */376377app.disabled = function(setting){378 return !this.set(setting);379};380381/**382 * Enable `setting`.383 *384 * @param {String} setting385 * @return {app} for chaining386 * @api public387 */388389app.enable = function(setting){390 return this.set(setting, true);391};392393/**394 * Disable `setting`.395 *396 * @param {String} setting397 * @return {app} for chaining398 * @api public399 */400401app.disable = function(setting){402 return this.set(setting, false);403};404405/**406 * Delegate `.VERB(...)` calls to `router.VERB(...)`.407 */408409methods.forEach(function(method){410 app[method] = function(path){

fix behavior of multiple app.VERB for the same pathDouglas Christopher Wilsonbefore adoption31b2e2d

lines 411–413why, one step back
411 if (method === 'get' && arguments.length === 1) {
412 return this.set(path);413 }

update connectTJ Holowaychukbefore adoption929ffb8

line 414why, one step back
414

fix behavior of multiple app.VERB for the same pathDouglas Christopher Wilsonbefore adoption31b2e2d

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

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

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 417–431why, one step back
417 return this;
418 };419});420421/**422 * Special-cased "all" method, applying the given route `path`,423 * middleware, and callback to _every_ HTTP method.424 *425 * @param {String} path426 * @param {Function} ...427 * @return {app} for chaining428 * @api public429 */430431app.all = function(path){

fix behavior of multiple app.VERB for the same pathDouglas Christopher Wilsonbefore adoption31b2e2d

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

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

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

update connectTJ Holowaychukbefore adoption929ffb8

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

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

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 436–437why, one step back
436 });
437

update connectTJ Holowaychukbefore adoption929ffb8

lines 438–442why, one step back
438 return this;
439};440441// del -> delete alias442

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 444–462why, one step back
444
445/**446 * Render the given view `name` name with `options`447 * and a callback accepting an error and the448 * rendered template string.449 *450 * Example:451 *452 * app.render('email', { name: 'Tobi' }, function(err, html){453 * // ...454 * })455 *456 * @param {String} name457 * @param {String|Function} options or fn458 * @param {Function} fn459 * @api public460 */461462app.render = function(name, options, fn){

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

lines 463–466why, one step back
463 var opts = {};
464 var cache = this.cache;465 var engines = this.engines;466 var view;

update connectTJ Holowaychukbefore adoption929ffb8

lines 467–473why, one step back
467
468 // support callback function as second arg469 if ('function' == typeof options) {470 fn = options, options = {};471 }472473 // merge app.locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 474why, one step back
474 mixin(opts, this.locals);

update connectTJ Holowaychukbefore adoption929ffb8

lines 475–476why, one step back
475
476 // merge options._locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 477why, one step back
477 if (options._locals) mixin(opts, options._locals);

update connectTJ Holowaychukbefore adoption929ffb8

lines 478–479why, one step back
478
479 // merge options

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

line 480why, one step back
480 mixin(opts, options);

update connectTJ Holowaychukbefore adoption929ffb8

lines 481–498why, one step back
481
482 // set .cache unless explicitly provided483 opts.cache = null == opts.cache484 ? this.enabled('view cache')485 : opts.cache;486487 // primed cache488 if (opts.cache) view = cache[name];489490 // view491 if (!view) {492 view = new (this.get('view'))(name, {493 defaultEngine: this.get('view engine'),494 root: this.get('views'),495 engines: engines496 });497498 if (!view.path) {

Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1

line 499why, one step back
499 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');

update connectTJ Holowaychukbefore adoption929ffb8

lines 500–539why, one step back
500 err.view = view;
501 return fn(err);502 }503504 // prime the cache505 if (opts.cache) cache[name] = view;506 }507508 // render509 try {510 view.render(opts, fn);511 } catch (err) {512 fn(err);513 }514};515516/**517 * Listen for connections.518 *519 * A node `http.Server` is returned, with this520 * application (which is a `Function`) as its521 * callback. If you wish to create both an HTTP522 * and HTTPS server you may do so with the "http"523 * and "https" modules as shown here:524 *525 * var http = require('http')526 * , https = require('https')527 * , express = require('express')528 * , app = express();529 *530 * http.createServer(app).listen(80);531 * https.createServer({ ... }, app).listen(443);532 *533 * @return {http.Server}534 * @api public535 */536537app.listen = function(){538 var server = http.createServer(this);539 return server.listen.apply(server, arguments);

fix behavior of multiple app.VERB for the same pathDouglas Christopher Wilsonbefore adoption31b2e2d

lines 540–568why, one step back
540};
541542/**543 * Get or create a new base route for path.544 *545 * @param {String} path546 * @return {Route}547 * @api private548 */549550app._baseRoute = function(path){551 this.lazyrouter();552553 var key = typeof path !== 'string'554 ? 'o:' + String(path)555 : 's:' + path;556557 if (path.ignoreCase || !this._router.caseSensitive) {558 key = 'i' + key.toLowerCase();559 }560561 var route = this._baseRoutes[key];562563 if (!route) {564 route = this._router.route(path);565 this._baseRoutes[key] = route;566 }567568 return route;

update connectTJ Holowaychukbefore adoption929ffb8

line 569why, one step back
569};