5 var finalhandler = require('finalhandler');
6 var flatten = require('./utils').flatten;
7 var Router = require('./router');
8 var methods = require('methods');
9 var middleware = require('./middleware/init');
10 var query = require('./middleware/query');
11 var debug = require('debug')('express:application');
12 var View = require('./view');
13 var http = require('http');
14 var compileETag = require('./utils').compileETag;
15 var compileQueryParser = require('./utils').compileQueryParser;
16 var compileTrust = require('./utils').compileTrust;
17 var deprecate = require('depd')('express');
18 var merge = require('utils-merge');
19 var resolve = require('path').resolve;
20 var slice = Array.prototype.slice;
23 * Application prototype.
26 var app = exports = module.exports = {};
29 * Initialize the server.
31 * - setup default configuration
32 * - setup default middleware
33 * - setup route reflection methods
38 app.init = function(){
42 this.defaultConfiguration();
46 * Initialize application configuration.
51 app.defaultConfiguration = function(){
53 this.enable('x-powered-by');
54 this.set('etag', 'weak');
55 var env = process.env.NODE_ENV || 'development';
57 this.set('query parser', 'extended');
58 this.set('subdomain offset', 2);
59 this.set('trust proxy', false);
61 debug('booting in %s mode', env);
64 this.on('mount', function(parent){
65 this.request.__proto__ = parent.request;
66 this.response.__proto__ = parent.response;
67 this.engines.__proto__ = parent.engines;
68 this.settings.__proto__ = parent.settings;
72 this.locals = Object.create(null);
74 // top-most app is mounted at /
78 this.locals.settings = this.settings;
80 // default configuration
81 this.set('view', View);
82 this.set('views', resolve('views'));
83 this.set('jsonp callback name', 'callback');
85 if (env === 'production') {
86 this.enable('view cache');
89 Object.defineProperty(this, 'router', {
91 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.');
97 * lazily adds the base router if it has not yet been added.
99 * We cannot add the base router in the defaultConfiguration because
100 * it reads app settings which might be set after that has run.
104 app.lazyrouter = function() {
106 this._router = new Router({
107 caseSensitive: this.enabled('case sensitive routing'),
108 strict: this.enabled('strict routing')
111 this._router.use(query(this.get('query parser fn')));
112 this._router.use(middleware.init(this));
117 * Dispatch a req, res pair into the application. Starts pipeline processing.
119 * If no _done_ callback is provided, then default error handlers will respond
120 * in the event of an error bubbling through the stack.
125 app.handle = function(req, res, done) {
126 var router = this._router;
129 done = done || finalhandler(req, res, {
130 env: this.get('env'),
131 onerror: logerror.bind(this)
136 debug('no routes defined on app');
141 router.handle(req, res, done);
145 * Proxy `Router#use()` to add middleware to the app router.
146 * See Router#use() documentation for details.
148 * If the _fn_ parameter is an express app, then it will be
149 * mounted at the _route_ specified.
154 app.use = function use(fn) {
158 // default path to '/'
159 // disambiguate app.use([fn])
160 if (typeof fn !== 'function') {
163 while (Array.isArray(arg) && arg.length !== 0) {
167 // first arg is the path
168 if (typeof arg !== 'function') {
174 var fns = flatten(slice.call(arguments, offset));
176 if (fns.length === 0) {
177 throw new TypeError('app.use() requires middleware functions');
182 var router = this._router;
184 fns.forEach(function (fn) {
186 if (!fn || !fn.handle || !fn.set) {
187 return router.use(path, fn);
190 debug('.use app under %s', path);
194 // restore .app property on req and res
195 router.use(path, function mounted_app(req, res, next) {
197 fn.handle(req, res, function (err) {
198 req.__proto__ = orig.request;
199 res.__proto__ = orig.response;
205 fn.emit('mount', this);
212 * Proxy to the app `Router#route()`
213 * Returns a new `Route` instance for the _path_.
215 * Routes are isolated middleware stacks for specific paths.
216 * See the Route api docs for details.
221 app.route = function(path){
223 return this._router.route(path);
227 * Register the given template engine callback `fn`
230 * By default will `require()` the engine based on the
231 * file extension. For example if you try to render
232 * a "foo.jade" file Express will invoke the following internally:
234 * app.engine('jade', require('jade').__express);
236 * For engines that do not provide `.__express` out of the box,
237 * or if you wish to "map" a different extension to the template engine
238 * you may use this method. For example mapping the EJS template engine to
241 * app.engine('html', require('ejs').renderFile);
243 * In this case EJS provides a `.renderFile()` method with
244 * the same signature that Express expects: `(path, options, callback)`,
245 * though note that it aliases this method as `ejs.__express` internally
246 * so if you're using ".ejs" extensions you dont need to do anything.
248 * Some template engines do not follow this convention, the
249 * [Consolidate.js](https://github.com/tj/consolidate.js)
250 * library was created to map all of node's popular template
251 * engines to follow this convention, thus allowing them to
252 * work seamlessly within Express.
254 * @param {String} ext
255 * @param {Function} fn
256 * @return {app} for chaining
260 app.engine = function(ext, fn){
261 if ('function' != typeof fn) throw new Error('callback function required');
262 if ('.' != ext[0]) ext = '.' + ext;
263 this.engines[ext] = fn;
268 * Proxy to `Router#param()` with one added api feature. The _name_ parameter
269 * can be an array of names.
271 * See the Router#param() docs for more details.
273 * @param {String|Array} name
274 * @param {Function} fn
275 * @return {app} for chaining
279 app.param = function(name, fn){
282 if (Array.isArray(name)) {
283 name.forEach(function(key) {
289 this._router.param(name, fn);
294 * Assign `setting` to `val`, or return `setting`'s value.
296 * app.set('foo', 'bar');
300 * Mounted servers inherit their parent server's settings.
302 * @param {String} setting
304 * @return {Server} for chaining
308 app.set = function(setting, val){
309 if (arguments.length === 1) {
311 return this.settings[setting];
315 this.settings[setting] = val;
317 // trigger matched settings
320 debug('compile etag %s', val);
321 this.set('etag fn', compileETag(val));
324 debug('compile query parser %s', val);
325 this.set('query parser fn', compileQueryParser(val));
328 debug('compile trust proxy %s', val);
329 this.set('trust proxy fn', compileTrust(val));
337 * Return the app's absolute pathname
338 * based on the parent(s) that have
341 * For example if the application was
342 * mounted as "/admin", which itself
343 * was mounted as "/blog" then the
344 * return value would be "/blog/admin".
350 app.path = function(){
352 ? this.parent.path() + this.mountpath
357 * Check if `setting` is enabled (truthy).
366 * @param {String} setting
371 app.enabled = function(setting){
372 return !!this.set(setting);
376 * Check if `setting` is disabled.
378 * app.disabled('foo')
382 * app.disabled('foo')
385 * @param {String} setting
390 app.disabled = function(setting){
391 return !this.set(setting);
397 * @param {String} setting
398 * @return {app} for chaining
402 app.enable = function(setting){
403 return this.set(setting, true);
409 * @param {String} setting
410 * @return {app} for chaining
414 app.disable = function(setting){
415 return this.set(setting, false);
419 * Delegate `.VERB(...)` calls to `router.VERB(...)`.
422 methods.forEach(function(method){
423 app[method] = function(path){
424 if ('get' == method && 1 == arguments.length) return this.set(path);
428 var route = this._router.route(path);
429 route[method].apply(route, slice.call(arguments, 1));
435 * Special-cased "all" method, applying the given route `path`,
436 * middleware, and callback to _every_ HTTP method.
438 * @param {String} path
439 * @param {Function} ...
440 * @return {app} for chaining
444 app.all = function(path){
447 var route = this._router.route(path);
448 var args = slice.call(arguments, 1);
449 methods.forEach(function(method){
450 route[method].apply(route, args);
456 // del -> delete alias
458 app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');
461 * Render the given view `name` name with `options`
462 * and a callback accepting an error and the
463 * rendered template string.
467 * app.render('email', { name: 'Tobi' }, function(err, html){
471 * @param {String} name
472 * @param {String|Function} options or fn
473 * @param {Function} fn
477 app.render = function(name, options, fn){
479 var cache = this.cache;
480 var engines = this.engines;
483 // support callback function as second arg
484 if ('function' == typeof options) {
485 fn = options, options = {};
489 merge(opts, this.locals);
491 // merge options._locals
492 if (options._locals) {
493 merge(opts, options._locals);
497 merge(opts, options);
499 // set .cache unless explicitly provided
500 opts.cache = null == opts.cache
501 ? this.enabled('view cache')
505 if (opts.cache) view = cache[name];
509 view = new (this.get('view'))(name, {
510 defaultEngine: this.get('view engine'),
511 root: this.get('views'),
516 var dirs = Array.isArray(view.root) && view.root.length > 1
517 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
518 : 'directory "' + view.root + '"'
519 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
525 if (opts.cache) cache[name] = view;
530 view.render(opts, fn);
537 * Listen for connections.
539 * A node `http.Server` is returned, with this
540 * application (which is a `Function`) as its
541 * callback. If you wish to create both an HTTP
542 * and HTTPS server you may do so with the "http"
543 * and "https" modules as shown here:
545 * var http = require('http')
546 * , https = require('https')
547 * , express = require('express')
550 * http.createServer(app).listen(80);
551 * https.createServer({ ... }, app).listen(443);
553 * @return {http.Server}
557 app.listen = function(){
558 var server = http.createServer(this);
559 return server.listen.apply(server, arguments);
563 * Log error using console.error.
569 function logerror(err){
570 if (this.get('env') !== 'test') console.error(err.stack || err.toString());