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')
32 var slice = Array.prototype.slice;
35 * Application prototype.
38 var app = exports = module.exports = {};
41 * Variable for trust proxy inheritance back-compat
45 var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
48 * Initialize the server.
50 * - setup default configuration
51 * - setup default middleware
52 * - setup route reflection methods
57 app.init = function init() {
62 this.defaultConfiguration();
66 * Initialize application configuration.
70 app.defaultConfiguration = function defaultConfiguration() {
71 var env = process.env.NODE_ENV || 'development';
74 this.enable('x-powered-by');
75 this.set('etag', 'weak');
77 this.set('query parser', 'extended');
78 this.set('subdomain offset', 2);
79 this.set('trust proxy', false);
81 // trust proxy inherit back-compat
82 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
87 debug('booting in %s mode', env);
89 this.on('mount', function onmount(parent) {
90 // inherit trust proxy
91 if (this.settings[trustProxyDefaultSymbol] === true
92 && typeof parent.settings['trust proxy fn'] === 'function') {
93 delete this.settings['trust proxy'];
94 delete this.settings['trust proxy fn'];
98 setPrototypeOf(this.request, parent.request)
99 setPrototypeOf(this.response, parent.response)
100 setPrototypeOf(this.engines, parent.engines)
101 setPrototypeOf(this.settings, parent.settings)
105 this.locals = Object.create(null);
107 // top-most app is mounted at /
108 this.mountpath = '/';
111 this.locals.settings = this.settings;
113 // default configuration
114 this.set('view', View);
115 this.set('views', resolve('views'));
116 this.set('jsonp callback name', 'callback');
118 if (env === 'production') {
119 this.enable('view cache');
122 Object.defineProperty(this, 'router', {
124 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.');
130 * lazily adds the base router if it has not yet been added.
132 * We cannot add the base router in the defaultConfiguration because
133 * it reads app settings which might be set after that has run.
137 app.lazyrouter = function lazyrouter() {
139 this._router = new Router({
140 caseSensitive: this.enabled('case sensitive routing'),
141 strict: this.enabled('strict routing')
144 this._router.use(query(this.get('query parser fn')));
145 this._router.use(middleware.init(this));
150 * Dispatch a req, res pair into the application. Starts pipeline processing.
152 * If no callback is provided, then default error handlers will respond
153 * in the event of an error bubbling through the stack.
158 app.handle = function handle(req, res, callback) {
159 var router = this._router;
162 var done = callback || finalhandler(req, res, {
163 env: this.get('env'),
164 onerror: logerror.bind(this)
169 debug('no routes defined on app');
174 router.handle(req, res, done);
178 * Proxy `Router#use()` to add middleware to the app router.
179 * See Router#use() documentation for details.
181 * If the _fn_ parameter is an express app, then it will be
182 * mounted at the _route_ specified.
187 app.use = function use(fn) {
191 // default path to '/'
192 // disambiguate app.use([fn])
193 if (typeof fn !== 'function') {
196 while (Array.isArray(arg) && arg.length !== 0) {
200 // first arg is the path
201 if (typeof arg !== 'function') {
207 var fns = flatten(slice.call(arguments, offset));
209 if (fns.length === 0) {
210 throw new TypeError('app.use() requires a middleware function')
215 var router = this._router;
217 fns.forEach(function (fn) {
219 if (!fn || !fn.handle || !fn.set) {
220 return router.use(path, fn);
223 debug('.use app under %s', path);
227 // restore .app property on req and res
228 router.use(path, function mounted_app(req, res, next) {
230 fn.handle(req, res, function (err) {
231 setPrototypeOf(req, orig.request)
232 setPrototypeOf(res, orig.response)
238 fn.emit('mount', this);
245 * Proxy to the app `Router#route()`
246 * Returns a new `Route` instance for the _path_.
248 * Routes are isolated middleware stacks for specific paths.
249 * See the Route api docs for details.
254 app.route = function route(path) {
256 return this._router.route(path);
260 * Register the given template engine callback `fn`
263 * By default will `require()` the engine based on the
264 * file extension. For example if you try to render
265 * a "foo.ejs" file Express will invoke the following internally:
267 * app.engine('ejs', require('ejs').__express);
269 * For engines that do not provide `.__express` out of the box,
270 * or if you wish to "map" a different extension to the template engine
271 * you may use this method. For example mapping the EJS template engine to
274 * app.engine('html', require('ejs').renderFile);
276 * In this case EJS provides a `.renderFile()` method with
277 * the same signature that Express expects: `(path, options, callback)`,
278 * though note that it aliases this method as `ejs.__express` internally
279 * so if you're using ".ejs" extensions you don't need to do anything.
281 * Some template engines do not follow this convention, the
282 * [Consolidate.js](https://github.com/tj/consolidate.js)
283 * library was created to map all of node's popular template
284 * engines to follow this convention, thus allowing them to
285 * work seamlessly within Express.
287 * @param {String} ext
288 * @param {Function} fn
289 * @return {app} for chaining
293 app.engine = function engine(ext, fn) {
294 if (typeof fn !== 'function') {
295 throw new Error('callback function required');
298 // get file extension
299 var extension = ext[0] !== '.'
304 this.engines[extension] = fn;
310 * Proxy to `Router#param()` with one added api feature. The _name_ parameter
311 * can be an array of names.
313 * See the Router#param() docs for more details.
315 * @param {String|Array} name
316 * @param {Function} fn
317 * @return {app} for chaining
321 app.param = function param(name, fn) {
324 if (Array.isArray(name)) {
325 for (var i = 0; i < name.length; i++) {
326 this.param(name[i], fn);
332 this._router.param(name, fn);
338 * Assign `setting` to `val`, or return `setting`'s value.
340 * app.set('foo', 'bar');
344 * Mounted servers inherit their parent server's settings.
346 * @param {String} setting
348 * @return {Server} for chaining
352 app.set = function set(setting, val) {
353 if (arguments.length === 1) {
355 return this.settings[setting];
358 debug('set "%s" to %o', setting, val);
361 this.settings[setting] = val;
363 // trigger matched settings
366 this.set('etag fn', compileETag(val));
369 this.set('query parser fn', compileQueryParser(val));
372 this.set('trust proxy fn', compileTrust(val));
374 // trust proxy inherit back-compat
375 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
387 * Return the app's absolute pathname
388 * based on the parent(s) that have
391 * For example if the application was
392 * mounted as "/admin", which itself
393 * was mounted as "/blog" then the
394 * return value would be "/blog/admin".
400 app.path = function path() {
402 ? this.parent.path() + this.mountpath
407 * Check if `setting` is enabled (truthy).
416 * @param {String} setting
421 app.enabled = function enabled(setting) {
422 return Boolean(this.set(setting));
426 * Check if `setting` is disabled.
428 * app.disabled('foo')
432 * app.disabled('foo')
435 * @param {String} setting
440 app.disabled = function disabled(setting) {
441 return !this.set(setting);
447 * @param {String} setting
448 * @return {app} for chaining
452 app.enable = function enable(setting) {
453 return this.set(setting, true);
459 * @param {String} setting
460 * @return {app} for chaining
464 app.disable = function disable(setting) {
465 return this.set(setting, false);
469 * Delegate `.VERB(...)` calls to `router.VERB(...)`.
472 methods.forEach(function(method){
473 app[method] = function(path){
474 if (method === 'get' && arguments.length === 1) {
476 return this.set(path);
481 var route = this._router.route(path);
482 route[method].apply(route, slice.call(arguments, 1));
488 * Special-cased "all" method, applying the given route `path`,
489 * middleware, and callback to _every_ HTTP method.
491 * @param {String} path
492 * @param {Function} ...
493 * @return {app} for chaining
497 app.all = function all(path) {
500 var route = this._router.route(path);
501 var args = slice.call(arguments, 1);
503 for (var i = 0; i < methods.length; i++) {
504 route[methods[i]].apply(route, args);
510 // del -> delete alias
512 app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');
515 * Render the given view `name` name with `options`
516 * and a callback accepting an error and the
517 * rendered template string.
521 * app.render('email', { name: 'Tobi' }, function(err, html){
525 * @param {String} name
526 * @param {Object|Function} options or fn
527 * @param {Function} callback
531 app.render = function render(name, options, callback) {
532 var cache = this.cache;
534 var engines = this.engines;
536 var renderOptions = {};
539 // support callback function as second arg
540 if (typeof options === 'function') {
546 merge(renderOptions, this.locals);
548 // merge options._locals
550 merge(renderOptions, opts._locals);
554 merge(renderOptions, opts);
556 // set .cache unless explicitly provided
557 if (renderOptions.cache == null) {
558 renderOptions.cache = this.enabled('view cache');
562 if (renderOptions.cache) {
568 var View = this.get('view');
570 view = new View(name, {
571 defaultEngine: this.get('view engine'),
572 root: this.get('views'),
577 var dirs = Array.isArray(view.root) && view.root.length > 1
578 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
579 : 'directory "' + view.root + '"'
580 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
586 if (renderOptions.cache) {
592 tryRender(view, renderOptions, done);
596 * Listen for connections.
598 * A node `http.Server` is returned, with this
599 * application (which is a `Function`) as its
600 * callback. If you wish to create both an HTTP
601 * and HTTPS server you may do so with the "http"
602 * and "https" modules as shown here:
604 * var http = require('http')
605 * , https = require('https')
606 * , express = require('express')
609 * http.createServer(app).listen(80);
610 * https.createServer({ ... }, app).listen(443);
612 * @return {http.Server}
616 app.listen = function listen() {
617 var server = http.createServer(this);
618 return server.listen.apply(server, arguments);
622 * Log error using console.error.
628 function logerror(err) {
629 /* istanbul ignore next */
630 if (this.get('env') !== 'test') console.error(err.stack || err.toString());
634 * Try rendering a view.
638 function tryRender(view, options, callback) {
640 view.render(options, callback);