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');
34 var slice = Array.prototype.slice;
35 var flatten = Array.prototype.flat;
38 * Application prototype.
41 var app = exports = module.exports = {};
44 * Variable for trust proxy inheritance back-compat
48 var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
51 * Initialize the server.
53 * - setup default configuration
54 * - setup default middleware
55 * - setup route reflection methods
60 app.init = function init() {
63 this.cache = Object.create(null);
64 this.engines = Object.create(null);
65 this.settings = Object.create(null);
67 this.defaultConfiguration();
69 // Setup getting to lazily add base router
70 Object.defineProperty(this, 'router', {
73 get: function getrouter() {
74 if (router === null) {
76 caseSensitive: this.enabled('case sensitive routing'),
77 strict: this.enabled('strict routing')
87 * Initialize application configuration.
91 app.defaultConfiguration = function defaultConfiguration() {
92 var env = process.env.NODE_ENV || 'development';
95 this.enable('x-powered-by');
96 this.set('etag', 'weak');
98 this.set('query parser', 'simple')
99 this.set('subdomain offset', 2);
100 this.set('trust proxy', false);
102 // trust proxy inherit back-compat
103 Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
108 debug('booting in %s mode', env);
110 this.on('mount', function onmount(parent) {
111 // inherit trust proxy
112 if (this.settings[trustProxyDefaultSymbol] === true
113 && typeof parent.settings['trust proxy fn'] === 'function') {
114 delete this.settings['trust proxy'];
115 delete this.settings['trust proxy fn'];
119 Object.setPrototypeOf(this.request, parent.request)
120 Object.setPrototypeOf(this.response, parent.response)
121 Object.setPrototypeOf(this.engines, parent.engines)
122 Object.setPrototypeOf(this.settings, parent.settings)
126 this.locals = Object.create(null);
128 // top-most app is mounted at /
129 this.mountpath = '/';
132 this.locals.settings = this.settings;
134 // default configuration
135 this.set('view', View);
136 this.set('views', resolve('views'));
137 this.set('jsonp callback name', 'callback');
139 if (env === 'production') {
140 this.enable('view cache');
145 * Dispatch a req, res pair into the application. Starts pipeline processing.
147 * If no callback is provided, then default error handlers will respond
148 * in the event of an error bubbling through the stack.
153 app.handle = function handle(req, res, callback) {
155 var done = callback || finalhandler(req, res, {
156 env: this.get('env'),
157 onerror: logerror.bind(this)
160 // set powered by header
161 if (this.enabled('x-powered-by')) {
162 res.setHeader('X-Powered-By', 'Express');
165 // set circular references
169 // alter the prototypes
170 Object.setPrototypeOf(req, this.request)
171 Object.setPrototypeOf(res, this.response)
175 res.locals = Object.create(null);
178 this.router.handle(req, res, done);
182 * Proxy `Router#use()` to add middleware to the app router.
183 * See Router#use() documentation for details.
185 * If the _fn_ parameter is an express app, then it will be
186 * mounted at the _route_ specified.
191 app.use = function use(fn) {
195 // default path to '/'
196 // disambiguate app.use([fn])
197 if (typeof fn !== 'function') {
200 while (Array.isArray(arg) && arg.length !== 0) {
204 // first arg is the path
205 if (typeof arg !== 'function') {
211 var fns = flatten.call(slice.call(arguments, offset), Infinity);
213 if (fns.length === 0) {
214 throw new TypeError('app.use() requires a middleware function')
218 var router = this.router;
220 fns.forEach(function (fn) {
222 if (!fn || !fn.handle || !fn.set) {
223 return router.use(path, fn);
226 debug('.use app under %s', path);
230 // restore .app property on req and res
231 router.use(path, function mounted_app(req, res, next) {
233 fn.handle(req, res, function (err) {
234 Object.setPrototypeOf(req, orig.request)
235 Object.setPrototypeOf(res, orig.response)
241 fn.emit('mount', this);
248 * Proxy to the app `Router#route()`
249 * Returns a new `Route` instance for the _path_.
251 * Routes are isolated middleware stacks for specific paths.
252 * See the Route api docs for details.
257 app.route = function route(path) {
258 return this.router.route(path);
262 * Register the given template engine callback `fn`
265 * By default will `require()` the engine based on the
266 * file extension. For example if you try to render
267 * a "foo.ejs" file Express will invoke the following internally:
269 * app.engine('ejs', require('ejs').__express);
271 * For engines that do not provide `.__express` out of the box,
272 * or if you wish to "map" a different extension to the template engine
273 * you may use this method. For example mapping the EJS template engine to
276 * app.engine('html', require('ejs').renderFile);
278 * In this case EJS provides a `.renderFile()` method with
279 * the same signature that Express expects: `(path, options, callback)`,
280 * though note that it aliases this method as `ejs.__express` internally
281 * so if you're using ".ejs" extensions you don't need to do anything.
283 * Some template engines do not follow this convention, the
284 * [Consolidate.js](https://github.com/tj/consolidate.js)
285 * library was created to map all of node's popular template
286 * engines to follow this convention, thus allowing them to
287 * work seamlessly within Express.
289 * @param {String} ext
290 * @param {Function} fn
291 * @return {app} for chaining
295 app.engine = function engine(ext, fn) {
296 if (typeof fn !== 'function') {
297 throw new Error('callback function required');
300 // get file extension
301 var extension = ext[0] !== '.'
306 this.engines[extension] = fn;
312 * Proxy to `Router#param()` with one added api feature. The _name_ parameter
313 * can be an array of names.
315 * See the Router#param() docs for more details.
317 * @param {String|Array} name
318 * @param {Function} fn
319 * @return {app} for chaining
323 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);
479 var route = this.route(path);
480 route[method].apply(route, slice.call(arguments, 1));
486 * Special-cased "all" method, applying the given route `path`,
487 * middleware, and callback to _every_ HTTP method.
489 * @param {String} path
490 * @param {Function} ...
491 * @return {app} for chaining
495 app.all = function all(path) {
496 var route = this.route(path);
497 var args = slice.call(arguments, 1);
499 for (var i = 0; i < methods.length; i++) {
500 route[methods[i]].apply(route, args);
507 * Render the given view `name` name with `options`
508 * and a callback accepting an error and the
509 * rendered template string.
513 * app.render('email', { name: 'Tobi' }, function(err, html){
517 * @param {String} name
518 * @param {Object|Function} options or fn
519 * @param {Function} callback
523 app.render = function render(name, options, callback) {
524 var cache = this.cache;
526 var engines = this.engines;
528 var renderOptions = {};
531 // support callback function as second arg
532 if (typeof options === 'function') {
538 merge(renderOptions, this.locals);
540 // merge options._locals
542 merge(renderOptions, opts._locals);
546 merge(renderOptions, opts);
548 // set .cache unless explicitly provided
549 if (renderOptions.cache == null) {
550 renderOptions.cache = this.enabled('view cache');
554 if (renderOptions.cache) {
560 var View = this.get('view');
562 view = new View(name, {
563 defaultEngine: this.get('view engine'),
564 root: this.get('views'),
569 var dirs = Array.isArray(view.root) && view.root.length > 1
570 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
571 : 'directory "' + view.root + '"'
572 var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
578 if (renderOptions.cache) {
584 tryRender(view, renderOptions, done);
588 * Listen for connections.
590 * A node `http.Server` is returned, with this
591 * application (which is a `Function`) as its
592 * callback. If you wish to create both an HTTP
593 * and HTTPS server you may do so with the "http"
594 * and "https" modules as shown here:
596 * var http = require('http')
597 * , https = require('https')
598 * , express = require('express')
601 * http.createServer(app).listen(80);
602 * https.createServer({ ... }, app).listen(443);
604 * @return {http.Server}
608 app.listen = function listen () {
609 var server = http.createServer(this)
610 var args = Array.prototype.slice.call(arguments)
611 if (typeof args[args.length - 1] === 'function') {
612 var done = args[args.length - 1] = once(args[args.length - 1])
613 server.once('error', done)
615 return server.listen.apply(server, args)
619 * Log error using console.error.
625 function logerror(err) {
626 /* istanbul ignore next */
627 if (this.get('env') !== 'test') console.error(err.stack || err.toString());
631 * Try rendering a view.
635 function tryRender(view, options, callback) {
637 view.render(options, callback);