Skip to content
Myr

application.js

This file

Path

lib/application.js

557 lines · 12.1 KiB · JavaScript

Last changed by

Merge tag '4.11.2'Douglas Christopher Wilsonbefore adoptiona9ef9e1

History of this file

Take it

The walk stopped after 200 commits: lines older than 3205f68 point at it.

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

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;

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 7–12why, one step back
7var Router = require('./router');
8var methods = require('methods');9var debug = require('debug')('express:application');10var View = require('./view');11var http = require('http');12var compileETag = require('./utils').compileETag;

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

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

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 15why, one step back
15var merge = require('utils-merge');

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

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

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

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 18–35why, 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(){

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

lines 36–37why, one step back
36 var router = null;
37

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 38–41why, one step back
38 this.cache = {};
39 this.settings = {};40 this.engines = {};41 this.defaultConfiguration();

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

lines 42–57why, one step back
42
43 // Setup getting to lazily add base router44 Object.defineProperty(this, 'router', {45 configurable: true,46 enumerable: true,47 get: function getrouter() {48 if (router === null) {49 router = new Router({50 caseSensitive: this.enabled('case sensitive routing'),51 strict: this.enabled('strict routing')52 });53 }5455 return router;56 }57 });

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 58–71why, one step back
58};
5960/**61 * Initialize application configuration.62 *63 * @api private64 */6566app.defaultConfiguration = function(){67 // default settings68 this.enable('x-powered-by');69 this.set('etag', 'weak');70 var env = process.env.NODE_ENV || 'development';71 this.set('env', env);

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 73–114why, one step back
73 this.set('subdomain offset', 2);
74 this.set('trust proxy', false);7576 debug('booting in %s mode', env);7778 // inherit protos79 this.on('mount', function(parent){80 this.request.__proto__ = parent.request;81 this.response.__proto__ = parent.response;82 this.engines.__proto__ = parent.engines;83 this.settings.__proto__ = parent.settings;84 });8586 // setup locals87 this.locals = Object.create(null);8889 // top-most app is mounted at /90 this.mountpath = '/';9192 // default locals93 this.locals.settings = this.settings;9495 // default configuration96 this.set('view', View);97 this.set('views', resolve('views'));98 this.set('jsonp callback name', 'callback');99100 if (env === 'production') {101 this.enable('view cache');102 }103};104105/**106 * Dispatch a req, res pair into the application. Starts pipeline processing.107 *108 * If no _done_ callback is provided, then default error handlers will respond109 * in the event of an error bubbling through the stack.110 *111 * @api private112 */113114app.handle = function(req, res, done) {

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 115–118why, one step back
115 // final handler
116 done = done || finalhandler(req, res, {117 env: this.get('env'),118 onerror: logerror.bind(this)

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 119why, one step back
119 });

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

line 120why, one step back
120

Refactor away init middlewareDouglas Christopher Wilsonbefore adoption78e5054

lines 121–136why, one step back
121 // set powered by header
122 if (this.enabled('x-powered-by')) {123 res.setHeader('X-Powered-By', 'Express');124 }125126 // set circular references127 req.res = res;128 res.req = req;129130 // alter the prototypes131 req.__proto__ = this.request;132 res.__proto__ = this.response;133134 // setup locals135 if (!res.locals) {136 res.locals = Object.create(null);

fix behavior when handling request without routesDouglas Christopher Wilsonbefore adoptionbdfd288

lines 137–138why, one step back
137 }
138

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

line 139why, one step back
139 this.router.handle(req, res, done);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 140–151why, one step back
140};
141142/**143 * Proxy `Router#use()` to add middleware to the app router.144 * See Router#use() documentation for details.145 *146 * If the _fn_ parameter is an express app, then it will be147 * mounted at the _route_ specified.148 *149 * @api public150 */151

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

lines 152–154why, one step back
152app.use = function use(fn) {
153 var offset = 0;154 var path = '/';

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 155why, one step back
155

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

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

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

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

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

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

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

lines 159–164why, one step back
159 var arg = fn;
160161 while (Array.isArray(arg) && arg.length !== 0) {162 arg = arg[0];163 }164

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

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

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

lines 167–169why, one step back
167 offset = 1;
168 path = fn;169 }

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

line 170why, one step back
170 }

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 171why, one step back
171

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

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

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

lines 178–179why, one step back
178 // get router
179 var router = this.router;

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 180why, one step back
180

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

lines 181–185why, one step back
181 fns.forEach(function (fn) {
182 // non-express app183 if (!fn || !fn.handle || !fn.set) {184 return router.use(path, fn);185 }

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

line 186why, one step back
186

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

lines 187–188why, one step back
187 debug('.use app under %s', path);
188 fn.mountpath = path;

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

line 189why, one step back
189 fn.parent = this;

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

line 190why, one step back
190

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

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

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

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

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

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

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

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

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

line 199why, one step back
199 });

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 200why, one step back
200

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

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

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

lines 202–203why, one step back
202 fn.emit('mount', this);
203 }, this);

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

line 204why, one step back
204

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 205–217why, one step back
205 return this;
206};207208/**209 * Proxy to the app `Router#route()`210 * Returns a new `Route` instance for the _path_.211 *212 * Routes are isolated middleware stacks for specific paths.213 * See the Route api docs for details.214 *215 * @api public216 */217

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

lines 218–219why, one step back
218app.route = function route(path) {
219 return this.router.route(path);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 220–244why, one step back
220};
221222/**223 * Register the given template engine callback `fn`224 * as `ext`.225 *226 * By default will `require()` the engine based on the227 * file extension. For example if you try to render228 * a "foo.jade" file Express will invoke the following internally:229 *230 * app.engine('jade', require('jade').__express);231 *232 * For engines that do not provide `.__express` out of the box,233 * or if you wish to "map" a different extension to the template engine234 * you may use this method. For example mapping the EJS template engine to235 * ".html" files:236 *237 * app.engine('html', require('ejs').renderFile);238 *239 * In this case EJS provides a `.renderFile()` method with240 * the same signature that Express expects: `(path, options, callback)`,241 * though note that it aliases this method as `ejs.__express` internally242 * so if you're using ".ejs" extensions you dont need to do anything.243 *244 * Some template engines do not follow this convention, the

docs: visionmedia is now tj on GithubDouglas Christopher Wilsonbefore adoptione9539fc

line 245why, one step back
245 * [Consolidate.js](https://github.com/tj/consolidate.js)

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 246–274why, one step back
246 * library was created to map all of node's popular template
247 * engines to follow this convention, thus allowing them to248 * work seamlessly within Express.249 *250 * @param {String} ext251 * @param {Function} fn252 * @return {app} for chaining253 * @api public254 */255256app.engine = function(ext, fn){257 if ('function' != typeof fn) throw new Error('callback function required');258 if ('.' != ext[0]) ext = '.' + ext;259 this.engines[ext] = fn;260 return this;261};262263/**264 * Proxy to `Router#param()` with one added api feature. The _name_ parameter265 * can be an array of names.266 *267 * See the Router#param() docs for more details.268 *269 * @param {String|Array} name270 * @param {Function} fn271 * @return {app} for chaining272 * @api public273 */274

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

line 275why, one step back
275app.param = function param(name, fn) {

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

line 276why, one step back
276 if (Array.isArray(name)) {

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

lines 277–279why, one step back
277 for (var i = 0; i < name.length; i++) {
278 this.param(name[i], fn);279 }

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 280–282why, one step back
280 return this;
281 }282

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

line 283why, one step back
283 this.router.param(name, fn);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 284–315why, one step back
284 return this;
285};286287/**288 * Assign `setting` to `val`, or return `setting`'s value.289 *290 * app.set('foo', 'bar');291 * app.get('foo');292 * // => "bar"293 *294 * Mounted servers inherit their parent server's settings.295 *296 * @param {String} setting297 * @param {*} [val]298 * @return {Server} for chaining299 * @api public300 */301302app.set = function(setting, val){303 if (arguments.length === 1) {304 // app.get(setting)305 return this.settings[setting];306 }307308 // set value309 this.settings[setting] = val;310311 // trigger matched settings312 switch (setting) {313 case 'etag':314 debug('compile etag %s', val);315 this.set('etag fn', compileETag(val));

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

lines 316–319why, one step back
316 break;
317 case 'query parser':318 debug('compile query parser %s', val);319 this.set('query parser fn', compileQueryParser(val));

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 320–419why, one step back
320 break;
321 case 'trust proxy':322 debug('compile trust proxy %s', val);323 this.set('trust proxy fn', compileTrust(val));324 break;325 }326327 return this;328};329330/**331 * Return the app's absolute pathname332 * based on the parent(s) that have333 * mounted it.334 *335 * For example if the application was336 * mounted as "/admin", which itself337 * was mounted as "/blog" then the338 * return value would be "/blog/admin".339 *340 * @return {String}341 * @api private342 */343344app.path = function(){345 return this.parent346 ? this.parent.path() + this.mountpath347 : '';348};349350/**351 * Check if `setting` is enabled (truthy).352 *353 * app.enabled('foo')354 * // => false355 *356 * app.enable('foo')357 * app.enabled('foo')358 * // => true359 *360 * @param {String} setting361 * @return {Boolean}362 * @api public363 */364365app.enabled = function(setting){366 return !!this.set(setting);367};368369/**370 * Check if `setting` is disabled.371 *372 * app.disabled('foo')373 * // => true374 *375 * app.enable('foo')376 * app.disabled('foo')377 * // => false378 *379 * @param {String} setting380 * @return {Boolean}381 * @api public382 */383384app.disabled = function(setting){385 return !this.set(setting);386};387388/**389 * Enable `setting`.390 *391 * @param {String} setting392 * @return {app} for chaining393 * @api public394 */395396app.enable = function(setting){397 return this.set(setting, true);398};399400/**401 * Disable `setting`.402 *403 * @param {String} setting404 * @return {app} for chaining405 * @api public406 */407408app.disable = function(setting){409 return this.set(setting, false);410};411412/**413 * Delegate `.VERB(...)` calls to `router.VERB(...)`.414 */415416methods.forEach(function(method){417 app[method] = function(path){418 if ('get' == method && 1 == arguments.length) return this.set(path);419

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

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

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

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 422–436why, one step back
422 return this;
423 };424});425426/**427 * Special-cased "all" method, applying the given route `path`,428 * middleware, and callback to _every_ HTTP method.429 *430 * @param {String} path431 * @param {Function} ...432 * @return {app} for chaining433 * @api public434 */435436app.all = function(path){

Add app.router reference backDouglas Christopher Wilsonbefore adoption509ebb1

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

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

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 439–474why, one step back
439 methods.forEach(function(method){
440 route[method].apply(route, args);441 });442443 return this;444};445446/**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){464 var opts = {};465 var cache = this.cache;466 var engines = this.engines;467 var view;468469 // support callback function as second arg470 if ('function' == typeof options) {471 fn = options, options = {};472 }473474 // merge app.locals

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

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

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

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

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

lines 478–480why, one step back
478 if (options._locals) {
479 merge(opts, options._locals);480 }

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 481–482why, one step back
481
482 // merge options

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 483why, one step back
483 merge(opts, options);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 484–501why, one step back
484
485 // set .cache unless explicitly provided486 opts.cache = null == opts.cache487 ? this.enabled('view cache')488 : opts.cache;489490 // primed cache491 if (opts.cache) view = cache[name];492493 // view494 if (!view) {495 view = new (this.get('view'))(name, {496 defaultEngine: this.get('view engine'),497 root: this.get('views'),498 engines: engines499 });500501 if (!view.path) {

Add support for app.set('views', array)Douglas Christopher Wilsonbefore adoption6614352

lines 502–505why, one step back
502 var dirs = Array.isArray(view.root) && view.root.length > 1
503 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'504 : 'directory "' + view.root + '"'505 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption3205f68

lines 506–546why, one step back
506 err.view = view;
507 return fn(err);508 }509510 // prime the cache511 if (opts.cache) cache[name] = view;512 }513514 // render515 try {516 view.render(opts, fn);517 } catch (err) {518 fn(err);519 }520};521522/**523 * Listen for connections.524 *525 * A node `http.Server` is returned, with this526 * application (which is a `Function`) as its527 * callback. If you wish to create both an HTTP528 * and HTTPS server you may do so with the "http"529 * and "https" modules as shown here:530 *531 * var http = require('http')532 * , https = require('https')533 * , express = require('express')534 * , app = express();535 *536 * http.createServer(app).listen(80);537 * https.createServer({ ... }, app).listen(443);538 *539 * @return {http.Server}540 * @api public541 */542543app.listen = function(){544 var server = http.createServer(this);545 return server.listen.apply(server, arguments);546};

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 547–551why, one step back
547
548/**549* Log error using console.error.550*551* @param {Error} err

Merge tag '4.11.2'Douglas Christopher Wilsonbefore adoptiona9ef9e1

line 552why, one step back
552* @api private

use finalhandler for final response handlingDouglas Christopher Wilsonbefore adoption7e01531

lines 553–557why, one step back
553*/
554555function logerror(err){556 if (this.get('env') !== 'test') console.error(err.stack || err.toString());557}