Skip to content
Myr

application.js

This file

Path

lib/application.js

541 lines · 12.1 KiB · JavaScript

Last changed by

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

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–49why, 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(){34 this.cache = {};35 this.settings = {};36 this.engines = {};37 this.defaultConfiguration();38};3940/**41 * Initialize application configuration.42 *43 * @api private44 */4546app.defaultConfiguration = function(){47 // default settings48 this.enable('x-powered-by');49 this.enable('etag');

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

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

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

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

update connectTJ Holowaychukbefore adoption929ffb8

line 54why, one step back
54

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 56–65why, one step back
56
57 // inherit protos58 this.on('mount', function(parent){59 this.request.__proto__ = parent.request;60 this.response.__proto__ = parent.response;61 this.engines.__proto__ = parent.engines;62 this.settings.__proto__ = parent.settings;63 });6465 // setup locals

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

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

update connectTJ Holowaychukbefore adoption929ffb8

line 67why, one step back
67

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 71–78why, one step back
71 // default locals
72 this.locals.settings = this.settings;7374 // default configuration75 this.set('view', View);76 this.set('views', process.cwd() + '/views');77 this.set('jsonp callback name', 'callback');78

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

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

Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0

line 81why, one step back
81 }

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 88–90why, one step back
88};
8990/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

line 92why, one step back
92 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 106–143why, one step back
106 this._router.use(middleware.init(this));
107 }108};109110/**111 * Dispatch a req, res pair into the application. Starts pipeline processing.112 *113 * If no _done_ callback is provided, then default error handlers will respond114 * in the event of an error bubbling through the stack.115 *116 * @api private117 */118119app.handle = function(req, res, done) {120 var env = this.get('env');121122 this._router.handle(req, res, function(err) {123 if (done) {124 return done(err);125 }126127 // unhandled error128 if (err) {129 // default to 500130 if (res.statusCode < 400) res.statusCode = 500;131 debug('default %s', res.statusCode);132133 // respect err.status134 if (err.status) res.statusCode = err.status;135136 // production gets a basic error message137 var msg = 'production' == env138 ? http.STATUS_CODES[res.statusCode]139 : err.stack || err.toString();140 msg = escapeHtml(msg);141142 // log to stderr in a non-test env143 if ('test' != env) console.error(err.stack || err.toString());

remove ServerResonse.headerSent monkey patchRoman Shtylmanbefore adoption6835289

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 168–174why, one step back
168 * @param {String|Function|Server} route
169 * @param {Function|Server} fn170 * @return {app} for chaining171 * @api public172 */173174app.use = function(route, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 175why, one step back
175 var mount_app;

update connectTJ Holowaychukbefore adoption929ffb8

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 204–209why, one step back
204 }
205206 return this;207};208209/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

implement app.route()Roman Shtylmanbefore adoption0719e5f

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 222–224why, one step back
222};
223224/**

update connectTJ Holowaychukbefore adoption929ffb8

lines 225–265why, one step back
225 * Register the given template engine callback `fn`
226 * as `ext`.227 *228 * By default will `require()` the engine based on the229 * file extension. For example if you try to render230 * a "foo.jade" file Express will invoke the following internally:231 *232 * app.engine('jade', require('jade').__express);233 *234 * For engines that do not provide `.__express` out of the box,235 * or if you wish to "map" a different extension to the template engine236 * you may use this method. For example mapping the EJS template engine to237 * ".html" files:238 *239 * app.engine('html', require('ejs').renderFile);240 *241 * In this case EJS provides a `.renderFile()` method with242 * the same signature that Express expects: `(path, options, callback)`,243 * though note that it aliases this method as `ejs.__express` internally244 * so if you're using ".ejs" extensions you dont need to do anything.245 *246 * Some template engines do not follow this convention, the247 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)248 * library was created to map all of node's popular template249 * engines to follow this convention, thus allowing them to250 * work seamlessly within Express.251 *252 * @param {String} ext253 * @param {Function} fn254 * @return {app} for chaining255 * @api public256 */257258app.engine = function(ext, fn){259 if ('function' != typeof fn) throw new Error('callback function required');260 if ('.' != ext[0]) ext = '.' + ext;261 this.engines[ext] = fn;262 return this;263};264265/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

line 268why, one step back
268 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 270–277why, one step back
270 *
271 * @param {String|Array} name272 * @param {Function} fn273 * @return {app} for chaining274 * @api public275 */276277app.param = function(name, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

line 284why, one step back
284 });

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 285why, one step back
285 return this;

update connectTJ Holowaychukbefore adoption929ffb8

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

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

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

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

update connectTJ Holowaychukbefore adoption929ffb8

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

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 318–337why, one step back
318 return this;
319 }320};321322/**323 * Return the app's absolute pathname324 * based on the parent(s) that have325 * mounted it.326 *327 * For example if the application was328 * mounted as "/admin", which itself329 * was mounted as "/blog" then the330 * return value would be "/blog/admin".331 *332 * @return {String}333 * @api private334 */335336app.path = function(){337 return this.parent

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 339–409why, one step back
339 : '';
340};341342/**343 * Check if `setting` is enabled (truthy).344 *345 * app.enabled('foo')346 * // => false347 *348 * app.enable('foo')349 * app.enabled('foo')350 * // => true351 *352 * @param {String} setting353 * @return {Boolean}354 * @api public355 */356357app.enabled = function(setting){358 return !!this.set(setting);359};360361/**362 * Check if `setting` is disabled.363 *364 * app.disabled('foo')365 * // => true366 *367 * app.enable('foo')368 * app.disabled('foo')369 * // => false370 *371 * @param {String} setting372 * @return {Boolean}373 * @api public374 */375376app.disabled = function(setting){377 return !this.set(setting);378};379380/**381 * Enable `setting`.382 *383 * @param {String} setting384 * @return {app} for chaining385 * @api public386 */387388app.enable = function(setting){389 return this.set(setting, true);390};391392/**393 * Disable `setting`.394 *395 * @param {String} setting396 * @return {app} for chaining397 * @api public398 */399400app.disable = function(setting){401 return this.set(setting, false);402};403404/**405 * Delegate `.VERB(...)` calls to `router.VERB(...)`.406 */407408methods.forEach(function(method){409 app[method] = function(path){

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

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

update connectTJ Holowaychukbefore adoption929ffb8

line 411why, one step back
411

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

lines 412–414why, one step back
412 this.lazyrouter();
413414 var route = this._router.route(path);

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

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 416–430why, one step back
416 return this;
417 };418});419420/**421 * Special-cased "all" method, applying the given route `path`,422 * middleware, and callback to _every_ HTTP method.423 *424 * @param {String} path425 * @param {Function} ...426 * @return {app} for chaining427 * @api public428 */429430app.all = function(path){

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

lines 431–433why, one step back
431 this.lazyrouter();
432433 var route = this._router.route(path);

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

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

update connectTJ Holowaychukbefore adoption929ffb8

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

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

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 439–443why, one step back
439 return this;
440};441442// del -> delete alias443

Merge tag '3.6.0'Douglas Christopher Wilsonbefore adoption35c5060

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 445–463why, one step back
445
446/**447 * Render the given view `name` name with `options`448 * and a callback accepting an error and the449 * rendered template string.450 *451 * Example:452 *453 * app.render('email', { name: 'Tobi' }, function(err, html){454 * // ...455 * })456 *457 * @param {String} name458 * @param {String|Function} options or fn459 * @param {Function} fn460 * @api public461 */462463app.render = function(name, options, fn){

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

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 468–474why, one step back
468
469 // support callback function as second arg470 if ('function' == typeof options) {471 fn = options, options = {};472 }473474 // merge app.locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

update connectTJ Holowaychukbefore adoption929ffb8

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

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

update connectTJ Holowaychukbefore adoption929ffb8

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

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 482–499why, one step back
482
483 // set .cache unless explicitly provided484 opts.cache = null == opts.cache485 ? this.enabled('view cache')486 : opts.cache;487488 // primed cache489 if (opts.cache) view = cache[name];490491 // view492 if (!view) {493 view = new (this.get('view'))(name, {494 defaultEngine: this.get('view engine'),495 root: this.get('views'),496 engines: engines497 });498499 if (!view.path) {

Merge pull request #1869 from yamatt/masterTJ Holowaychukbefore adoption72daae1

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

update connectTJ Holowaychukbefore adoption929ffb8

lines 501–541why, one step back
501 err.view = view;
502 return fn(err);503 }504505 // prime the cache506 if (opts.cache) cache[name] = view;507 }508509 // render510 try {511 view.render(opts, fn);512 } catch (err) {513 fn(err);514 }515};516517/**518 * Listen for connections.519 *520 * A node `http.Server` is returned, with this521 * application (which is a `Function`) as its522 * callback. If you wish to create both an HTTP523 * and HTTPS server you may do so with the "http"524 * and "https" modules as shown here:525 *526 * var http = require('http')527 * , https = require('https')528 * , express = require('express')529 * , app = express();530 *531 * http.createServer(app).listen(80);532 * https.createServer({ ... }, app).listen(443);533 *534 * @return {http.Server}535 * @api public536 */537538app.listen = function(){539 var server = http.createServer(this);540 return server.listen.apply(server, arguments);541};