Skip to content
Myr

application.js

This file

Path

lib/application.js

537 lines · 11.6 KiB · JavaScript

Last changed by

fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288

History of this file

Take it

The walk stopped after 200 commits: lines older than 5ddbb69 point at it.

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

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;

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

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');

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

line 54why, one step back
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);

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

line 56why, one step back
56

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 58–67why, one step back
58
59 // 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 locals

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

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

line 69why, one step back
69

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 73–77why, one step back
73 // default locals
74 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'));

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 79–80why, one step back
79 this.set('jsonp callback name', 'callback');
80

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

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

Merge pull request #1904 from popomore/masterRoman Shtylmanbefore adoptionb77ffe0

line 83why, one step back
83 }

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 84–89why, one step back
84
85 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 });

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 90–92why, one step back
90};
9192/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

line 94why, one step back
94 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 95–106why, one step back
95 * We cannot add the base router in the defaultConfiguration because
96 * 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());

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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)

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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);

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 138–146why, 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 *

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 147–150why, one step back
147 * @api public
148 */149150app.use = function(route, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 151why, one step back
151 var mount_app;

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 152–156why, one step back
152
153 // default route to '/'154 if ('string' != typeof route) fn = route, route = '/';155156 // express app

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 166–172why, one step back
166 req.__proto__ = orig.request;
167 res.__proto__ = orig.response;168 next(err);169 });170 };171 }172

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 175–176why, one step back
175
176 // mounted an app

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 177–179why, one step back
177 if (mount_app) {
178 mount_app.parent = this;179 mount_app.emit('mount', this);

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 180–185why, one step back
180 }
181182 return this;183};184185/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 186–195why, one step back
186 * Proxy to the app `Router#route()`
187 * Returns a new `Route` instance for the _path_.188 *189 * Routes are isolated middleware stacks for specific paths.190 * See the Route api docs for details.191 *192 * @api public193 */194195app.route = function(path){

implement app.route()Roman Shtylmanbefore adoption0719e5f

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 198–200why, one step back
198};
199200/**

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 201–241why, one step back
201 * Register the given template engine callback `fn`
202 * as `ext`.203 *204 * By default will `require()` the engine based on the205 * file extension. For example if you try to render206 * a "foo.jade" file Express will invoke the following internally:207 *208 * app.engine('jade', require('jade').__express);209 *210 * For engines that do not provide `.__express` out of the box,211 * or if you wish to "map" a different extension to the template engine212 * you may use this method. For example mapping the EJS template engine to213 * ".html" files:214 *215 * app.engine('html', require('ejs').renderFile);216 *217 * In this case EJS provides a `.renderFile()` method with218 * the same signature that Express expects: `(path, options, callback)`,219 * though note that it aliases this method as `ejs.__express` internally220 * so if you're using ".ejs" extensions you dont need to do anything.221 *222 * Some template engines do not follow this convention, the223 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)224 * library was created to map all of node's popular template225 * engines to follow this convention, thus allowing them to226 * work seamlessly within Express.227 *228 * @param {String} ext229 * @param {Function} fn230 * @return {app} for chaining231 * @api public232 */233234app.engine = function(ext, fn){235 if ('function' != typeof fn) throw new Error('callback function required');236 if ('.' != ext[0]) ext = '.' + ext;237 this.engines[ext] = fn;238 return this;239};240241/**

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

line 244why, one step back
244 *

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 246–253why, one step back
246 *
247 * @param {String|Array} name248 * @param {Function} fn249 * @return {app} for chaining250 * @api public251 */252253app.param = function(name, fn){

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 256–257why, one step back
256
257 if (Array.isArray(name)) {

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

line 260why, one step back
260 });

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

line 261why, one step back
261 return this;

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 262–263why, one step back
262 }
263

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 265–283why, one step back
265 return this;
266};267268/**269 * Assign `setting` to `val`, or return `setting`'s value.270 *271 * app.set('foo', 'bar');272 * app.get('foo');273 * // => "bar"274 *275 * Mounted servers inherit their parent server's settings.276 *277 * @param {String} setting278 * @param {*} [val]279 * @return {Server} for chaining280 * @api public281 */282283app.set = function(setting, val){

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

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

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 287why, one step back
287 }

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 288why, one step back
288

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

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

Merge tag '3.7.0'Douglas Christopher Wilsonbefore adoption097cd0c

line 291why, one step back
291

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 292–301why, one step back
292 // trigger matched settings
293 switch (setting) {294 case 'etag':295 debug('compile etag %s', val);296 this.set('etag fn', compileETag(val));297 break;298 case 'trust proxy':299 debug('compile trust proxy %s', val);300 this.set('trust proxy fn', compileTrust(val));301 break;

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

line 302why, one step back
302 }

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 303–304why, one step back
303
304 return this;

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 305–322why, one step back
305};
306307/**308 * Return the app's absolute pathname309 * based on the parent(s) that have310 * mounted it.311 *312 * For example if the application was313 * mounted as "/admin", which itself314 * was mounted as "/blog" then the315 * return value would be "/blog/admin".316 *317 * @return {String}318 * @api private319 */320321app.path = function(){322 return this.parent

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 324–394why, one step back
324 : '';
325};326327/**328 * Check if `setting` is enabled (truthy).329 *330 * app.enabled('foo')331 * // => false332 *333 * app.enable('foo')334 * app.enabled('foo')335 * // => true336 *337 * @param {String} setting338 * @return {Boolean}339 * @api public340 */341342app.enabled = function(setting){343 return !!this.set(setting);344};345346/**347 * Check if `setting` is disabled.348 *349 * app.disabled('foo')350 * // => true351 *352 * app.enable('foo')353 * app.disabled('foo')354 * // => false355 *356 * @param {String} setting357 * @return {Boolean}358 * @api public359 */360361app.disabled = function(setting){362 return !this.set(setting);363};364365/**366 * Enable `setting`.367 *368 * @param {String} setting369 * @return {app} for chaining370 * @api public371 */372373app.enable = function(setting){374 return this.set(setting, true);375};376377/**378 * Disable `setting`.379 *380 * @param {String} setting381 * @return {app} for chaining382 * @api public383 */384385app.disable = function(setting){386 return this.set(setting, false);387};388389/**390 * Delegate `.VERB(...)` calls to `router.VERB(...)`.391 */392393methods.forEach(function(method){394 app[method] = function(path){

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

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

line 396why, one step back
396

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

lines 397–399why, one step back
397 this.lazyrouter();
398399 var route = this._router.route(path);

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

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 401–415why, one step back
401 return this;
402 };403});404405/**406 * Special-cased "all" method, applying the given route `path`,407 * middleware, and callback to _every_ HTTP method.408 *409 * @param {String} path410 * @param {Function} ...411 * @return {app} for chaining412 * @api public413 */414415app.all = function(path){

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

lines 416–418why, one step back
416 this.lazyrouter();
417418 var route = this._router.route(path);

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

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

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

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

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

remove app.router and refactor middleware processingRoman Shtylmanbefore adoptionf41d09a

lines 422–423why, one step back
422 });
423

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 424–428why, one step back
424 return this;
425};426427// del -> delete alias428

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 430–448why, one step back
430
431/**432 * Render the given view `name` name with `options`433 * and a callback accepting an error and the434 * rendered template string.435 *436 * Example:437 *438 * app.render('email', { name: 'Tobi' }, function(err, html){439 * // ...440 * })441 *442 * @param {String} name443 * @param {String|Function} options or fn444 * @param {Function} fn445 * @api public446 */447448app.render = function(name, options, fn){

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

lines 449–452why, one step back
449 var opts = {};
450 var cache = this.cache;451 var engines = this.engines;452 var view;

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 453–459why, one step back
453
454 // support callback function as second arg455 if ('function' == typeof options) {456 fn = options, options = {};457 }458459 // merge app.locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 461–462why, one step back
461
462 // merge options._locals

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 464–465why, one step back
464
465 // merge options

use utils-merge module to mixin object propertiesRoman Shtylmanbefore adoption718e68f

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

Merge pull request #1868 from dpatti/smarter-router-auto-optionsRoman Shtylmanbefore adoption5ddbb69

lines 467–526why, one step back
467
468 // set .cache unless explicitly provided469 opts.cache = null == opts.cache470 ? this.enabled('view cache')471 : opts.cache;472473 // primed cache474 if (opts.cache) view = cache[name];475476 // view477 if (!view) {478 view = new (this.get('view'))(name, {479 defaultEngine: this.get('view engine'),480 root: this.get('views'),481 engines: engines482 });483484 if (!view.path) {485 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');486 err.view = view;487 return fn(err);488 }489490 // prime the cache491 if (opts.cache) cache[name] = view;492 }493494 // render495 try {496 view.render(opts, fn);497 } catch (err) {498 fn(err);499 }500};501502/**503 * Listen for connections.504 *505 * A node `http.Server` is returned, with this506 * application (which is a `Function`) as its507 * callback. If you wish to create both an HTTP508 * and HTTPS server you may do so with the "http"509 * and "https" modules as shown here:510 *511 * var http = require('http')512 * , https = require('https')513 * , express = require('express')514 * , app = express();515 *516 * http.createServer(app).listen(80);517 * https.createServer({ ... }, app).listen(443);518 *519 * @return {http.Server}520 * @api public521 */522523app.listen = function(){524 var server = http.createServer(this);525 return server.listen.apply(server, arguments);526};

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 527–537why, one step back
527
528/**529* Log error using console.error.530*531* @param {Error} err532* @api public533*/534535function logerror(err){536 if (this.get('env') !== 'test') console.error(err.stack || err.toString());537}