Skip to content
Myr

application.js

This file

Path

lib/application.js

568 lines · 12.3 KiB · JavaScript

Last changed by

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

History of this file

Take it

The walk stopped after 200 commits: lines older than 739586f point at it.

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

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

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

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 7–14why, one step back
7var mixin = require('utils-merge');
8var Router = require('./router');9var methods = require('methods');10var middleware = require('./middleware/init');11var query = require('./middleware/query');12var debug = require('debug')('express:application');13var View = require('./view');14var http = require('http');

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

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

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

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

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

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

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

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

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

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 21–53why, one step back
21
22/**23 * Application prototype.24 */2526var app = exports = module.exports = {};2728/**29 * Initialize the server.30 *31 * - setup default configuration32 * - setup default middleware33 * - setup route reflection methods34 *35 * @api private36 */3738app.init = function(){39 this.cache = {};40 this.settings = {};41 this.engines = {};42 this.defaultConfiguration();43};4445/**46 * Initialize application configuration.47 *48 * @api private49 */5051app.defaultConfiguration = function(){52 // default settings53 this.enable('x-powered-by');

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 54why, one step back
54 this.set('etag', 'weak');

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

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

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 58–81why, one step back
58 this.set('subdomain offset', 2);
59 this.set('trust proxy', false);6061 debug('booting in %s mode', env);6263 // inherit protos64 this.on('mount', function(parent){65 this.request.__proto__ = parent.request;66 this.response.__proto__ = parent.response;67 this.engines.__proto__ = parent.engines;68 this.settings.__proto__ = parent.settings;69 });7071 // setup locals72 this.locals = Object.create(null);7374 // top-most app is mounted at /75 this.mountpath = '/';7677 // default locals78 this.locals.settings = this.settings;7980 // default configuration81 this.set('view', View);

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

line 82why, one step back
82 this.set('views', resolve('views'));

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 83–110why, one step back
83 this.set('jsonp callback name', 'callback');
8485 if (env === 'production') {86 this.enable('view cache');87 }8889 Object.defineProperty(this, 'router', {90 get: function() {91 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.');92 }93 });94};9596/**97 * lazily adds the base router if it has not yet been added.98 *99 * We cannot add the base router in the defaultConfiguration because100 * it reads app settings which might be set after that has run.101 *102 * @api private103 */104app.lazyrouter = function() {105 if (!this._router) {106 this._router = new Router({107 caseSensitive: this.enabled('case sensitive routing'),108 strict: this.enabled('strict routing')109 });110

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

line 111why, one step back
111 this._router.use(query(this.get('query parser fn')));

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 112–125why, one step back
112 this._router.use(middleware.init(this));
113 }114};115116/**117 * Dispatch a req, res pair into the application. Starts pipeline processing.118 *119 * If no _done_ callback is provided, then default error handlers will respond120 * in the event of an error bubbling through the stack.121 *122 * @api private123 */124125app.handle = function(req, res, done) {

fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288

lines 126–127why, one step back
126 var router = this._router;
127

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 128–131why, one step back
128 // final handler
129 done = done || finalhandler(req, res, {130 env: this.get('env'),131 onerror: logerror.bind(this)

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

line 132why, one step back
132 });

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

line 133why, one step back
133

fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288

lines 134–141why, one step back
134 // no routes
135 if (!router) {136 debug('no routes defined on app');137 done();138 return;139 }140141 router.handle(req, res, done);

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 142–153why, one step back
142};
143144/**145 * Proxy `Router#use()` to add middleware to the app router.146 * See Router#use() documentation for details.147 *148 * If the _fn_ parameter is an express app, then it will be149 * mounted at the _route_ specified.150 *151 * @api public152 */153

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

lines 154–157why, one step back
154app.use = function use(fn) {
155 var offset = 0;156 var path = '/';157 var self = this;

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

line 158why, one step back
158

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

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

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

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

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

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

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

lines 162–167why, one step back
162 var arg = fn;
163164 while (Array.isArray(arg) && arg.length !== 0) {165 arg = arg[0];166 }167

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

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

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

lines 170–172why, one step back
170 offset = 1;
171 path = fn;172 }

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

line 173why, one step back
173 }

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

line 174why, one step back
174

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

lines 175–180why, one step back
175 var fns = flatten(slice.call(arguments, offset));
176177 if (fns.length === 0) {178 throw new TypeError('app.use() requires middleware functions');179 }180

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

lines 181–183why, one step back
181 // setup router
182 this.lazyrouter();183 var router = this._router;

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

line 184why, one step back
184

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

lines 185–189why, one step back
185 fns.forEach(function (fn) {
186 // non-express app187 if (!fn || !fn.handle || !fn.set) {188 return router.use(path, fn);189 }

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

line 190why, one step back
190

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

lines 191–194why, one step back
191 debug('.use app under %s', path);
192 fn.mountpath = path;193 fn.parent = self;194

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

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

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

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

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

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

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 199–202why, one step back
199 req.__proto__ = orig.request;
200 res.__proto__ = orig.response;201 next(err);202 });

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

line 203why, one step back
203 });

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

line 204why, one step back
204

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

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

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

lines 206–207why, one step back
206 fn.emit('mount', self);
207 });

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

line 208why, one step back
208

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 209–310why, one step back
209 return this;
210};211212/**213 * Proxy to the app `Router#route()`214 * Returns a new `Route` instance for the _path_.215 *216 * Routes are isolated middleware stacks for specific paths.217 * See the Route api docs for details.218 *219 * @api public220 */221222app.route = function(path){223 this.lazyrouter();224 return this._router.route(path);225};226227/**228 * Register the given template engine callback `fn`229 * as `ext`.230 *231 * By default will `require()` the engine based on the232 * file extension. For example if you try to render233 * a "foo.jade" file Express will invoke the following internally:234 *235 * app.engine('jade', require('jade').__express);236 *237 * For engines that do not provide `.__express` out of the box,238 * or if you wish to "map" a different extension to the template engine239 * you may use this method. For example mapping the EJS template engine to240 * ".html" files:241 *242 * app.engine('html', require('ejs').renderFile);243 *244 * In this case EJS provides a `.renderFile()` method with245 * the same signature that Express expects: `(path, options, callback)`,246 * though note that it aliases this method as `ejs.__express` internally247 * so if you're using ".ejs" extensions you dont need to do anything.248 *249 * Some template engines do not follow this convention, the250 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)251 * library was created to map all of node's popular template252 * engines to follow this convention, thus allowing them to253 * work seamlessly within Express.254 *255 * @param {String} ext256 * @param {Function} fn257 * @return {app} for chaining258 * @api public259 */260261app.engine = function(ext, fn){262 if ('function' != typeof fn) throw new Error('callback function required');263 if ('.' != ext[0]) ext = '.' + ext;264 this.engines[ext] = fn;265 return this;266};267268/**269 * Proxy to `Router#param()` with one added api feature. The _name_ parameter270 * can be an array of names.271 *272 * See the Router#param() docs for more details.273 *274 * @param {String|Array} name275 * @param {Function} fn276 * @return {app} for chaining277 * @api public278 */279280app.param = function(name, fn){281 var self = this;282 self.lazyrouter();283284 if (Array.isArray(name)) {285 name.forEach(function(key) {286 self.param(key, fn);287 });288 return this;289 }290291 self._router.param(name, fn);292 return this;293};294295/**296 * Assign `setting` to `val`, or return `setting`'s value.297 *298 * app.set('foo', 'bar');299 * app.get('foo');300 * // => "bar"301 *302 * Mounted servers inherit their parent server's settings.303 *304 * @param {String} setting305 * @param {*} [val]306 * @return {Server} for chaining307 * @api public308 */309310app.set = function(setting, val){

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

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

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 314why, one step back
314 }

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

line 315why, one step back
315

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

line 318why, one step back
318

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 319–323why, one step back
319 // trigger matched settings
320 switch (setting) {321 case 'etag':322 debug('compile etag %s', val);323 this.set('etag fn', compileETag(val));

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

lines 324–327why, one step back
324 break;
325 case 'query parser':326 debug('compile query parser %s', val);327 this.set('query parser fn', compileQueryParser(val));

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 328–332why, one step back
328 break;
329 case 'trust proxy':330 debug('compile trust proxy %s', val);331 this.set('trust proxy fn', compileTrust(val));332 break;

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

line 333why, one step back
333 }

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 334–335why, one step back
334
335 return this;

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 336–425why, one step back
336};
337338/**339 * Return the app's absolute pathname340 * based on the parent(s) that have341 * mounted it.342 *343 * For example if the application was344 * mounted as "/admin", which itself345 * was mounted as "/blog" then the346 * return value would be "/blog/admin".347 *348 * @return {String}349 * @api private350 */351352app.path = function(){353 return this.parent354 ? this.parent.path() + this.mountpath355 : '';356};357358/**359 * Check if `setting` is enabled (truthy).360 *361 * app.enabled('foo')362 * // => false363 *364 * app.enable('foo')365 * app.enabled('foo')366 * // => true367 *368 * @param {String} setting369 * @return {Boolean}370 * @api public371 */372373app.enabled = function(setting){374 return !!this.set(setting);375};376377/**378 * Check if `setting` is disabled.379 *380 * app.disabled('foo')381 * // => true382 *383 * app.enable('foo')384 * app.disabled('foo')385 * // => false386 *387 * @param {String} setting388 * @return {Boolean}389 * @api public390 */391392app.disabled = function(setting){393 return !this.set(setting);394};395396/**397 * Enable `setting`.398 *399 * @param {String} setting400 * @return {app} for chaining401 * @api public402 */403404app.enable = function(setting){405 return this.set(setting, true);406};407408/**409 * Disable `setting`.410 *411 * @param {String} setting412 * @return {app} for chaining413 * @api public414 */415416app.disable = function(setting){417 return this.set(setting, false);418};419420/**421 * Delegate `.VERB(...)` calls to `router.VERB(...)`.422 */423424methods.forEach(function(method){425 app[method] = function(path){

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

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

line 427why, one step back
427

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

lines 428–430why, one step back
428 this.lazyrouter();
429430 var route = this._router.route(path);

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

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 432–446why, one step back
432 return this;
433 };434});435436/**437 * Special-cased "all" method, applying the given route `path`,438 * middleware, and callback to _every_ HTTP method.439 *440 * @param {String} path441 * @param {Function} ...442 * @return {app} for chaining443 * @api public444 */445446app.all = function(path){

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

lines 447–449why, one step back
447 this.lazyrouter();
448449 var route = this._router.route(path);

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

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 451–459why, one step back
451 methods.forEach(function(method){
452 route[method].apply(route, args);453 });454455 return this;456};457458// del -> delete alias459

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

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

add req.baseUrl to access stripped path in routesDouglas Christopher Wilsonbefore adoption739586f

lines 461–557why, one step back
461
462/**463 * Render the given view `name` name with `options`464 * and a callback accepting an error and the465 * rendered template string.466 *467 * Example:468 *469 * app.render('email', { name: 'Tobi' }, function(err, html){470 * // ...471 * })472 *473 * @param {String} name474 * @param {String|Function} options or fn475 * @param {Function} fn476 * @api public477 */478479app.render = function(name, options, fn){480 var opts = {};481 var cache = this.cache;482 var engines = this.engines;483 var view;484485 // support callback function as second arg486 if ('function' == typeof options) {487 fn = options, options = {};488 }489490 // merge app.locals491 mixin(opts, this.locals);492493 // merge options._locals494 if (options._locals) mixin(opts, options._locals);495496 // merge options497 mixin(opts, options);498499 // set .cache unless explicitly provided500 opts.cache = null == opts.cache501 ? this.enabled('view cache')502 : opts.cache;503504 // primed cache505 if (opts.cache) view = cache[name];506507 // view508 if (!view) {509 view = new (this.get('view'))(name, {510 defaultEngine: this.get('view engine'),511 root: this.get('views'),512 engines: engines513 });514515 if (!view.path) {516 var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');517 err.view = view;518 return fn(err);519 }520521 // prime the cache522 if (opts.cache) cache[name] = view;523 }524525 // render526 try {527 view.render(opts, fn);528 } catch (err) {529 fn(err);530 }531};532533/**534 * Listen for connections.535 *536 * A node `http.Server` is returned, with this537 * application (which is a `Function`) as its538 * callback. If you wish to create both an HTTP539 * and HTTPS server you may do so with the "http"540 * and "https" modules as shown here:541 *542 * var http = require('http')543 * , https = require('https')544 * , express = require('express')545 * , app = express();546 *547 * http.createServer(app).listen(80);548 * https.createServer({ ... }, app).listen(443);549 *550 * @return {http.Server}551 * @api public552 */553554app.listen = function(){555 var server = http.createServer(this);556 return server.listen.apply(server, arguments);557};

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 558–568why, one step back
558
559/**560* Log error using console.error.561*562* @param {Error} err563* @api public564*/565566function logerror(err){567 if (this.get('env') !== 'test') console.error(err.stack || err.toString());568}