rc@73: /** rc@73: * Module dependencies. rc@73: */ rc@73: rc@73: var mixin = require('utils-merge'); rc@73: var escapeHtml = require('escape-html'); rc@73: var Router = require('./router'); rc@73: var methods = require('methods'); rc@73: var middleware = require('./middleware/init'); rc@73: var query = require('./middleware/query'); rc@73: var debug = require('debug')('express:application'); rc@73: var View = require('./view'); rc@73: var http = require('http'); rc@73: var compileETag = require('./utils').compileETag; rc@73: var compileTrust = require('./utils').compileTrust; rc@73: var deprecate = require('./utils').deprecate; rc@73: var resolve = require('path').resolve; rc@73: rc@73: /** rc@73: * Application prototype. rc@73: */ rc@73: rc@73: var app = exports = module.exports = {}; rc@73: rc@73: /** rc@73: * Initialize the server. rc@73: * rc@73: * - setup default configuration rc@73: * - setup default middleware rc@73: * - setup route reflection methods rc@73: * rc@73: * @api private rc@73: */ rc@73: rc@73: app.init = function(){ rc@73: this.cache = {}; rc@73: this.settings = {}; rc@73: this.engines = {}; rc@73: this.defaultConfiguration(); rc@73: }; rc@73: rc@73: /** rc@73: * Initialize application configuration. rc@73: * rc@73: * @api private rc@73: */ rc@73: rc@73: app.defaultConfiguration = function(){ rc@73: // default settings rc@73: this.enable('x-powered-by'); rc@73: this.set('etag', 'weak'); rc@73: var env = process.env.NODE_ENV || 'development'; rc@73: this.set('env', env); rc@73: this.set('subdomain offset', 2); rc@73: this.set('trust proxy', false); rc@73: rc@73: debug('booting in %s mode', env); rc@73: rc@73: // inherit protos rc@73: this.on('mount', function(parent){ rc@73: this.request.__proto__ = parent.request; rc@73: this.response.__proto__ = parent.response; rc@73: this.engines.__proto__ = parent.engines; rc@73: this.settings.__proto__ = parent.settings; rc@73: }); rc@73: rc@73: // setup locals rc@73: this.locals = Object.create(null); rc@73: rc@73: // top-most app is mounted at / rc@73: this.mountpath = '/'; rc@73: rc@73: // default locals rc@73: this.locals.settings = this.settings; rc@73: rc@73: // default configuration rc@73: this.set('view', View); rc@73: this.set('views', resolve('views')); rc@73: this.set('jsonp callback name', 'callback'); rc@73: rc@73: if (env === 'production') { rc@73: this.enable('view cache'); rc@73: } rc@73: rc@73: Object.defineProperty(this, 'router', { rc@73: get: function() { rc@73: 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.'); rc@73: } rc@73: }); rc@73: }; rc@73: rc@73: /** rc@73: * lazily adds the base router if it has not yet been added. rc@73: * rc@73: * We cannot add the base router in the defaultConfiguration because rc@73: * it reads app settings which might be set after that has run. rc@73: * rc@73: * @api private rc@73: */ rc@73: app.lazyrouter = function() { rc@73: if (!this._router) { rc@73: this._router = new Router({ rc@73: caseSensitive: this.enabled('case sensitive routing'), rc@73: strict: this.enabled('strict routing') rc@73: }); rc@73: rc@73: this._router.use(query()); rc@73: this._router.use(middleware.init(this)); rc@73: } rc@73: }; rc@73: rc@73: /** rc@73: * Dispatch a req, res pair into the application. Starts pipeline processing. rc@73: * rc@73: * If no _done_ callback is provided, then default error handlers will respond rc@73: * in the event of an error bubbling through the stack. rc@73: * rc@73: * @api private rc@73: */ rc@73: rc@73: app.handle = function(req, res, done) { rc@73: var env = this.get('env'); rc@73: rc@73: this._router.handle(req, res, function(err) { rc@73: if (done) { rc@73: return done(err); rc@73: } rc@73: rc@73: // unhandled error rc@73: if (err) { rc@73: // default to 500 rc@73: if (res.statusCode < 400) res.statusCode = 500; rc@73: debug('default %s', res.statusCode); rc@73: rc@73: // respect err.status rc@73: if (err.status) res.statusCode = err.status; rc@73: rc@73: // production gets a basic error message rc@73: var msg = 'production' == env rc@73: ? http.STATUS_CODES[res.statusCode] rc@73: : err.stack || err.toString(); rc@73: msg = escapeHtml(msg); rc@73: rc@73: // log to stderr in a non-test env rc@73: if ('test' != env) console.error(err.stack || err.toString()); rc@73: if (res.headersSent) return req.socket.destroy(); rc@73: res.setHeader('Content-Type', 'text/html'); rc@73: res.setHeader('Content-Length', Buffer.byteLength(msg)); rc@73: if ('HEAD' == req.method) return res.end(); rc@73: res.end(msg); rc@73: return; rc@73: } rc@73: rc@73: // 404 rc@73: debug('default 404'); rc@73: res.statusCode = 404; rc@73: res.setHeader('Content-Type', 'text/html'); rc@73: if ('HEAD' == req.method) return res.end(); rc@73: res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n'); rc@73: }); rc@73: }; rc@73: rc@73: /** rc@73: * Proxy `Router#use()` to add middleware to the app router. rc@73: * See Router#use() documentation for details. rc@73: * rc@73: * If the _fn_ parameter is an express app, then it will be rc@73: * mounted at the _route_ specified. rc@73: * rc@73: * @api public rc@73: */ rc@73: rc@73: app.use = function(route, fn){ rc@73: var mount_app; rc@73: rc@73: // default route to '/' rc@73: if ('string' != typeof route) fn = route, route = '/'; rc@73: rc@73: // express app rc@73: if (fn.handle && fn.set) mount_app = fn; rc@73: rc@73: // restore .app property on req and res rc@73: if (mount_app) { rc@73: debug('.use app under %s', route); rc@73: mount_app.mountpath = route; rc@73: fn = function(req, res, next) { rc@73: var orig = req.app; rc@73: mount_app.handle(req, res, function(err) { rc@73: req.__proto__ = orig.request; rc@73: res.__proto__ = orig.response; rc@73: next(err); rc@73: }); rc@73: }; rc@73: } rc@73: rc@73: this.lazyrouter(); rc@73: this._router.use(route, fn); rc@73: rc@73: // mounted an app rc@73: if (mount_app) { rc@73: mount_app.parent = this; rc@73: mount_app.emit('mount', this); rc@73: } rc@73: rc@73: return this; rc@73: }; rc@73: rc@73: /** rc@73: * Proxy to the app `Router#route()` rc@73: * Returns a new `Route` instance for the _path_. rc@73: * rc@73: * Routes are isolated middleware stacks for specific paths. rc@73: * See the Route api docs for details. rc@73: * rc@73: * @api public rc@73: */ rc@73: rc@73: app.route = function(path){ rc@73: this.lazyrouter(); rc@73: return this._router.route(path); rc@73: }; rc@73: rc@73: /** rc@73: * Register the given template engine callback `fn` rc@73: * as `ext`. rc@73: * rc@73: * By default will `require()` the engine based on the rc@73: * file extension. For example if you try to render rc@73: * a "foo.jade" file Express will invoke the following internally: rc@73: * rc@73: * app.engine('jade', require('jade').__express); rc@73: * rc@73: * For engines that do not provide `.__express` out of the box, rc@73: * or if you wish to "map" a different extension to the template engine rc@73: * you may use this method. For example mapping the EJS template engine to rc@73: * ".html" files: rc@73: * rc@73: * app.engine('html', require('ejs').renderFile); rc@73: * rc@73: * In this case EJS provides a `.renderFile()` method with rc@73: * the same signature that Express expects: `(path, options, callback)`, rc@73: * though note that it aliases this method as `ejs.__express` internally rc@73: * so if you're using ".ejs" extensions you dont need to do anything. rc@73: * rc@73: * Some template engines do not follow this convention, the rc@73: * [Consolidate.js](https://github.com/visionmedia/consolidate.js) rc@73: * library was created to map all of node's popular template rc@73: * engines to follow this convention, thus allowing them to rc@73: * work seamlessly within Express. rc@73: * rc@73: * @param {String} ext rc@73: * @param {Function} fn rc@73: * @return {app} for chaining rc@73: * @api public rc@73: */ rc@73: rc@73: app.engine = function(ext, fn){ rc@73: if ('function' != typeof fn) throw new Error('callback function required'); rc@73: if ('.' != ext[0]) ext = '.' + ext; rc@73: this.engines[ext] = fn; rc@73: return this; rc@73: }; rc@73: rc@73: /** rc@73: * Proxy to `Router#param()` with one added api feature. The _name_ parameter rc@73: * can be an array of names. rc@73: * rc@73: * See the Router#param() docs for more details. rc@73: * rc@73: * @param {String|Array} name rc@73: * @param {Function} fn rc@73: * @return {app} for chaining rc@73: * @api public rc@73: */ rc@73: rc@73: app.param = function(name, fn){ rc@73: var self = this; rc@73: self.lazyrouter(); rc@73: rc@73: if (Array.isArray(name)) { rc@73: name.forEach(function(key) { rc@73: self.param(key, fn); rc@73: }); rc@73: return this; rc@73: } rc@73: rc@73: self._router.param(name, fn); rc@73: return this; rc@73: }; rc@73: rc@73: /** rc@73: * Assign `setting` to `val`, or return `setting`'s value. rc@73: * rc@73: * app.set('foo', 'bar'); rc@73: * app.get('foo'); rc@73: * // => "bar" rc@73: * rc@73: * Mounted servers inherit their parent server's settings. rc@73: * rc@73: * @param {String} setting rc@73: * @param {*} [val] rc@73: * @return {Server} for chaining rc@73: * @api public rc@73: */ rc@73: rc@73: app.set = function(setting, val){ rc@73: if (arguments.length === 1) { rc@73: // app.get(setting) rc@73: return this.settings[setting]; rc@73: } rc@73: rc@73: // set value rc@73: this.settings[setting] = val; rc@73: rc@73: // trigger matched settings rc@73: switch (setting) { rc@73: case 'etag': rc@73: debug('compile etag %s', val); rc@73: this.set('etag fn', compileETag(val)); rc@73: break; rc@73: case 'trust proxy': rc@73: debug('compile trust proxy %s', val); rc@73: this.set('trust proxy fn', compileTrust(val)); rc@73: break; rc@73: } rc@73: rc@73: return this; rc@73: }; rc@73: rc@73: /** rc@73: * Return the app's absolute pathname rc@73: * based on the parent(s) that have rc@73: * mounted it. rc@73: * rc@73: * For example if the application was rc@73: * mounted as "/admin", which itself rc@73: * was mounted as "/blog" then the rc@73: * return value would be "/blog/admin". rc@73: * rc@73: * @return {String} rc@73: * @api private rc@73: */ rc@73: rc@73: app.path = function(){ rc@73: return this.parent rc@73: ? this.parent.path() + this.mountpath rc@73: : ''; rc@73: }; rc@73: rc@73: /** rc@73: * Check if `setting` is enabled (truthy). rc@73: * rc@73: * app.enabled('foo') rc@73: * // => false rc@73: * rc@73: * app.enable('foo') rc@73: * app.enabled('foo') rc@73: * // => true rc@73: * rc@73: * @param {String} setting rc@73: * @return {Boolean} rc@73: * @api public rc@73: */ rc@73: rc@73: app.enabled = function(setting){ rc@73: return !!this.set(setting); rc@73: }; rc@73: rc@73: /** rc@73: * Check if `setting` is disabled. rc@73: * rc@73: * app.disabled('foo') rc@73: * // => true rc@73: * rc@73: * app.enable('foo') rc@73: * app.disabled('foo') rc@73: * // => false rc@73: * rc@73: * @param {String} setting rc@73: * @return {Boolean} rc@73: * @api public rc@73: */ rc@73: rc@73: app.disabled = function(setting){ rc@73: return !this.set(setting); rc@73: }; rc@73: rc@73: /** rc@73: * Enable `setting`. rc@73: * rc@73: * @param {String} setting rc@73: * @return {app} for chaining rc@73: * @api public rc@73: */ rc@73: rc@73: app.enable = function(setting){ rc@73: return this.set(setting, true); rc@73: }; rc@73: rc@73: /** rc@73: * Disable `setting`. rc@73: * rc@73: * @param {String} setting rc@73: * @return {app} for chaining rc@73: * @api public rc@73: */ rc@73: rc@73: app.disable = function(setting){ rc@73: return this.set(setting, false); rc@73: }; rc@73: rc@73: /** rc@73: * Delegate `.VERB(...)` calls to `router.VERB(...)`. rc@73: */ rc@73: rc@73: methods.forEach(function(method){ rc@73: app[method] = function(path){ rc@73: if ('get' == method && 1 == arguments.length) return this.set(path); rc@73: rc@73: this.lazyrouter(); rc@73: rc@73: var route = this._router.route(path); rc@73: route[method].apply(route, [].slice.call(arguments, 1)); rc@73: return this; rc@73: }; rc@73: }); rc@73: rc@73: /** rc@73: * Special-cased "all" method, applying the given route `path`, rc@73: * middleware, and callback to _every_ HTTP method. rc@73: * rc@73: * @param {String} path rc@73: * @param {Function} ... rc@73: * @return {app} for chaining rc@73: * @api public rc@73: */ rc@73: rc@73: app.all = function(path){ rc@73: this.lazyrouter(); rc@73: rc@73: var route = this._router.route(path); rc@73: var args = [].slice.call(arguments, 1); rc@73: methods.forEach(function(method){ rc@73: route[method].apply(route, args); rc@73: }); rc@73: rc@73: return this; rc@73: }; rc@73: rc@73: // del -> delete alias rc@73: rc@73: app.del = deprecate(app.delete, 'app.del: Use app.delete instead'); rc@73: rc@73: /** rc@73: * Render the given view `name` name with `options` rc@73: * and a callback accepting an error and the rc@73: * rendered template string. rc@73: * rc@73: * Example: rc@73: * rc@73: * app.render('email', { name: 'Tobi' }, function(err, html){ rc@73: * // ... rc@73: * }) rc@73: * rc@73: * @param {String} name rc@73: * @param {String|Function} options or fn rc@73: * @param {Function} fn rc@73: * @api public rc@73: */ rc@73: rc@73: app.render = function(name, options, fn){ rc@73: var opts = {}; rc@73: var cache = this.cache; rc@73: var engines = this.engines; rc@73: var view; rc@73: rc@73: // support callback function as second arg rc@73: if ('function' == typeof options) { rc@73: fn = options, options = {}; rc@73: } rc@73: rc@73: // merge app.locals rc@73: mixin(opts, this.locals); rc@73: rc@73: // merge options._locals rc@73: if (options._locals) mixin(opts, options._locals); rc@73: rc@73: // merge options rc@73: mixin(opts, options); rc@73: rc@73: // set .cache unless explicitly provided rc@73: opts.cache = null == opts.cache rc@73: ? this.enabled('view cache') rc@73: : opts.cache; rc@73: rc@73: // primed cache rc@73: if (opts.cache) view = cache[name]; rc@73: rc@73: // view rc@73: if (!view) { rc@73: view = new (this.get('view'))(name, { rc@73: defaultEngine: this.get('view engine'), rc@73: root: this.get('views'), rc@73: engines: engines rc@73: }); rc@73: rc@73: if (!view.path) { rc@73: var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"'); rc@73: err.view = view; rc@73: return fn(err); rc@73: } rc@73: rc@73: // prime the cache rc@73: if (opts.cache) cache[name] = view; rc@73: } rc@73: rc@73: // render rc@73: try { rc@73: view.render(opts, fn); rc@73: } catch (err) { rc@73: fn(err); rc@73: } rc@73: }; rc@73: rc@73: /** rc@73: * Listen for connections. rc@73: * rc@73: * A node `http.Server` is returned, with this rc@73: * application (which is a `Function`) as its rc@73: * callback. If you wish to create both an HTTP rc@73: * and HTTPS server you may do so with the "http" rc@73: * and "https" modules as shown here: rc@73: * rc@73: * var http = require('http') rc@73: * , https = require('https') rc@73: * , express = require('express') rc@73: * , app = express(); rc@73: * rc@73: * http.createServer(app).listen(80); rc@73: * https.createServer({ ... }, app).listen(443); rc@73: * rc@73: * @return {http.Server} rc@73: * @api public rc@73: */ rc@73: rc@73: app.listen = function(){ rc@73: var server = http.createServer(this); rc@73: return server.listen.apply(server, arguments); rc@73: };