3 * Copyright(c) 2009-2013 TJ Holowaychuk
4 * Copyright(c) 2013 Roman Shtylman
5 * Copyright(c) 2014-2015 Douglas Christopher Wilson
10 * Module dependencies.
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
;
32 * Application prototype.
35 var app
= exports
= module
.exports
= {};
38 * Variable for trust proxy inheritance back-compat
42 var trustProxyDefaultSymbol
= '@@symbol:trust_proxy_default';
45 * Initialize the server.
47 * - setup default configuration
48 * - setup default middleware
49 * - setup route reflection methods
54 app
.init = function(){
58 this.defaultConfiguration();
62 * Initialize application configuration.
67 app
.defaultConfiguration = function(){
69 this.enable('x-powered-by');
70 this.set('etag', 'weak');
71 var env
= process
.env
.NODE_ENV
|| 'development';
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
, {
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'];
94 this.request
.__proto__
= parent
.request
;
95 this.response
.__proto__
= parent
.response
;
96 this.engines
.__proto__
= parent
.engines
;
97 this.settings
.__proto__
= parent
.settings
;
101 this.locals
= Object
.create(null);
103 // top-most app is mounted at /
104 this.mountpath
= '/';
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', {
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.
133 app
.lazyrouter = function() {
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.
154 app
.handle = function(req
, res
, done
) {
155 var router
= this._router
;
158 done
= done
|| finalhandler(req
, res
, {
159 env
: this.get('env'),
160 onerror
: logerror
.bind(this)
165 debug('no routes defined on app');
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.
183 app
.use = function use(fn
) {
187 // default path to '/'
188 // disambiguate app.use([fn])
189 if (typeof fn
!== 'function') {
192 while (Array
.isArray(arg
) && arg
.length
!== 0) {
196 // first arg is the path
197 if (typeof arg
!== 'function') {
203 var fns
= flatten(slice
.call(arguments
, offset
));
205 if (fns
.length
=== 0) {
206 throw new TypeError('app.use() requires middleware functions');
211 var router
= this._router
;
213 fns
.forEach(function (fn
) {
215 if (!fn
|| !fn
.handle
|| !fn
.set) {
216 return router
.use(path
, fn
);
219 debug('.use app under %s', path
);
223 // restore .app property on req and res
224 router
.use(path
, function mounted_app(req
, res
, next
) {
226 fn
.handle(req
, res
, function (err
) {
227 req
.__proto__
= orig
.request
;
228 res
.__proto__
= orig
.response
;
234 fn
.emit('mount', 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.
250 app
.route = function(path
){
252 return this._router
.route(path
);
256 * Register the given template engine callback `fn`
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
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
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
;
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
308 app
.param = function(name
, fn
){
311 if (Array
.isArray(name
)) {
312 name
.forEach(function(key
) {
318 this._router
.param(name
, fn
);
323 * Assign `setting` to `val`, or return `setting`'s value.
325 * app.set('foo', 'bar');
329 * Mounted servers inherit their parent server's settings.
331 * @param {String} setting
333 * @return {Server} for chaining
337 app
.set = function(setting
, val
){
338 if (arguments
.length
=== 1) {
340 return this.settings
[setting
];
344 this.settings
[setting
] = val
;
346 // trigger matched settings
349 debug('compile etag %s', val
);
350 this.set('etag fn', compileETag(val
));
353 debug('compile query parser %s', val
);
354 this.set('query parser fn', compileQueryParser(val
));
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
, {
373 * Return the app's absolute pathname
374 * based on the parent(s) that have
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".
386 app
.path = function(){
388 ? this.parent
.path() + this.mountpath
393 * Check if `setting` is enabled (truthy).
402 * @param {String} setting
407 app
.enabled = function(setting
){
408 return !!this.set(setting
);
412 * Check if `setting` is disabled.
414 * app.disabled('foo')
418 * app.disabled('foo')
421 * @param {String} setting
426 app
.disabled = function(setting
){
427 return !this.set(setting
);
433 * @param {String} setting
434 * @return {app} for chaining
438 app
.enable = function(setting
){
439 return this.set(setting
, true);
445 * @param {String} setting
446 * @return {app} for chaining
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
);
464 var route
= this._router
.route(path
);
465 route
[method
].apply(route
, slice
.call(arguments
, 1));
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
480 app
.all = function(path
){
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
);
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.
503 * app.render('email', { name: 'Tobi' }, function(err, html){
507 * @param {String} name
508 * @param {String|Function} options or fn
509 * @param {Function} fn
513 app
.render = function(name
, options
, fn
){
515 var cache
= this.cache
;
516 var engines
= this.engines
;
519 // support callback function as second arg
520 if ('function' == typeof options
) {
521 fn
= options
, options
= {};
525 merge(opts
, this.locals
);
527 // merge options._locals
528 if (options
._locals
) {
529 merge(opts
, options
._locals
);
533 merge(opts
, options
);
535 // set .cache unless explicitly provided
536 opts
.cache
= null == opts
.cache
537 ? this.enabled('view cache')
541 if (opts
.cache
) view
= cache
[name
];
545 view
= new (this.get('view'))(name
, {
546 defaultEngine
: this.get('view engine'),
547 root
: this.get('views'),
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
);
561 if (opts
.cache
) cache
[name
] = view
;
566 view
.render(opts
, fn
);
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')
586 * http.createServer(app).listen(80);
587 * https.createServer({ ... }, app).listen(443);
589 * @return {http.Server}
593 app
.listen = function(){
594 var server
= http
.createServer(this);
595 return server
.listen
.apply(server
, arguments
);
599 * Log error using console.error.
605 function logerror(err
){
606 if (this.get('env') !== 'test') console
.error(err
.stack
|| err
.toString());