application.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. /*!
  2. * express
  3. * Copyright(c) 2009-2013 TJ Holowaychuk
  4. * Copyright(c) 2013 Roman Shtylman
  5. * Copyright(c) 2014-2015 Douglas Christopher Wilson
  6. * MIT Licensed
  7. */
  8. 'use strict';
  9. /**
  10. * Module dependencies.
  11. * @private
  12. */
  13. var finalhandler = require('finalhandler');
  14. var debug = require('debug')('express:application');
  15. var View = require('./view');
  16. var http = require('node:http');
  17. var methods = require('./utils').methods;
  18. var compileETag = require('./utils').compileETag;
  19. var compileQueryParser = require('./utils').compileQueryParser;
  20. var compileTrust = require('./utils').compileTrust;
  21. var resolve = require('node:path').resolve;
  22. var once = require('once')
  23. var Router = require('router');
  24. /**
  25. * Module variables.
  26. * @private
  27. */
  28. var slice = Array.prototype.slice;
  29. var flatten = Array.prototype.flat;
  30. /**
  31. * Application prototype.
  32. */
  33. var app = exports = module.exports = {};
  34. /**
  35. * Variable for trust proxy inheritance back-compat
  36. * @private
  37. */
  38. var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
  39. /**
  40. * Initialize the server.
  41. *
  42. * - setup default configuration
  43. * - setup default middleware
  44. * - setup route reflection methods
  45. *
  46. * @private
  47. */
  48. app.init = function init() {
  49. var router = null;
  50. this.cache = Object.create(null);
  51. this.engines = Object.create(null);
  52. this.settings = Object.create(null);
  53. this.defaultConfiguration();
  54. // Setup getting to lazily add base router
  55. Object.defineProperty(this, 'router', {
  56. configurable: true,
  57. enumerable: true,
  58. get: function getrouter() {
  59. if (router === null) {
  60. router = new Router({
  61. caseSensitive: this.enabled('case sensitive routing'),
  62. strict: this.enabled('strict routing')
  63. });
  64. }
  65. return router;
  66. }
  67. });
  68. };
  69. /**
  70. * Initialize application configuration.
  71. * @private
  72. */
  73. app.defaultConfiguration = function defaultConfiguration() {
  74. var env = process.env.NODE_ENV || 'development';
  75. // default settings
  76. this.enable('x-powered-by');
  77. this.set('etag', 'weak');
  78. this.set('env', env);
  79. this.set('query parser', 'simple')
  80. this.set('subdomain offset', 2);
  81. this.set('trust proxy', false);
  82. // trust proxy inherit back-compat
  83. Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
  84. configurable: true,
  85. value: true
  86. });
  87. debug('booting in %s mode', env);
  88. this.on('mount', function onmount(parent) {
  89. // inherit trust proxy
  90. if (this.settings[trustProxyDefaultSymbol] === true
  91. && typeof parent.settings['trust proxy fn'] === 'function') {
  92. delete this.settings['trust proxy'];
  93. delete this.settings['trust proxy fn'];
  94. }
  95. // inherit protos
  96. Object.setPrototypeOf(this.request, parent.request)
  97. Object.setPrototypeOf(this.response, parent.response)
  98. Object.setPrototypeOf(this.engines, parent.engines)
  99. Object.setPrototypeOf(this.settings, parent.settings)
  100. });
  101. // setup locals
  102. this.locals = Object.create(null);
  103. // top-most app is mounted at /
  104. this.mountpath = '/';
  105. // default locals
  106. this.locals.settings = this.settings;
  107. // default configuration
  108. this.set('view', View);
  109. this.set('views', resolve('views'));
  110. this.set('jsonp callback name', 'callback');
  111. if (env === 'production') {
  112. this.enable('view cache');
  113. }
  114. };
  115. /**
  116. * Dispatch a req, res pair into the application. Starts pipeline processing.
  117. *
  118. * If no callback is provided, then default error handlers will respond
  119. * in the event of an error bubbling through the stack.
  120. *
  121. * @private
  122. */
  123. app.handle = function handle(req, res, callback) {
  124. // final handler
  125. var done = callback || finalhandler(req, res, {
  126. env: this.get('env'),
  127. onerror: logerror.bind(this)
  128. });
  129. // set powered by header
  130. if (this.enabled('x-powered-by')) {
  131. res.setHeader('X-Powered-By', 'Express');
  132. }
  133. // set circular references
  134. req.res = res;
  135. res.req = req;
  136. // alter the prototypes
  137. Object.setPrototypeOf(req, this.request)
  138. Object.setPrototypeOf(res, this.response)
  139. // setup locals
  140. if (!res.locals) {
  141. res.locals = Object.create(null);
  142. }
  143. this.router.handle(req, res, done);
  144. };
  145. /**
  146. * Proxy `Router#use()` to add middleware to the app router.
  147. * See Router#use() documentation for details.
  148. *
  149. * If the _fn_ parameter is an express app, then it will be
  150. * mounted at the _route_ specified.
  151. *
  152. * @public
  153. */
  154. app.use = function use(fn) {
  155. var offset = 0;
  156. var path = '/';
  157. // default path to '/'
  158. // disambiguate app.use([fn])
  159. if (typeof fn !== 'function') {
  160. var arg = fn;
  161. while (Array.isArray(arg) && arg.length !== 0) {
  162. arg = arg[0];
  163. }
  164. // first arg is the path
  165. if (typeof arg !== 'function') {
  166. offset = 1;
  167. path = fn;
  168. }
  169. }
  170. var fns = flatten.call(slice.call(arguments, offset), Infinity);
  171. if (fns.length === 0) {
  172. throw new TypeError('app.use() requires a middleware function')
  173. }
  174. // get router
  175. var router = this.router;
  176. fns.forEach(function (fn) {
  177. // non-express app
  178. if (!fn || !fn.handle || !fn.set) {
  179. return router.use(path, fn);
  180. }
  181. debug('.use app under %s', path);
  182. fn.mountpath = path;
  183. fn.parent = this;
  184. // restore .app property on req and res
  185. router.use(path, function mounted_app(req, res, next) {
  186. var orig = req.app;
  187. fn.handle(req, res, function (err) {
  188. Object.setPrototypeOf(req, orig.request)
  189. Object.setPrototypeOf(res, orig.response)
  190. next(err);
  191. });
  192. });
  193. // mounted an app
  194. fn.emit('mount', this);
  195. }, this);
  196. return this;
  197. };
  198. /**
  199. * Proxy to the app `Router#route()`
  200. * Returns a new `Route` instance for the _path_.
  201. *
  202. * Routes are isolated middleware stacks for specific paths.
  203. * See the Route api docs for details.
  204. *
  205. * @public
  206. */
  207. app.route = function route(path) {
  208. return this.router.route(path);
  209. };
  210. /**
  211. * Register the given template engine callback `fn`
  212. * as `ext`.
  213. *
  214. * By default will `require()` the engine based on the
  215. * file extension. For example if you try to render
  216. * a "foo.ejs" file Express will invoke the following internally:
  217. *
  218. * app.engine('ejs', require('ejs').__express);
  219. *
  220. * For engines that do not provide `.__express` out of the box,
  221. * or if you wish to "map" a different extension to the template engine
  222. * you may use this method. For example mapping the EJS template engine to
  223. * ".html" files:
  224. *
  225. * app.engine('html', require('ejs').renderFile);
  226. *
  227. * In this case EJS provides a `.renderFile()` method with
  228. * the same signature that Express expects: `(path, options, callback)`,
  229. * though note that it aliases this method as `ejs.__express` internally
  230. * so if you're using ".ejs" extensions you don't need to do anything.
  231. *
  232. * Some template engines do not follow this convention, the
  233. * [Consolidate.js](https://github.com/tj/consolidate.js)
  234. * library was created to map all of node's popular template
  235. * engines to follow this convention, thus allowing them to
  236. * work seamlessly within Express.
  237. *
  238. * @param {String} ext
  239. * @param {Function} fn
  240. * @return {app} for chaining
  241. * @public
  242. */
  243. app.engine = function engine(ext, fn) {
  244. if (typeof fn !== 'function') {
  245. throw new Error('callback function required');
  246. }
  247. // get file extension
  248. var extension = ext[0] !== '.'
  249. ? '.' + ext
  250. : ext;
  251. // store engine
  252. this.engines[extension] = fn;
  253. return this;
  254. };
  255. /**
  256. * Proxy to `Router#param()` with one added api feature. The _name_ parameter
  257. * can be an array of names.
  258. *
  259. * See the Router#param() docs for more details.
  260. *
  261. * @param {String|Array} name
  262. * @param {Function} fn
  263. * @return {app} for chaining
  264. * @public
  265. */
  266. app.param = function param(name, fn) {
  267. if (Array.isArray(name)) {
  268. for (var i = 0; i < name.length; i++) {
  269. this.param(name[i], fn);
  270. }
  271. return this;
  272. }
  273. this.router.param(name, fn);
  274. return this;
  275. };
  276. /**
  277. * Assign `setting` to `val`, or return `setting`'s value.
  278. *
  279. * app.set('foo', 'bar');
  280. * app.set('foo');
  281. * // => "bar"
  282. *
  283. * Mounted servers inherit their parent server's settings.
  284. *
  285. * @param {String} setting
  286. * @param {*} [val]
  287. * @return {Server} for chaining
  288. * @public
  289. */
  290. app.set = function set(setting, val) {
  291. if (arguments.length === 1) {
  292. // app.get(setting)
  293. return this.settings[setting];
  294. }
  295. debug('set "%s" to %o', setting, val);
  296. // set value
  297. this.settings[setting] = val;
  298. // trigger matched settings
  299. switch (setting) {
  300. case 'etag':
  301. this.set('etag fn', compileETag(val));
  302. break;
  303. case 'query parser':
  304. this.set('query parser fn', compileQueryParser(val));
  305. break;
  306. case 'trust proxy':
  307. this.set('trust proxy fn', compileTrust(val));
  308. // trust proxy inherit back-compat
  309. Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
  310. configurable: true,
  311. value: false
  312. });
  313. break;
  314. }
  315. return this;
  316. };
  317. /**
  318. * Return the app's absolute pathname
  319. * based on the parent(s) that have
  320. * mounted it.
  321. *
  322. * For example if the application was
  323. * mounted as "/admin", which itself
  324. * was mounted as "/blog" then the
  325. * return value would be "/blog/admin".
  326. *
  327. * @return {String}
  328. * @private
  329. */
  330. app.path = function path() {
  331. return this.parent
  332. ? this.parent.path() + this.mountpath
  333. : '';
  334. };
  335. /**
  336. * Check if `setting` is enabled (truthy).
  337. *
  338. * app.enabled('foo')
  339. * // => false
  340. *
  341. * app.enable('foo')
  342. * app.enabled('foo')
  343. * // => true
  344. *
  345. * @param {String} setting
  346. * @return {Boolean}
  347. * @public
  348. */
  349. app.enabled = function enabled(setting) {
  350. return Boolean(this.set(setting));
  351. };
  352. /**
  353. * Check if `setting` is disabled.
  354. *
  355. * app.disabled('foo')
  356. * // => true
  357. *
  358. * app.enable('foo')
  359. * app.disabled('foo')
  360. * // => false
  361. *
  362. * @param {String} setting
  363. * @return {Boolean}
  364. * @public
  365. */
  366. app.disabled = function disabled(setting) {
  367. return !this.set(setting);
  368. };
  369. /**
  370. * Enable `setting`.
  371. *
  372. * @param {String} setting
  373. * @return {app} for chaining
  374. * @public
  375. */
  376. app.enable = function enable(setting) {
  377. return this.set(setting, true);
  378. };
  379. /**
  380. * Disable `setting`.
  381. *
  382. * @param {String} setting
  383. * @return {app} for chaining
  384. * @public
  385. */
  386. app.disable = function disable(setting) {
  387. return this.set(setting, false);
  388. };
  389. /**
  390. * Delegate `.VERB(...)` calls to `router.VERB(...)`.
  391. */
  392. methods.forEach(function (method) {
  393. app[method] = function (path) {
  394. if (method === 'get' && arguments.length === 1) {
  395. // app.get(setting)
  396. return this.set(path);
  397. }
  398. var route = this.route(path);
  399. route[method].apply(route, slice.call(arguments, 1));
  400. return this;
  401. };
  402. });
  403. /**
  404. * Special-cased "all" method, applying the given route `path`,
  405. * middleware, and callback to _every_ HTTP method.
  406. *
  407. * @param {String} path
  408. * @param {Function} ...
  409. * @return {app} for chaining
  410. * @public
  411. */
  412. app.all = function all(path) {
  413. var route = this.route(path);
  414. var args = slice.call(arguments, 1);
  415. for (var i = 0; i < methods.length; i++) {
  416. route[methods[i]].apply(route, args);
  417. }
  418. return this;
  419. };
  420. /**
  421. * Render the given view `name` name with `options`
  422. * and a callback accepting an error and the
  423. * rendered template string.
  424. *
  425. * Example:
  426. *
  427. * app.render('email', { name: 'Tobi' }, function(err, html){
  428. * // ...
  429. * })
  430. *
  431. * @param {String} name
  432. * @param {Object|Function} options or fn
  433. * @param {Function} callback
  434. * @public
  435. */
  436. app.render = function render(name, options, callback) {
  437. var cache = this.cache;
  438. var done = callback;
  439. var engines = this.engines;
  440. var opts = options;
  441. var view;
  442. // support callback function as second arg
  443. if (typeof options === 'function') {
  444. done = options;
  445. opts = {};
  446. }
  447. // merge options
  448. var renderOptions = { ...this.locals, ...opts._locals, ...opts };
  449. // set .cache unless explicitly provided
  450. if (renderOptions.cache == null) {
  451. renderOptions.cache = this.enabled('view cache');
  452. }
  453. // primed cache
  454. if (renderOptions.cache) {
  455. view = cache[name];
  456. }
  457. // view
  458. if (!view) {
  459. var View = this.get('view');
  460. view = new View(name, {
  461. defaultEngine: this.get('view engine'),
  462. root: this.get('views'),
  463. engines: engines
  464. });
  465. if (!view.path) {
  466. var dirs = Array.isArray(view.root) && view.root.length > 1
  467. ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
  468. : 'directory "' + view.root + '"'
  469. var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
  470. err.view = view;
  471. return done(err);
  472. }
  473. // prime the cache
  474. if (renderOptions.cache) {
  475. cache[name] = view;
  476. }
  477. }
  478. // render
  479. tryRender(view, renderOptions, done);
  480. };
  481. /**
  482. * Listen for connections.
  483. *
  484. * A node `http.Server` is returned, with this
  485. * application (which is a `Function`) as its
  486. * callback. If you wish to create both an HTTP
  487. * and HTTPS server you may do so with the "http"
  488. * and "https" modules as shown here:
  489. *
  490. * var http = require('node:http')
  491. * , https = require('node:https')
  492. * , express = require('express')
  493. * , app = express();
  494. *
  495. * http.createServer(app).listen(80);
  496. * https.createServer({ ... }, app).listen(443);
  497. *
  498. * @return {http.Server}
  499. * @public
  500. */
  501. app.listen = function listen() {
  502. var server = http.createServer(this)
  503. var args = Array.prototype.slice.call(arguments)
  504. if (typeof args[args.length - 1] === 'function') {
  505. var done = args[args.length - 1] = once(args[args.length - 1])
  506. server.once('error', done)
  507. }
  508. return server.listen.apply(server, args)
  509. }
  510. /**
  511. * Log error using console.error.
  512. *
  513. * @param {Error} err
  514. * @private
  515. */
  516. function logerror(err) {
  517. /* istanbul ignore next */
  518. if (this.get('env') !== 'test') console.error(err.stack || err.toString());
  519. }
  520. /**
  521. * Try rendering a view.
  522. * @private
  523. */
  524. function tryRender(view, options, callback) {
  525. try {
  526. view.render(options, callback);
  527. } catch (err) {
  528. callback(err);
  529. }
  530. }