3 * Copyright(c) 2009-2013 TJ Holowaychuk
4 * Copyright(c) 2013 Roman Shtylman
5 * Copyright(c) 2014-2015 Douglas Christopher Wilson
12 * Module dependencies.
16 var finalhandler = require('finalhandler');
17 var Router = require('./router');
18 var methods = require('methods');
19 var middleware = require('./middleware/init');
20 var query = require('./middleware/query');
21 var debug = require('debug')('express:application');
22 var View = require('./view');
23 var http = require('http');
24 var compileETag = require('./utils').compileETag;
25 var compileQueryParser = require('./utils').compileQueryParser;
26 var compileTrust = require('./utils').compileTrust;
27 var deprecate = require('depd')('express');
28 var flatten = require('array-flatten');
29 var merge = require('utils-merge');
30 var resolve = require('path').resolve;
31 var setPrototypeOf = require('setprototypeof')
38 var hasOwnProperty = Object.prototype.hasOwnProperty
39 var slice = Array.prototype.slice;
42 * Application prototype.
45 var app = exports = module.exports = {};
48 * Variable for trust proxy inheritance back-compat
52 var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
55 * Initialize the server.
57 * - setup default configuration
58 * - setup default middleware
59 * - setup route reflection methods
64 app.init = function init() {
69 this.defaultConfiguration();
73 * Initialize application configuration.
77 app.defaultConfiguration = function defaultConfiguration() {
78 var env = process.env.NODE_ENV || 'development';
81 this.enable('x-powered-by');
82 this.set('etag', 'weak');
84 this.set('query parser', 'extended');
85 this.set('subdomain offset', 2);
86 this.set('trust proxy', false);
88 // trust proxy inherit back-compat
89 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
94 debug('booting in %s mode', env);
96 this.on('mount', function onmount(parent) {
97 // inherit trust proxy
98 if (this.settings[trustProxyDefaultSymbol] === true
99 && typeof parent.settings['trust proxy fn'] === 'function') {
100 delete this.settings['trust proxy'];
101 delete this.settings['trust proxy fn'];
105 setPrototypeOf(this.request, parent.request)
106 setPrototypeOf(this.response, parent.response)
107 setPrototypeOf(this.engines, parent.engines)
108 setPrototypeOf(this.settings, parent.settings)
112 this.locals = Object.create(null);
114 // top-most app is mounted at /
115 this.mountpath = '/';
118 this.locals.settings = this.settings;
120 // default configuration
121 this.set('view', View);
122 this.set('views', resolve('views'));
123 this.set('jsonp callback name', 'callback');
125 if (env === 'production') {
126 this.enable('view cache');
129 Object.defineProperty(this, 'router', {
131 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.');
137 * lazily adds the base router if it has not yet been added.
139 * We cannot add the base router in the defaultConfiguration because
140 * it reads app settings which might be set after that has run.
144 app.lazyrouter = function lazyrouter() {
146 this._router = new Router({
147 caseSensitive: this.enabled('case sensitive routing'),
148 strict: this.enabled('strict routing')
151 this._router.use(query(this.get('query parser fn')));
152 this._router.use(middleware.init(this));
157 * Dispatch a req, res pair into the application. Starts pipeline processing.
159 * If no callback is provided, then default error handlers will respond
160 * in the event of an error bubbling through the stack.
165 app.handle = function handle(req, res, callback) {
166 var router = this._router;
169 var done = callback || finalhandler(req, res, {
170 env: this.get('env'),
171 onerror: logerror.bind(this)
176 debug('no routes defined on app');
181 router.handle(req, res, done);
185 * Proxy `Router#use()` to add middleware to the app router.
186 * See Router#use() documentation for details.
188 * If the _fn_ parameter is an express app, then it will be
189 * mounted at the _route_ specified.
194 app.use = function use(fn) {
198 // default path to '/'
199 // disambiguate app.use([fn])
200 if (typeof fn !== 'function') {
203 while (Array.isArray(arg) && arg.length !== 0) {
207 // first arg is the path
208 if (typeof arg !== 'function') {
214 var fns = flatten(slice.call(arguments, offset));
216 if (fns.length === 0) {
217 throw new TypeError('app.use() requires a middleware function')
222 var router = this._router;
224 fns.forEach(function (fn) {
226 if (!fn || !fn.handle || !fn.set) {
227 return router.use(path, fn);
230 debug('.use app under %s', path);
234 // restore .app property on req and res
235 router.use(path, function mounted_app(req, res, next) {
237 fn.handle(req, res, function (err) {
238 setPrototypeOf(req, orig.request)
239 setPrototypeOf(res, orig.response)
245 fn.emit('mount', this);
252 * Proxy to the app `Router#route()`
253 * Returns a new `Route` instance for the _path_.
255 * Routes are isolated middleware stacks for specific paths.
256 * See the Route api docs for details.
261 app.route = function route(path) {
263 return this._router.route(path);
267 * Register the given template engine callback `fn`
270 * By default will `require()` the engine based on the
271 * file extension. For example if you try to render
272 * a "foo.ejs" file Express will invoke the following internally:
274 * app.engine('ejs', require('ejs').__express);
276 * For engines that do not provide `.__express` out of the box,
277 * or if you wish to "map" a different extension to the template engine
278 * you may use this method. For example mapping the EJS template engine to
281 * app.engine('html', require('ejs').renderFile);
283 * In this case EJS provides a `.renderFile()` method with
284 * the same signature that Express expects: `(path, options, callback)`,
285 * though note that it aliases this method as `ejs.__express` internally
286 * so if you're using ".ejs" extensions you don't need to do anything.
288 * Some template engines do not follow this convention, the
289 * [Consolidate.js](https://github.com/tj/consolidate.js)
290 * library was created to map all of node's popular template
291 * engines to follow this convention, thus allowing them to
292 * work seamlessly within Express.
294 * @param {String} ext
295 * @param {Function} fn
296 * @return {app} for chaining
300 app.engine = function engine(ext, fn) {
301 if (typeof fn !== 'function') {
302 throw new Error('callback function required');
305 // get file extension
306 var extension = ext[0] !== '.'
311 this.engines[extension] = fn;
317 * Proxy to `Router#param()` with one added api feature. The _name_ parameter
318 * can be an array of names.
320 * See the Router#param() docs for more details.
322 * @param {String|Array} name
323 * @param {Function} fn
324 * @return {app} for chaining
328 app.param = function param(name, fn) {
331 if (Array.isArray(name)) {
332 for (var i = 0; i < name.length; i++) {
333 this.param(name[i], fn);
339 this._router.param(name, fn);
345 * Assign `setting` to `val`, or return `setting`'s value.
347 * app.set('foo', 'bar');
351 * Mounted servers inherit their parent server's settings.
353 * @param {String} setting
355 * @return {Server} for chaining
359 app.set = function set(setting, val) {
360 if (arguments.length === 1) {
362 var settings = this.settings
364 while (settings && settings !== Object.prototype) {
365 if (hasOwnProperty.call(settings, setting)) {
366 return settings[setting]
369 settings = Object.getPrototypeOf(settings)
375 debug('set "%s" to %o', setting, val);
378 this.settings[setting] = val;
380 // trigger matched settings
383 this.set('etag fn', compileETag(val));
386 this.set('query parser fn', compileQueryParser(val));
389 this.set('trust proxy fn', compileTrust(val));
391 // trust proxy inherit back-compat
392 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
404 * Return the app's absolute pathname
405 * based on the parent(s) that have
408 * For example if the application was
409 * mounted as "/admin", which itself
410 * was mounted as "/blog" then the
411 * return value would be "/blog/admin".
417 app.path = function path() {
419 ? this.parent.path() + this.mountpath
424 * Check if `setting` is enabled (truthy).
433 * @param {String} setting
438 app.enabled = function enabled(setting) {
439 return Boolean(this.set(setting));
443 * Check if `setting` is disabled.
445 * app.disabled('foo')
449 * app.disabled('foo')
452 * @param {String} setting
457 app.disabled = function disabled(setting) {
458 return !this.set(setting);
464 * @param {String} setting
465 * @return {app} for chaining
469 app.enable = function enable(setting) {
470 return this.set(setting, true);
476 * @param {String} setting
477 * @return {app} for chaining
481 app.disable = function disable(setting) {
482 return this.set(setting, false);
486 * Delegate `.VERB(...)` calls to `router.VERB(...)`.
489 methods.forEach(function(method){
490 app[method] = function(path){
491 if (method === 'get' && arguments.length === 1) {
493 return this.set(path);
498 var route = this._router.route(path);
499 route[method].apply(route, slice.call(arguments, 1));
505 * Special-cased "all" method, applying the given route `path`,
506 * middleware, and callback to _every_ HTTP method.
508 * @param {String} path
509 * @param {Function} ...
510 * @return {app} for chaining
514 app.all = function all(path) {
517 var route = this._router.route(path);
518 var args = slice.call(arguments, 1);
520 for (var i = 0; i < methods.length; i++) {
521 route[methods[i]].apply(route, args);
527 // del -> delete alias
529 app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');
532 * Render the given view `name` name with `options`
533 * and a callback accepting an error and the
534 * rendered template string.
538 * app.render('email', { name: 'Tobi' }, function(err, html){
542 * @param {String} name
543 * @param {Object|Function} options or fn
544 * @param {Function} callback
548 app.render = function render(name, options, callback) {
549 var cache = this.cache;
551 var engines = this.engines;
553 var renderOptions = {};
556 // support callback function as second arg
557 if (typeof options === 'function') {
563 merge(renderOptions, this.locals);
565 // merge options._locals
567 merge(renderOptions, opts._locals);
571 merge(renderOptions, opts);
573 // set .cache unless explicitly provided
574 if (renderOptions.cache == null) {
575 renderOptions.cache = this.enabled('view cache');
579 if (renderOptions.cache) {
585 var View = this.get('view');
587 view = new View(name, {
588 defaultEngine: this.get('view engine'),
589 root: this.get('views'),
594 var dirs = Array.isArray(view.root) && view.root.length > 1
595 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
596 : 'directory "' + view.root + '"'
597 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
603 if (renderOptions.cache) {
609 tryRender(view, renderOptions, done);
613 * Listen for connections.
615 * A node `http.Server` is returned, with this
616 * application (which is a `Function`) as its
617 * callback. If you wish to create both an HTTP
618 * and HTTPS server you may do so with the "http"
619 * and "https" modules as shown here:
621 * var http = require('http')
622 * , https = require('https')
623 * , express = require('express')
626 * http.createServer(app).listen(80);
627 * https.createServer({ ... }, app).listen(443);
629 * @return {http.Server}
633 app.listen = function listen() {
634 var server = http.createServer(this);
635 return server.listen.apply(server, arguments);
639 * Log error using console.error.
645 function logerror(err) {
646 /* istanbul ignore next */
647 if (this.get('env') !== 'test') console.error(err.stack || err.toString());
651 * Try rendering a view.
655 function tryRender(view, options, callback) {
657 view.render(options, callback);