4.12.2
[express.git] / lib / application.js
blob5ec44248cad7c3febe1eee6ba3202444c39bf09a
1 /*!
2 * express
3 * Copyright(c) 2009-2013 TJ Holowaychuk
4 * Copyright(c) 2013 Roman Shtylman
5 * Copyright(c) 2014-2015 Douglas Christopher Wilson
6 * MIT Licensed
7 */
9 /**
10 * Module dependencies.
11 * @api private
14 var finalhandler = require('finalhandler');
15 var flatten = require('./utils').flatten;
16 var Router = require('./router');
17 var methods = require('methods');
18 var middleware = require('./middleware/init');
19 var query = require('./middleware/query');
20 var debug = require('debug')('express:application');
21 var View = require('./view');
22 var http = require('http');
23 var compileETag = require('./utils').compileETag;
24 var compileQueryParser = require('./utils').compileQueryParser;
25 var compileTrust = require('./utils').compileTrust;
26 var deprecate = require('depd')('express');
27 var merge = require('utils-merge');
28 var resolve = require('path').resolve;
29 var slice = Array.prototype.slice;
31 /**
32 * Application prototype.
35 var app = exports = module.exports = {};
37 /**
38 * Variable for trust proxy inheritance back-compat
39 * @api private
42 var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
44 /**
45 * Initialize the server.
47 * - setup default configuration
48 * - setup default middleware
49 * - setup route reflection methods
51 * @api private
54 app.init = function(){
55 this.cache = {};
56 this.settings = {};
57 this.engines = {};
58 this.defaultConfiguration();
61 /**
62 * Initialize application configuration.
64 * @api private
67 app.defaultConfiguration = function(){
68 // default settings
69 this.enable('x-powered-by');
70 this.set('etag', 'weak');
71 var env = process.env.NODE_ENV || 'development';
72 this.set('env', env);
73 this.set('query parser', 'extended');
74 this.set('subdomain offset', 2);
75 this.set('trust proxy', false);
77 // trust proxy inherit back-compat
78 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
79 configurable: true,
80 value: true
81 });
83 debug('booting in %s mode', env);
85 this.on('mount', function onmount(parent) {
86 // inherit trust proxy
87 if (this.settings[trustProxyDefaultSymbol] === true
88 && typeof parent.settings['trust proxy fn'] === 'function') {
89 delete this.settings['trust proxy'];
90 delete this.settings['trust proxy fn'];
93 // inherit protos
94 this.request.__proto__ = parent.request;
95 this.response.__proto__ = parent.response;
96 this.engines.__proto__ = parent.engines;
97 this.settings.__proto__ = parent.settings;
98 });
100 // setup locals
101 this.locals = Object.create(null);
103 // top-most app is mounted at /
104 this.mountpath = '/';
106 // default locals
107 this.locals.settings = this.settings;
109 // default configuration
110 this.set('view', View);
111 this.set('views', resolve('views'));
112 this.set('jsonp callback name', 'callback');
114 if (env === 'production') {
115 this.enable('view cache');
118 Object.defineProperty(this, 'router', {
119 get: function() {
120 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.');
126 * lazily adds the base router if it has not yet been added.
128 * We cannot add the base router in the defaultConfiguration because
129 * it reads app settings which might be set after that has run.
131 * @api private
133 app.lazyrouter = function() {
134 if (!this._router) {
135 this._router = new Router({
136 caseSensitive: this.enabled('case sensitive routing'),
137 strict: this.enabled('strict routing')
140 this._router.use(query(this.get('query parser fn')));
141 this._router.use(middleware.init(this));
146 * Dispatch a req, res pair into the application. Starts pipeline processing.
148 * If no _done_ callback is provided, then default error handlers will respond
149 * in the event of an error bubbling through the stack.
151 * @api private
154 app.handle = function(req, res, done) {
155 var router = this._router;
157 // final handler
158 done = done || finalhandler(req, res, {
159 env: this.get('env'),
160 onerror: logerror.bind(this)
163 // no routes
164 if (!router) {
165 debug('no routes defined on app');
166 done();
167 return;
170 router.handle(req, res, done);
174 * Proxy `Router#use()` to add middleware to the app router.
175 * See Router#use() documentation for details.
177 * If the _fn_ parameter is an express app, then it will be
178 * mounted at the _route_ specified.
180 * @api public
183 app.use = function use(fn) {
184 var offset = 0;
185 var path = '/';
187 // default path to '/'
188 // disambiguate app.use([fn])
189 if (typeof fn !== 'function') {
190 var arg = fn;
192 while (Array.isArray(arg) && arg.length !== 0) {
193 arg = arg[0];
196 // first arg is the path
197 if (typeof arg !== 'function') {
198 offset = 1;
199 path = fn;
203 var fns = flatten(slice.call(arguments, offset));
205 if (fns.length === 0) {
206 throw new TypeError('app.use() requires middleware functions');
209 // setup router
210 this.lazyrouter();
211 var router = this._router;
213 fns.forEach(function (fn) {
214 // non-express app
215 if (!fn || !fn.handle || !fn.set) {
216 return router.use(path, fn);
219 debug('.use app under %s', path);
220 fn.mountpath = path;
221 fn.parent = this;
223 // restore .app property on req and res
224 router.use(path, function mounted_app(req, res, next) {
225 var orig = req.app;
226 fn.handle(req, res, function (err) {
227 req.__proto__ = orig.request;
228 res.__proto__ = orig.response;
229 next(err);
233 // mounted an app
234 fn.emit('mount', this);
235 }, this);
237 return this;
241 * Proxy to the app `Router#route()`
242 * Returns a new `Route` instance for the _path_.
244 * Routes are isolated middleware stacks for specific paths.
245 * See the Route api docs for details.
247 * @api public
250 app.route = function(path){
251 this.lazyrouter();
252 return this._router.route(path);
256 * Register the given template engine callback `fn`
257 * as `ext`.
259 * By default will `require()` the engine based on the
260 * file extension. For example if you try to render
261 * a "foo.jade" file Express will invoke the following internally:
263 * app.engine('jade', require('jade').__express);
265 * For engines that do not provide `.__express` out of the box,
266 * or if you wish to "map" a different extension to the template engine
267 * you may use this method. For example mapping the EJS template engine to
268 * ".html" files:
270 * app.engine('html', require('ejs').renderFile);
272 * In this case EJS provides a `.renderFile()` method with
273 * the same signature that Express expects: `(path, options, callback)`,
274 * though note that it aliases this method as `ejs.__express` internally
275 * so if you're using ".ejs" extensions you dont need to do anything.
277 * Some template engines do not follow this convention, the
278 * [Consolidate.js](https://github.com/tj/consolidate.js)
279 * library was created to map all of node's popular template
280 * engines to follow this convention, thus allowing them to
281 * work seamlessly within Express.
283 * @param {String} ext
284 * @param {Function} fn
285 * @return {app} for chaining
286 * @api public
289 app.engine = function(ext, fn){
290 if ('function' != typeof fn) throw new Error('callback function required');
291 if ('.' != ext[0]) ext = '.' + ext;
292 this.engines[ext] = fn;
293 return this;
297 * Proxy to `Router#param()` with one added api feature. The _name_ parameter
298 * can be an array of names.
300 * See the Router#param() docs for more details.
302 * @param {String|Array} name
303 * @param {Function} fn
304 * @return {app} for chaining
305 * @api public
308 app.param = function(name, fn){
309 this.lazyrouter();
311 if (Array.isArray(name)) {
312 name.forEach(function(key) {
313 this.param(key, fn);
314 }, this);
315 return this;
318 this._router.param(name, fn);
319 return this;
323 * Assign `setting` to `val`, or return `setting`'s value.
325 * app.set('foo', 'bar');
326 * app.get('foo');
327 * // => "bar"
329 * Mounted servers inherit their parent server's settings.
331 * @param {String} setting
332 * @param {*} [val]
333 * @return {Server} for chaining
334 * @api public
337 app.set = function(setting, val){
338 if (arguments.length === 1) {
339 // app.get(setting)
340 return this.settings[setting];
343 // set value
344 this.settings[setting] = val;
346 // trigger matched settings
347 switch (setting) {
348 case 'etag':
349 debug('compile etag %s', val);
350 this.set('etag fn', compileETag(val));
351 break;
352 case 'query parser':
353 debug('compile query parser %s', val);
354 this.set('query parser fn', compileQueryParser(val));
355 break;
356 case 'trust proxy':
357 debug('compile trust proxy %s', val);
358 this.set('trust proxy fn', compileTrust(val));
360 // trust proxy inherit back-compat
361 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
362 configurable: true,
363 value: false
366 break;
369 return this;
373 * Return the app's absolute pathname
374 * based on the parent(s) that have
375 * mounted it.
377 * For example if the application was
378 * mounted as "/admin", which itself
379 * was mounted as "/blog" then the
380 * return value would be "/blog/admin".
382 * @return {String}
383 * @api private
386 app.path = function(){
387 return this.parent
388 ? this.parent.path() + this.mountpath
389 : '';
393 * Check if `setting` is enabled (truthy).
395 * app.enabled('foo')
396 * // => false
398 * app.enable('foo')
399 * app.enabled('foo')
400 * // => true
402 * @param {String} setting
403 * @return {Boolean}
404 * @api public
407 app.enabled = function(setting){
408 return !!this.set(setting);
412 * Check if `setting` is disabled.
414 * app.disabled('foo')
415 * // => true
417 * app.enable('foo')
418 * app.disabled('foo')
419 * // => false
421 * @param {String} setting
422 * @return {Boolean}
423 * @api public
426 app.disabled = function(setting){
427 return !this.set(setting);
431 * Enable `setting`.
433 * @param {String} setting
434 * @return {app} for chaining
435 * @api public
438 app.enable = function(setting){
439 return this.set(setting, true);
443 * Disable `setting`.
445 * @param {String} setting
446 * @return {app} for chaining
447 * @api public
450 app.disable = function(setting){
451 return this.set(setting, false);
455 * Delegate `.VERB(...)` calls to `router.VERB(...)`.
458 methods.forEach(function(method){
459 app[method] = function(path){
460 if ('get' == method && 1 == arguments.length) return this.set(path);
462 this.lazyrouter();
464 var route = this._router.route(path);
465 route[method].apply(route, slice.call(arguments, 1));
466 return this;
471 * Special-cased "all" method, applying the given route `path`,
472 * middleware, and callback to _every_ HTTP method.
474 * @param {String} path
475 * @param {Function} ...
476 * @return {app} for chaining
477 * @api public
480 app.all = function(path){
481 this.lazyrouter();
483 var route = this._router.route(path);
484 var args = slice.call(arguments, 1);
485 methods.forEach(function(method){
486 route[method].apply(route, args);
489 return this;
492 // del -> delete alias
494 app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');
497 * Render the given view `name` name with `options`
498 * and a callback accepting an error and the
499 * rendered template string.
501 * Example:
503 * app.render('email', { name: 'Tobi' }, function(err, html){
504 * // ...
505 * })
507 * @param {String} name
508 * @param {String|Function} options or fn
509 * @param {Function} fn
510 * @api public
513 app.render = function(name, options, fn){
514 var opts = {};
515 var cache = this.cache;
516 var engines = this.engines;
517 var view;
519 // support callback function as second arg
520 if ('function' == typeof options) {
521 fn = options, options = {};
524 // merge app.locals
525 merge(opts, this.locals);
527 // merge options._locals
528 if (options._locals) {
529 merge(opts, options._locals);
532 // merge options
533 merge(opts, options);
535 // set .cache unless explicitly provided
536 opts.cache = null == opts.cache
537 ? this.enabled('view cache')
538 : opts.cache;
540 // primed cache
541 if (opts.cache) view = cache[name];
543 // view
544 if (!view) {
545 view = new (this.get('view'))(name, {
546 defaultEngine: this.get('view engine'),
547 root: this.get('views'),
548 engines: engines
551 if (!view.path) {
552 var dirs = Array.isArray(view.root) && view.root.length > 1
553 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
554 : 'directory "' + view.root + '"'
555 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
556 err.view = view;
557 return fn(err);
560 // prime the cache
561 if (opts.cache) cache[name] = view;
564 // render
565 try {
566 view.render(opts, fn);
567 } catch (err) {
568 fn(err);
573 * Listen for connections.
575 * A node `http.Server` is returned, with this
576 * application (which is a `Function`) as its
577 * callback. If you wish to create both an HTTP
578 * and HTTPS server you may do so with the "http"
579 * and "https" modules as shown here:
581 * var http = require('http')
582 * , https = require('https')
583 * , express = require('express')
584 * , app = express();
586 * http.createServer(app).listen(80);
587 * https.createServer({ ... }, app).listen(443);
589 * @return {http.Server}
590 * @api public
593 app.listen = function(){
594 var server = http.createServer(this);
595 return server.listen.apply(server, arguments);
599 * Log error using console.error.
601 * @param {Error} err
602 * @api private
605 function logerror(err){
606 if (this.get('env') !== 'test') console.error(err.stack || err.toString());