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 fileTake it
1/**2 * Module dependencies.3 */45var finalhandler = require('finalhandler');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');14var compileETag = require('./utils').compileETag;15var compileTrust = require('./utils').compileTrust;16var deprecate = require('depd')('express');17var resolve = require('path').resolve;1819/**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');51 this.set('etag', 'weak');52 var env = process.env.NODE_ENV || 'development';53 this.set('env', env);54 this.set('subdomain offset', 2);55 this.set('trust proxy', false);5657 debug('booting in %s mode', env);5859 // 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 locals68 this.locals = Object.create(null);6970 // top-most app is mounted at /71 this.mountpath = '/';7273 // default locals74 this.locals.settings = this.settings;7576 // default configuration77 this.set('view', View);78 this.set('views', resolve('views'));79 this.set('jsonp callback name', 'callback');8081 if (env === 'production') {82 this.enable('view cache');83 }8485 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 });90};9192/**93 * lazily adds the base router if it has not yet been added.94 *95 * We cannot add the base router in the defaultConfiguration because96 * 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 });106107 this._router.use(query());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) {122 var router = this._router;123124 // final handler125 done = done || finalhandler(req, res, {126 env: this.get('env'),127 onerror: logerror.bind(this)128 });129130 // no routes131 if (!router) {132 debug('no routes defined on app');133 done();134 return;135 }136137 router.handle(req, res, done);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 *147 * @api public148 */149150app.use = function(route, fn){151 var mount_app;152153 // default route to '/'154 if ('string' != typeof route) fn = route, route = '/';155156 // express app157 if (fn.handle && fn.set) mount_app = fn;158159 // restore .app property on req and res160 if (mount_app) {161 debug('.use app under %s', route);162 mount_app.mountpath = route;163 fn = function(req, res, next) {164 var orig = req.app;165 mount_app.handle(req, res, function(err) {166 req.__proto__ = orig.request;167 res.__proto__ = orig.response;168 next(err);169 });170 };171 }172173 this.lazyrouter();174 this._router.use(route, fn);175176 // mounted an app177 if (mount_app) {178 mount_app.parent = this;179 mount_app.emit('mount', this);180 }181182 return this;183};184185/**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){196 this.lazyrouter();197 return this._router.route(path);198};199200/**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/**242 * Proxy to `Router#param()` with one added api feature. The _name_ parameter243 * can be an array of names.244 *245 * See the Router#param() docs for more details.246 *247 * @param {String|Array} name248 * @param {Function} fn249 * @return {app} for chaining250 * @api public251 */252253app.param = function(name, fn){254 var self = this;255 self.lazyrouter();256257 if (Array.isArray(name)) {258 name.forEach(function(key) {259 self.param(key, fn);260 });261 return this;262 }263264 self._router.param(name, fn);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){284 if (arguments.length === 1) {285 // app.get(setting)286 return this.settings[setting];287 }288289 // set value290 this.settings[setting] = val;291292 // trigger matched settings293 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;302 }303304 return this;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.parent323 ? this.parent.path() + this.mountpath324 : '';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){395 if ('get' == method && 1 == arguments.length) return this.set(path);396397 this.lazyrouter();398399 var route = this._router.route(path);400 route[method].apply(route, [].slice.call(arguments, 1));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){416 this.lazyrouter();417418 var route = this._router.route(path);419 var args = [].slice.call(arguments, 1);420 methods.forEach(function(method){421 route[method].apply(route, args);422 });423424 return this;425};426427// del -> delete alias428429app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');430431/**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){449 var opts = {};450 var cache = this.cache;451 var engines = this.engines;452 var view;453454 // support callback function as second arg455 if ('function' == typeof options) {456 fn = options, options = {};457 }458459 // merge app.locals460 mixin(opts, this.locals);461462 // merge options._locals463 if (options._locals) mixin(opts, options._locals);464465 // merge options466 mixin(opts, options);467468 // 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};527528/**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}