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 methods
= require('methods');
18 var debug
= require('debug')('express:application');
19 var View
= require('./view');
20 var http
= require('http');
21 var compileETag
= require('./utils').compileETag
;
22 var compileQueryParser
= require('./utils').compileQueryParser
;
23 var compileTrust
= require('./utils').compileTrust
;
24 var merge
= require('utils-merge');
25 var resolve
= require('path').resolve
;
26 var once
= require('once')
27 var Router
= require('router');
28 var setPrototypeOf
= require('setprototypeof')
35 var slice
= Array
.prototype.slice
;
36 var flatten
= Array
.prototype.flat
;
39 * Application prototype.
42 var app
= exports
= module
.exports
= {};
45 * Variable for trust proxy inheritance back-compat
49 var trustProxyDefaultSymbol
= '@@symbol:trust_proxy_default';
52 * Initialize the server.
54 * - setup default configuration
55 * - setup default middleware
56 * - setup route reflection methods
61 app
.init
= function init() {
64 this.cache
= Object
.create(null);
65 this.engines
= Object
.create(null);
66 this.settings
= Object
.create(null);
68 this.defaultConfiguration();
70 // Setup getting to lazily add base router
71 Object
.defineProperty(this, 'router', {
74 get: function getrouter() {
75 if (router
=== null) {
77 caseSensitive
: this.enabled('case sensitive routing'),
78 strict
: this.enabled('strict routing')
88 * Initialize application configuration.
92 app
.defaultConfiguration
= function defaultConfiguration() {
93 var env
= process
.env
.NODE_ENV
|| 'development';
96 this.enable('x-powered-by');
97 this.set('etag', 'weak');
99 this.set('query parser', 'simple')
100 this.set('subdomain offset', 2);
101 this.set('trust proxy', false);
103 // trust proxy inherit back-compat
104 Object
.defineProperty(this.settings
, trustProxyDefaultSymbol
, {
109 debug('booting in %s mode', env
);
111 this.on('mount', function onmount(parent
) {
112 // inherit trust proxy
113 if (this.settings
[trustProxyDefaultSymbol
] === true
114 && typeof parent
.settings
['trust proxy fn'] === 'function') {
115 delete this.settings
['trust proxy'];
116 delete this.settings
['trust proxy fn'];
120 setPrototypeOf(this.request
, parent
.request
)
121 setPrototypeOf(this.response
, parent
.response
)
122 setPrototypeOf(this.engines
, parent
.engines
)
123 setPrototypeOf(this.settings
, parent
.settings
)
127 this.locals
= Object
.create(null);
129 // top-most app is mounted at /
130 this.mountpath
= '/';
133 this.locals
.settings
= this.settings
;
135 // default configuration
136 this.set('view', View
);
137 this.set('views', resolve('views'));
138 this.set('jsonp callback name', 'callback');
140 if (env
=== 'production') {
141 this.enable('view cache');
146 * Dispatch a req, res pair into the application. Starts pipeline processing.
148 * If no callback is provided, then default error handlers will respond
149 * in the event of an error bubbling through the stack.
154 app
.handle
= function handle(req
, res
, callback
) {
156 var done
= callback
|| finalhandler(req
, res
, {
157 env
: this.get('env'),
158 onerror
: logerror
.bind(this)
161 // set powered by header
162 if (this.enabled('x-powered-by')) {
163 res
.setHeader('X-Powered-By', 'Express');
166 // set circular references
170 // alter the prototypes
171 setPrototypeOf(req
, this.request
)
172 setPrototypeOf(res
, this.response
)
176 res
.locals
= Object
.create(null);
179 this.router
.handle(req
, res
, done
);
183 * Proxy `Router#use()` to add middleware to the app router.
184 * See Router#use() documentation for details.
186 * If the _fn_ parameter is an express app, then it will be
187 * mounted at the _route_ specified.
192 app
.use = function use(fn
) {
196 // default path to '/'
197 // disambiguate app.use([fn])
198 if (typeof fn
!== 'function') {
201 while (Array
.isArray(arg
) && arg
.length
!== 0) {
205 // first arg is the path
206 if (typeof arg
!== 'function') {
212 var fns
= flatten
.call(slice
.call(arguments
, offset
), Infinity
);
214 if (fns
.length
=== 0) {
215 throw new TypeError('app.use() requires a middleware function')
219 var router
= this.router
;
221 fns
.forEach(function (fn
) {
223 if (!fn
|| !fn
.handle
|| !fn
.set) {
224 return router
.use(path
, fn
);
227 debug('.use app under %s', path
);
231 // restore .app property on req and res
232 router
.use(path
, function mounted_app(req
, res
, next
) {
234 fn
.handle(req
, res
, function (err
) {
235 setPrototypeOf(req
, orig
.request
)
236 setPrototypeOf(res
, orig
.response
)
242 fn
.emit('mount', this);
249 * Proxy to the app `Router#route()`
250 * Returns a new `Route` instance for the _path_.
252 * Routes are isolated middleware stacks for specific paths.
253 * See the Route api docs for details.
258 app
.route
= function route(path
) {
259 return this.router
.route(path
);
263 * Register the given template engine callback `fn`
266 * By default will `require()` the engine based on the
267 * file extension. For example if you try to render
268 * a "foo.ejs" file Express will invoke the following internally:
270 * app.engine('ejs', require('ejs').__express);
272 * For engines that do not provide `.__express` out of the box,
273 * or if you wish to "map" a different extension to the template engine
274 * you may use this method. For example mapping the EJS template engine to
277 * app.engine('html', require('ejs').renderFile);
279 * In this case EJS provides a `.renderFile()` method with
280 * the same signature that Express expects: `(path, options, callback)`,
281 * though note that it aliases this method as `ejs.__express` internally
282 * so if you're using ".ejs" extensions you don't need to do anything.
284 * Some template engines do not follow this convention, the
285 * [Consolidate.js](https://github.com/tj/consolidate.js)
286 * library was created to map all of node's popular template
287 * engines to follow this convention, thus allowing them to
288 * work seamlessly within Express.
290 * @param {String} ext
291 * @param {Function} fn
292 * @return {app} for chaining
296 app
.engine
= function engine(ext
, fn
) {
297 if (typeof fn
!== 'function') {
298 throw new Error('callback function required');
301 // get file extension
302 var extension
= ext
[0] !== '.'
307 this.engines
[extension
] = fn
;
313 * Proxy to `Router#param()` with one added api feature. The _name_ parameter
314 * can be an array of names.
316 * See the Router#param() docs for more details.
318 * @param {String|Array} name
319 * @param {Function} fn
320 * @return {app} for chaining
324 app
.param
= function param(name
, fn
) {
325 if (Array
.isArray(name
)) {
326 for (var i
= 0; i
< name
.length
; i
++) {
327 this.param(name
[i
], fn
);
333 this.router
.param(name
, fn
);
339 * Assign `setting` to `val`, or return `setting`'s value.
341 * app.set('foo', 'bar');
345 * Mounted servers inherit their parent server's settings.
347 * @param {String} setting
349 * @return {Server} for chaining
353 app
.set = function set(setting
, val
) {
354 if (arguments
.length
=== 1) {
356 return this.settings
[setting
];
359 debug('set "%s" to %o', setting
, val
);
362 this.settings
[setting
] = val
;
364 // trigger matched settings
367 this.set('etag fn', compileETag(val
));
370 this.set('query parser fn', compileQueryParser(val
));
373 this.set('trust proxy fn', compileTrust(val
));
375 // trust proxy inherit back-compat
376 Object
.defineProperty(this.settings
, trustProxyDefaultSymbol
, {
388 * Return the app's absolute pathname
389 * based on the parent(s) that have
392 * For example if the application was
393 * mounted as "/admin", which itself
394 * was mounted as "/blog" then the
395 * return value would be "/blog/admin".
401 app
.path
= function path() {
403 ? this.parent
.path() + this.mountpath
408 * Check if `setting` is enabled (truthy).
417 * @param {String} setting
422 app
.enabled
= function enabled(setting
) {
423 return Boolean(this.set(setting
));
427 * Check if `setting` is disabled.
429 * app.disabled('foo')
433 * app.disabled('foo')
436 * @param {String} setting
441 app
.disabled
= function disabled(setting
) {
442 return !this.set(setting
);
448 * @param {String} setting
449 * @return {app} for chaining
453 app
.enable
= function enable(setting
) {
454 return this.set(setting
, true);
460 * @param {String} setting
461 * @return {app} for chaining
465 app
.disable
= function disable(setting
) {
466 return this.set(setting
, false);
470 * Delegate `.VERB(...)` calls to `router.VERB(...)`.
473 methods
.forEach(function(method
){
474 app
[method
] = function(path
){
475 if (method
=== 'get' && arguments
.length
=== 1) {
477 return this.set(path
);
480 var route
= this.route(path
);
481 route
[method
].apply(route
, slice
.call(arguments
, 1));
487 * Special-cased "all" method, applying the given route `path`,
488 * middleware, and callback to _every_ HTTP method.
490 * @param {String} path
491 * @param {Function} ...
492 * @return {app} for chaining
496 app
.all
= function all(path
) {
497 var route
= this.route(path
);
498 var args
= slice
.call(arguments
, 1);
500 for (var i
= 0; i
< methods
.length
; i
++) {
501 route
[methods
[i
]].apply(route
, args
);
508 * Render the given view `name` name with `options`
509 * and a callback accepting an error and the
510 * rendered template string.
514 * app.render('email', { name: 'Tobi' }, function(err, html){
518 * @param {String} name
519 * @param {Object|Function} options or fn
520 * @param {Function} callback
524 app
.render
= function render(name
, options
, callback
) {
525 var cache
= this.cache
;
527 var engines
= this.engines
;
529 var renderOptions
= {};
532 // support callback function as second arg
533 if (typeof options
=== 'function') {
539 merge(renderOptions
, this.locals
);
541 // merge options._locals
543 merge(renderOptions
, opts
._locals
);
547 merge(renderOptions
, opts
);
549 // set .cache unless explicitly provided
550 if (renderOptions
.cache
== null) {
551 renderOptions
.cache
= this.enabled('view cache');
555 if (renderOptions
.cache
) {
561 var View
= this.get('view');
563 view
= new View(name
, {
564 defaultEngine
: this.get('view engine'),
565 root
: this.get('views'),
570 var dirs
= Array
.isArray(view
.root
) && view
.root
.length
> 1
571 ? 'directories "' + view
.root
.slice(0, -1).join('", "') + '" or "' + view
.root
[view
.root
.length
- 1] + '"'
572 : 'directory "' + view
.root
+ '"'
573 var err
= new Error('Failed to lookup view "' + name
+ '" in views ' + dirs
);
579 if (renderOptions
.cache
) {
585 tryRender(view
, renderOptions
, done
);
589 * Listen for connections.
591 * A node `http.Server` is returned, with this
592 * application (which is a `Function`) as its
593 * callback. If you wish to create both an HTTP
594 * and HTTPS server you may do so with the "http"
595 * and "https" modules as shown here:
597 * var http = require('http')
598 * , https = require('https')
599 * , express = require('express')
602 * http.createServer(app).listen(80);
603 * https.createServer({ ... }, app).listen(443);
605 * @return {http.Server}
609 app
.listen
= function listen () {
610 var server
= http
.createServer(this)
611 var args
= Array
.prototype.slice
.call(arguments
)
612 if (typeof args
[args
.length
- 1] === 'function') {
613 var done
= args
[args
.length
- 1] = once(args
[args
.length
- 1])
614 server
.once('error', done
)
616 return server
.listen
.apply(server
, args
)
620 * Log error using console.error.
626 function logerror(err
) {
627 /* istanbul ignore next */
628 if (this.get('env') !== 'test') console
.error(err
.stack
|| err
.toString());
632 * Try rendering a view.
636 function tryRender(view
, options
, callback
) {
638 view
.render(options
, callback
);