You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.d.ts 34KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. // Type definitions for Express 4.16
  2. // Project: http://expressjs.com
  3. // Definitions by: Boris Yankov <https://github.com/borisyankov>
  4. // Michał Lytek <https://github.com/19majkel94>
  5. // Kacper Polak <https://github.com/kacepe>
  6. // Satana Charuwichitratana <https://github.com/micksatana>
  7. // Sami Jaber <https://github.com/samijaber>
  8. // aereal <https://github.com/aereal>
  9. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  10. // TypeScript Version: 2.3
  11. // This extracts the core definitions from express to prevent a circular dependency between express and serve-static
  12. /// <reference types="node" />
  13. declare global {
  14. namespace Express {
  15. // These open interfaces may be extended in an application-specific manner via declaration merging.
  16. // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/method-override/index.d.ts)
  17. interface Request { }
  18. interface Response { }
  19. interface Application { }
  20. }
  21. }
  22. import * as http from "http";
  23. import { EventEmitter } from "events";
  24. import { Options as RangeParserOptions, Result as RangeParserResult, Ranges as RangeParserRanges } from "range-parser";
  25. export interface NextFunction {
  26. // tslint:disable-next-line callable-types (In ts2.1 it thinks the type alias has no call signatures)
  27. (err?: any): void;
  28. }
  29. export interface Dictionary<T> { [key: string]: T; }
  30. export type ParamsDictionary = Dictionary<string>;
  31. export type ParamsArray = string[];
  32. export type Params = ParamsDictionary | ParamsArray;
  33. export interface RequestHandler<P extends Params = ParamsDictionary> {
  34. // tslint:disable-next-line callable-types (This is extended from and can't extend from a type alias in ts<2.2
  35. (req: Request<P>, res: Response, next: NextFunction): any;
  36. }
  37. export type ErrorRequestHandler<P extends Params = ParamsDictionary> = (err: any, req: Request<P>, res: Response, next: NextFunction) => any;
  38. export type PathParams = string | RegExp | Array<string | RegExp>;
  39. export type RequestHandlerParams<P extends Params = ParamsDictionary> = RequestHandler<P> | ErrorRequestHandler<P> | Array<RequestHandler<P> | ErrorRequestHandler<P>>;
  40. export interface IRouterMatcher<T> {
  41. // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
  42. <P extends Params = ParamsDictionary>(path: PathParams, ...handlers: Array<RequestHandler<P>>): T;
  43. // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
  44. <P extends Params = ParamsDictionary>(path: PathParams, ...handlers: Array<RequestHandlerParams<P>>): T;
  45. (path: PathParams, subApplication: Application): T;
  46. }
  47. export interface IRouterHandler<T> {
  48. (...handlers: RequestHandler[]): T;
  49. (...handlers: RequestHandlerParams[]): T;
  50. }
  51. export interface IRouter extends RequestHandler {
  52. /**
  53. * Map the given param placeholder `name`(s) to the given callback(s).
  54. *
  55. * Parameter mapping is used to provide pre-conditions to routes
  56. * which use normalized placeholders. For example a _:user_id_ parameter
  57. * could automatically load a user's information from the database without
  58. * any additional code,
  59. *
  60. * The callback uses the samesignature as middleware, the only differencing
  61. * being that the value of the placeholder is passed, in this case the _id_
  62. * of the user. Once the `next()` function is invoked, just like middleware
  63. * it will continue on to execute the route, or subsequent parameter functions.
  64. *
  65. * app.param('user_id', function(req, res, next, id){
  66. * User.find(id, function(err, user){
  67. * if (err) {
  68. * next(err);
  69. * } else if (user) {
  70. * req.user = user;
  71. * next();
  72. * } else {
  73. * next(new Error('failed to load user'));
  74. * }
  75. * });
  76. * });
  77. */
  78. param(name: string, handler: RequestParamHandler): this;
  79. /**
  80. * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param()
  81. *
  82. * @deprecated since version 4.11
  83. */
  84. param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this;
  85. /**
  86. * Special-cased "all" method, applying the given route `path`,
  87. * middleware, and callback to _every_ HTTP method.
  88. */
  89. all: IRouterMatcher<this>;
  90. get: IRouterMatcher<this>;
  91. post: IRouterMatcher<this>;
  92. put: IRouterMatcher<this>;
  93. delete: IRouterMatcher<this>;
  94. patch: IRouterMatcher<this>;
  95. options: IRouterMatcher<this>;
  96. head: IRouterMatcher<this>;
  97. checkout: IRouterMatcher<this>;
  98. connect: IRouterMatcher<this>;
  99. copy: IRouterMatcher<this>;
  100. lock: IRouterMatcher<this>;
  101. merge: IRouterMatcher<this>;
  102. mkactivity: IRouterMatcher<this>;
  103. mkcol: IRouterMatcher<this>;
  104. move: IRouterMatcher<this>;
  105. "m-search": IRouterMatcher<this>;
  106. notify: IRouterMatcher<this>;
  107. propfind: IRouterMatcher<this>;
  108. proppatch: IRouterMatcher<this>;
  109. purge: IRouterMatcher<this>;
  110. report: IRouterMatcher<this>;
  111. search: IRouterMatcher<this>;
  112. subscribe: IRouterMatcher<this>;
  113. trace: IRouterMatcher<this>;
  114. unlock: IRouterMatcher<this>;
  115. unsubscribe: IRouterMatcher<this>;
  116. use: IRouterHandler<this> & IRouterMatcher<this>;
  117. route(prefix: PathParams): IRoute;
  118. /**
  119. * Stack of configured routes
  120. */
  121. stack: any[];
  122. }
  123. export interface IRoute {
  124. path: string;
  125. stack: any;
  126. all: IRouterHandler<this>;
  127. get: IRouterHandler<this>;
  128. post: IRouterHandler<this>;
  129. put: IRouterHandler<this>;
  130. delete: IRouterHandler<this>;
  131. patch: IRouterHandler<this>;
  132. options: IRouterHandler<this>;
  133. head: IRouterHandler<this>;
  134. checkout: IRouterHandler<this>;
  135. copy: IRouterHandler<this>;
  136. lock: IRouterHandler<this>;
  137. merge: IRouterHandler<this>;
  138. mkactivity: IRouterHandler<this>;
  139. mkcol: IRouterHandler<this>;
  140. move: IRouterHandler<this>;
  141. "m-search": IRouterHandler<this>;
  142. notify: IRouterHandler<this>;
  143. purge: IRouterHandler<this>;
  144. report: IRouterHandler<this>;
  145. search: IRouterHandler<this>;
  146. subscribe: IRouterHandler<this>;
  147. trace: IRouterHandler<this>;
  148. unlock: IRouterHandler<this>;
  149. unsubscribe: IRouterHandler<this>;
  150. }
  151. export interface Router extends IRouter { }
  152. export interface CookieOptions {
  153. maxAge?: number;
  154. signed?: boolean;
  155. expires?: Date | boolean;
  156. httpOnly?: boolean;
  157. path?: string;
  158. domain?: string;
  159. secure?: boolean | 'auto';
  160. encode?: (val: string) => void;
  161. sameSite?: boolean | string;
  162. }
  163. export interface ByteRange { start: number; end: number; }
  164. export interface RequestRanges extends RangeParserRanges { }
  165. export type Errback = (err: Error) => void;
  166. /**
  167. * @param P For most requests, this should be `ParamsDictionary`, but if you're
  168. * using this in a route handler for a route that uses a `RegExp` or a wildcard
  169. * `string` path (e.g. `'/user/*'`), then `req.params` will be an array, in
  170. * which case you should use `ParamsArray` instead.
  171. *
  172. * @see https://expressjs.com/en/api.html#req.params
  173. *
  174. * @example
  175. * app.get('/user/:id', (req, res) => res.send(req.params.id)); // implicitly `ParamsDictionary`
  176. * app.get<ParamsArray>(/user\/(.*)/, (req, res) => res.send(req.params[0]));
  177. * app.get<ParamsArray>('/user/*', (req, res) => res.send(req.params[0]));
  178. */
  179. export interface Request<P extends Params = ParamsDictionary> extends http.IncomingMessage, Express.Request {
  180. /**
  181. * Return request header.
  182. *
  183. * The `Referrer` header field is special-cased,
  184. * both `Referrer` and `Referer` are interchangeable.
  185. *
  186. * Examples:
  187. *
  188. * req.get('Content-Type');
  189. * // => "text/plain"
  190. *
  191. * req.get('content-type');
  192. * // => "text/plain"
  193. *
  194. * req.get('Something');
  195. * // => undefined
  196. *
  197. * Aliased as `req.header()`.
  198. */
  199. get(name: "set-cookie"): string[] | undefined;
  200. get(name: string): string | undefined;
  201. header(name: "set-cookie"): string[] | undefined;
  202. header(name: string): string | undefined;
  203. /**
  204. * Check if the given `type(s)` is acceptable, returning
  205. * the best match when true, otherwise `undefined`, in which
  206. * case you should respond with 406 "Not Acceptable".
  207. *
  208. * The `type` value may be a single mime type string
  209. * such as "application/json", the extension name
  210. * such as "json", a comma-delimted list such as "json, html, text/plain",
  211. * or an array `["json", "html", "text/plain"]`. When a list
  212. * or array is given the _best_ match, if any is returned.
  213. *
  214. * Examples:
  215. *
  216. * // Accept: text/html
  217. * req.accepts('html');
  218. * // => "html"
  219. *
  220. * // Accept: text/*, application/json
  221. * req.accepts('html');
  222. * // => "html"
  223. * req.accepts('text/html');
  224. * // => "text/html"
  225. * req.accepts('json, text');
  226. * // => "json"
  227. * req.accepts('application/json');
  228. * // => "application/json"
  229. *
  230. * // Accept: text/*, application/json
  231. * req.accepts('image/png');
  232. * req.accepts('png');
  233. * // => undefined
  234. *
  235. * // Accept: text/*;q=.5, application/json
  236. * req.accepts(['html', 'json']);
  237. * req.accepts('html, json');
  238. * // => "json"
  239. */
  240. accepts(): string[];
  241. accepts(type: string): string | false;
  242. accepts(type: string[]): string | false;
  243. accepts(...type: string[]): string | false;
  244. /**
  245. * Returns the first accepted charset of the specified character sets,
  246. * based on the request's Accept-Charset HTTP header field.
  247. * If none of the specified charsets is accepted, returns false.
  248. *
  249. * For more information, or if you have issues or concerns, see accepts.
  250. */
  251. acceptsCharsets(): string[];
  252. acceptsCharsets(charset: string): string | false;
  253. acceptsCharsets(charset: string[]): string | false;
  254. acceptsCharsets(...charset: string[]): string | false;
  255. /**
  256. * Returns the first accepted encoding of the specified encodings,
  257. * based on the request's Accept-Encoding HTTP header field.
  258. * If none of the specified encodings is accepted, returns false.
  259. *
  260. * For more information, or if you have issues or concerns, see accepts.
  261. */
  262. acceptsEncodings(): string[];
  263. acceptsEncodings(encoding: string): string | false;
  264. acceptsEncodings(encoding: string[]): string | false;
  265. acceptsEncodings(...encoding: string[]): string | false;
  266. /**
  267. * Returns the first accepted language of the specified languages,
  268. * based on the request's Accept-Language HTTP header field.
  269. * If none of the specified languages is accepted, returns false.
  270. *
  271. * For more information, or if you have issues or concerns, see accepts.
  272. */
  273. acceptsLanguages(): string[];
  274. acceptsLanguages(lang: string): string | false;
  275. acceptsLanguages(lang: string[]): string | false;
  276. acceptsLanguages(...lang: string[]): string | false;
  277. /**
  278. * Parse Range header field, capping to the given `size`.
  279. *
  280. * Unspecified ranges such as "0-" require knowledge of your resource length. In
  281. * the case of a byte range this is of course the total number of bytes.
  282. * If the Range header field is not given `undefined` is returned.
  283. * If the Range header field is given, return value is a result of range-parser.
  284. * See more ./types/range-parser/index.d.ts
  285. *
  286. * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
  287. * should respond with 4 users when available, not 3.
  288. *
  289. */
  290. range(size: number, options?: RangeParserOptions): RangeParserRanges | RangeParserResult | undefined;
  291. /**
  292. * Return an array of Accepted media types
  293. * ordered from highest quality to lowest.
  294. */
  295. accepted: MediaType[];
  296. /**
  297. * @deprecated since 4.11 Use either req.params, req.body or req.query, as applicable.
  298. *
  299. * Return the value of param `name` when present or `defaultValue`.
  300. *
  301. * - Checks route placeholders, ex: _/user/:id_
  302. * - Checks body params, ex: id=12, {"id":12}
  303. * - Checks query string params, ex: ?id=12
  304. *
  305. * To utilize request bodies, `req.body`
  306. * should be an object. This can be done by using
  307. * the `connect.bodyParser()` middleware.
  308. */
  309. param(name: string, defaultValue?: any): string;
  310. /**
  311. * Check if the incoming request contains the "Content-Type"
  312. * header field, and it contains the give mime `type`.
  313. *
  314. * Examples:
  315. *
  316. * // With Content-Type: text/html; charset=utf-8
  317. * req.is('html');
  318. * req.is('text/html');
  319. * req.is('text/*');
  320. * // => true
  321. *
  322. * // When Content-Type is application/json
  323. * req.is('json');
  324. * req.is('application/json');
  325. * req.is('application/*');
  326. * // => true
  327. *
  328. * req.is('html');
  329. * // => false
  330. */
  331. is(type: string): string | false;
  332. /**
  333. * Return the protocol string "http" or "https"
  334. * when requested with TLS. When the "trust proxy"
  335. * setting is enabled the "X-Forwarded-Proto" header
  336. * field will be trusted. If you're running behind
  337. * a reverse proxy that supplies https for you this
  338. * may be enabled.
  339. */
  340. protocol: string;
  341. /**
  342. * Short-hand for:
  343. *
  344. * req.protocol == 'https'
  345. */
  346. secure: boolean;
  347. /**
  348. * Return the remote address, or when
  349. * "trust proxy" is `true` return
  350. * the upstream addr.
  351. */
  352. ip: string;
  353. /**
  354. * When "trust proxy" is `true`, parse
  355. * the "X-Forwarded-For" ip address list.
  356. *
  357. * For example if the value were "client, proxy1, proxy2"
  358. * you would receive the array `["client", "proxy1", "proxy2"]`
  359. * where "proxy2" is the furthest down-stream.
  360. */
  361. ips: string[];
  362. /**
  363. * Return subdomains as an array.
  364. *
  365. * Subdomains are the dot-separated parts of the host before the main domain of
  366. * the app. By default, the domain of the app is assumed to be the last two
  367. * parts of the host. This can be changed by setting "subdomain offset".
  368. *
  369. * For example, if the domain is "tobi.ferrets.example.com":
  370. * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
  371. * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
  372. */
  373. subdomains: string[];
  374. /**
  375. * Short-hand for `url.parse(req.url).pathname`.
  376. */
  377. path: string;
  378. /**
  379. * Parse the "Host" header field hostname.
  380. */
  381. hostname: string;
  382. /**
  383. * @deprecated Use hostname instead.
  384. */
  385. host: string;
  386. /**
  387. * Check if the request is fresh, aka
  388. * Last-Modified and/or the ETag
  389. * still match.
  390. */
  391. fresh: boolean;
  392. /**
  393. * Check if the request is stale, aka
  394. * "Last-Modified" and / or the "ETag" for the
  395. * resource has changed.
  396. */
  397. stale: boolean;
  398. /**
  399. * Check if the request was an _XMLHttpRequest_.
  400. */
  401. xhr: boolean;
  402. //body: { username: string; password: string; remember: boolean; title: string; };
  403. body: any;
  404. //cookies: { string; remember: boolean; };
  405. cookies: any;
  406. method: string;
  407. params: P;
  408. /** Clear cookie `name`. */
  409. clearCookie(name: string, options?: any): Response;
  410. query: any;
  411. route: any;
  412. signedCookies: any;
  413. originalUrl: string;
  414. url: string;
  415. baseUrl: string;
  416. app: Application;
  417. /**
  418. * After middleware.init executed, Request will contain res and next properties
  419. * See: express/lib/middleware/init.js
  420. */
  421. res?: Response;
  422. next?: NextFunction;
  423. }
  424. export interface MediaType {
  425. value: string;
  426. quality: number;
  427. type: string;
  428. subtype: string;
  429. }
  430. export type Send = (body?: any) => Response;
  431. export interface Response extends http.ServerResponse, Express.Response {
  432. /**
  433. * Set status `code`.
  434. */
  435. status(code: number): Response;
  436. /**
  437. * Set the response HTTP status code to `statusCode` and send its string representation as the response body.
  438. * @link http://expressjs.com/4x/api.html#res.sendStatus
  439. *
  440. * Examples:
  441. *
  442. * res.sendStatus(200); // equivalent to res.status(200).send('OK')
  443. * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
  444. * res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
  445. * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
  446. */
  447. sendStatus(code: number): Response;
  448. /**
  449. * Set Link header field with the given `links`.
  450. *
  451. * Examples:
  452. *
  453. * res.links({
  454. * next: 'http://api.example.com/users?page=2',
  455. * last: 'http://api.example.com/users?page=5'
  456. * });
  457. */
  458. links(links: any): Response;
  459. /**
  460. * Send a response.
  461. *
  462. * Examples:
  463. *
  464. * res.send(new Buffer('wahoo'));
  465. * res.send({ some: 'json' });
  466. * res.send('<p>some html</p>');
  467. * res.status(404).send('Sorry, cant find that');
  468. */
  469. send: Send;
  470. /**
  471. * Send JSON response.
  472. *
  473. * Examples:
  474. *
  475. * res.json(null);
  476. * res.json({ user: 'tj' });
  477. * res.status(500).json('oh noes!');
  478. * res.status(404).json('I dont have that');
  479. */
  480. json: Send;
  481. /**
  482. * Send JSON response with JSONP callback support.
  483. *
  484. * Examples:
  485. *
  486. * res.jsonp(null);
  487. * res.jsonp({ user: 'tj' });
  488. * res.status(500).jsonp('oh noes!');
  489. * res.status(404).jsonp('I dont have that');
  490. */
  491. jsonp: Send;
  492. /**
  493. * Transfer the file at the given `path`.
  494. *
  495. * Automatically sets the _Content-Type_ response header field.
  496. * The callback `fn(err)` is invoked when the transfer is complete
  497. * or when an error occurs. Be sure to check `res.sentHeader`
  498. * if you wish to attempt responding, as the header and some data
  499. * may have already been transferred.
  500. *
  501. * Options:
  502. *
  503. * - `maxAge` defaulting to 0 (can be string converted by `ms`)
  504. * - `root` root directory for relative filenames
  505. * - `headers` object of headers to serve with file
  506. * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
  507. *
  508. * Other options are passed along to `send`.
  509. *
  510. * Examples:
  511. *
  512. * The following example illustrates how `res.sendFile()` may
  513. * be used as an alternative for the `static()` middleware for
  514. * dynamic situations. The code backing `res.sendFile()` is actually
  515. * the same code, so HTTP cache support etc is identical.
  516. *
  517. * app.get('/user/:uid/photos/:file', function(req, res){
  518. * var uid = req.params.uid
  519. * , file = req.params.file;
  520. *
  521. * req.user.mayViewFilesFrom(uid, function(yes){
  522. * if (yes) {
  523. * res.sendFile('/uploads/' + uid + '/' + file);
  524. * } else {
  525. * res.send(403, 'Sorry! you cant see that.');
  526. * }
  527. * });
  528. * });
  529. *
  530. * @api public
  531. */
  532. sendFile(path: string, fn?: Errback): void;
  533. sendFile(path: string, options: any, fn?: Errback): void;
  534. /**
  535. * @deprecated Use sendFile instead.
  536. */
  537. sendfile(path: string): void;
  538. /**
  539. * @deprecated Use sendFile instead.
  540. */
  541. sendfile(path: string, options: any): void;
  542. /**
  543. * @deprecated Use sendFile instead.
  544. */
  545. sendfile(path: string, fn: Errback): void;
  546. /**
  547. * @deprecated Use sendFile instead.
  548. */
  549. sendfile(path: string, options: any, fn: Errback): void;
  550. /**
  551. * Transfer the file at the given `path` as an attachment.
  552. *
  553. * Optionally providing an alternate attachment `filename`,
  554. * and optional callback `fn(err)`. The callback is invoked
  555. * when the data transfer is complete, or when an error has
  556. * ocurred. Be sure to check `res.headerSent` if you plan to respond.
  557. *
  558. * The optional options argument passes through to the underlying
  559. * res.sendFile() call, and takes the exact same parameters.
  560. *
  561. * This method uses `res.sendfile()`.
  562. */
  563. download(path: string, fn?: Errback): void;
  564. download(path: string, filename: string, fn?: Errback): void;
  565. download(path: string, filename: string, options: any, fn?: Errback): void;
  566. /**
  567. * Set _Content-Type_ response header with `type` through `mime.lookup()`
  568. * when it does not contain "/", or set the Content-Type to `type` otherwise.
  569. *
  570. * Examples:
  571. *
  572. * res.type('.html');
  573. * res.type('html');
  574. * res.type('json');
  575. * res.type('application/json');
  576. * res.type('png');
  577. */
  578. contentType(type: string): Response;
  579. /**
  580. * Set _Content-Type_ response header with `type` through `mime.lookup()`
  581. * when it does not contain "/", or set the Content-Type to `type` otherwise.
  582. *
  583. * Examples:
  584. *
  585. * res.type('.html');
  586. * res.type('html');
  587. * res.type('json');
  588. * res.type('application/json');
  589. * res.type('png');
  590. */
  591. type(type: string): Response;
  592. /**
  593. * Respond to the Acceptable formats using an `obj`
  594. * of mime-type callbacks.
  595. *
  596. * This method uses `req.accepted`, an array of
  597. * acceptable types ordered by their quality values.
  598. * When "Accept" is not present the _first_ callback
  599. * is invoked, otherwise the first match is used. When
  600. * no match is performed the server responds with
  601. * 406 "Not Acceptable".
  602. *
  603. * Content-Type is set for you, however if you choose
  604. * you may alter this within the callback using `res.type()`
  605. * or `res.set('Content-Type', ...)`.
  606. *
  607. * res.format({
  608. * 'text/plain': function(){
  609. * res.send('hey');
  610. * },
  611. *
  612. * 'text/html': function(){
  613. * res.send('<p>hey</p>');
  614. * },
  615. *
  616. * 'appliation/json': function(){
  617. * res.send({ message: 'hey' });
  618. * }
  619. * });
  620. *
  621. * In addition to canonicalized MIME types you may
  622. * also use extnames mapped to these types:
  623. *
  624. * res.format({
  625. * text: function(){
  626. * res.send('hey');
  627. * },
  628. *
  629. * html: function(){
  630. * res.send('<p>hey</p>');
  631. * },
  632. *
  633. * json: function(){
  634. * res.send({ message: 'hey' });
  635. * }
  636. * });
  637. *
  638. * By default Express passes an `Error`
  639. * with a `.status` of 406 to `next(err)`
  640. * if a match is not made. If you provide
  641. * a `.default` callback it will be invoked
  642. * instead.
  643. */
  644. format(obj: any): Response;
  645. /**
  646. * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
  647. */
  648. attachment(filename?: string): Response;
  649. /**
  650. * Set header `field` to `val`, or pass
  651. * an object of header fields.
  652. *
  653. * Examples:
  654. *
  655. * res.set('Foo', ['bar', 'baz']);
  656. * res.set('Accept', 'application/json');
  657. * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
  658. *
  659. * Aliased as `res.header()`.
  660. */
  661. set(field: any): Response;
  662. set(field: string, value?: string): Response;
  663. set(field: string, value?: string[]): Response;
  664. header(field: any): Response;
  665. header(field: string, value?: string): Response;
  666. // Property indicating if HTTP headers has been sent for the response.
  667. headersSent: boolean;
  668. /** Get value for header `field`. */
  669. get(field: string): string;
  670. /** Clear cookie `name`. */
  671. clearCookie(name: string, options?: any): Response;
  672. /**
  673. * Set cookie `name` to `val`, with the given `options`.
  674. *
  675. * Options:
  676. *
  677. * - `maxAge` max-age in milliseconds, converted to `expires`
  678. * - `signed` sign the cookie
  679. * - `path` defaults to "/"
  680. *
  681. * Examples:
  682. *
  683. * // "Remember Me" for 15 minutes
  684. * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
  685. *
  686. * // save as above
  687. * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
  688. */
  689. cookie(name: string, val: string, options: CookieOptions): Response;
  690. cookie(name: string, val: any, options: CookieOptions): Response;
  691. cookie(name: string, val: any): Response;
  692. /**
  693. * Set the location header to `url`.
  694. *
  695. * The given `url` can also be the name of a mapped url, for
  696. * example by default express supports "back" which redirects
  697. * to the _Referrer_ or _Referer_ headers or "/".
  698. *
  699. * Examples:
  700. *
  701. * res.location('/foo/bar').;
  702. * res.location('http://example.com');
  703. * res.location('../login'); // /blog/post/1 -> /blog/login
  704. *
  705. * Mounting:
  706. *
  707. * When an application is mounted and `res.location()`
  708. * is given a path that does _not_ lead with "/" it becomes
  709. * relative to the mount-point. For example if the application
  710. * is mounted at "/blog", the following would become "/blog/login".
  711. *
  712. * res.location('login');
  713. *
  714. * While the leading slash would result in a location of "/login":
  715. *
  716. * res.location('/login');
  717. */
  718. location(url: string): Response;
  719. /**
  720. * Redirect to the given `url` with optional response `status`
  721. * defaulting to 302.
  722. *
  723. * The resulting `url` is determined by `res.location()`, so
  724. * it will play nicely with mounted apps, relative paths,
  725. * `"back"` etc.
  726. *
  727. * Examples:
  728. *
  729. * res.redirect('/foo/bar');
  730. * res.redirect('http://example.com');
  731. * res.redirect(301, 'http://example.com');
  732. * res.redirect('http://example.com', 301);
  733. * res.redirect('../login'); // /blog/post/1 -> /blog/login
  734. */
  735. redirect(url: string): void;
  736. redirect(status: number, url: string): void;
  737. redirect(url: string, status: number): void;
  738. /**
  739. * Render `view` with the given `options` and optional callback `fn`.
  740. * When a callback function is given a response will _not_ be made
  741. * automatically, otherwise a response of _200_ and _text/html_ is given.
  742. *
  743. * Options:
  744. *
  745. * - `cache` boolean hinting to the engine it should cache
  746. * - `filename` filename of the view being rendered
  747. */
  748. render(view: string, options?: object, callback?: (err: Error, html: string) => void): void;
  749. render(view: string, callback?: (err: Error, html: string) => void): void;
  750. locals: any;
  751. charset: string;
  752. /**
  753. * Adds the field to the Vary response header, if it is not there already.
  754. * Examples:
  755. *
  756. * res.vary('User-Agent').render('docs');
  757. *
  758. */
  759. vary(field: string): Response;
  760. app: Application;
  761. /**
  762. * Appends the specified value to the HTTP response header field.
  763. * If the header is not already set, it creates the header with the specified value.
  764. * The value parameter can be a string or an array.
  765. *
  766. * Note: calling res.set() after res.append() will reset the previously-set header value.
  767. *
  768. * @since 4.11.0
  769. */
  770. append(field: string, value?: string[] | string): Response;
  771. /**
  772. * After middleware.init executed, Response will contain req property
  773. * See: express/lib/middleware/init.js
  774. */
  775. req?: Request;
  776. }
  777. export interface Handler extends RequestHandler { }
  778. export type RequestParamHandler = (req: Request, res: Response, next: NextFunction, value: any, name: string) => any;
  779. export type ApplicationRequestHandler<T> = IRouterHandler<T> & IRouterMatcher<T> & ((...handlers: RequestHandlerParams[]) => T);
  780. export interface Application extends EventEmitter, IRouter, Express.Application {
  781. /**
  782. * Express instance itself is a request handler, which could be invoked without
  783. * third argument.
  784. */
  785. (req: Request | http.IncomingMessage, res: Response | http.ServerResponse): any;
  786. /**
  787. * Initialize the server.
  788. *
  789. * - setup default configuration
  790. * - setup default middleware
  791. * - setup route reflection methods
  792. */
  793. init(): void;
  794. /**
  795. * Initialize application configuration.
  796. */
  797. defaultConfiguration(): void;
  798. /**
  799. * Register the given template engine callback `fn`
  800. * as `ext`.
  801. *
  802. * By default will `require()` the engine based on the
  803. * file extension. For example if you try to render
  804. * a "foo.jade" file Express will invoke the following internally:
  805. *
  806. * app.engine('jade', require('jade').__express);
  807. *
  808. * For engines that do not provide `.__express` out of the box,
  809. * or if you wish to "map" a different extension to the template engine
  810. * you may use this method. For example mapping the EJS template engine to
  811. * ".html" files:
  812. *
  813. * app.engine('html', require('ejs').renderFile);
  814. *
  815. * In this case EJS provides a `.renderFile()` method with
  816. * the same signature that Express expects: `(path, options, callback)`,
  817. * though note that it aliases this method as `ejs.__express` internally
  818. * so if you're using ".ejs" extensions you dont need to do anything.
  819. *
  820. * Some template engines do not follow this convention, the
  821. * [Consolidate.js](https://github.com/visionmedia/consolidate.js)
  822. * library was created to map all of node's popular template
  823. * engines to follow this convention, thus allowing them to
  824. * work seamlessly within Express.
  825. */
  826. engine(ext: string, fn: (path: string, options: object, callback: (e: any, rendered: string) => void) => void): Application;
  827. /**
  828. * Assign `setting` to `val`, or return `setting`'s value.
  829. *
  830. * app.set('foo', 'bar');
  831. * app.get('foo');
  832. * // => "bar"
  833. * app.set('foo', ['bar', 'baz']);
  834. * app.get('foo');
  835. * // => ["bar", "baz"]
  836. *
  837. * Mounted servers inherit their parent server's settings.
  838. */
  839. set(setting: string, val: any): Application;
  840. get: ((name: string) => any) & IRouterMatcher<this>;
  841. param(name: string | string[], handler: RequestParamHandler): this;
  842. /**
  843. * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param()
  844. *
  845. * @deprecated since version 4.11
  846. */
  847. param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this;
  848. /**
  849. * Return the app's absolute pathname
  850. * based on the parent(s) that have
  851. * mounted it.
  852. *
  853. * For example if the application was
  854. * mounted as "/admin", which itself
  855. * was mounted as "/blog" then the
  856. * return value would be "/blog/admin".
  857. */
  858. path(): string;
  859. /**
  860. * Check if `setting` is enabled (truthy).
  861. *
  862. * app.enabled('foo')
  863. * // => false
  864. *
  865. * app.enable('foo')
  866. * app.enabled('foo')
  867. * // => true
  868. */
  869. enabled(setting: string): boolean;
  870. /**
  871. * Check if `setting` is disabled.
  872. *
  873. * app.disabled('foo')
  874. * // => true
  875. *
  876. * app.enable('foo')
  877. * app.disabled('foo')
  878. * // => false
  879. */
  880. disabled(setting: string): boolean;
  881. /** Enable `setting`. */
  882. enable(setting: string): Application;
  883. /** Disable `setting`. */
  884. disable(setting: string): Application;
  885. /**
  886. * Render the given view `name` name with `options`
  887. * and a callback accepting an error and the
  888. * rendered template string.
  889. *
  890. * Example:
  891. *
  892. * app.render('email', { name: 'Tobi' }, function(err, html){
  893. * // ...
  894. * })
  895. */
  896. render(name: string, options?: object, callback?: (err: Error, html: string) => void): void;
  897. render(name: string, callback: (err: Error, html: string) => void): void;
  898. /**
  899. * Listen for connections.
  900. *
  901. * A node `http.Server` is returned, with this
  902. * application (which is a `Function`) as its
  903. * callback. If you wish to create both an HTTP
  904. * and HTTPS server you may do so with the "http"
  905. * and "https" modules as shown here:
  906. *
  907. * var http = require('http')
  908. * , https = require('https')
  909. * , express = require('express')
  910. * , app = express();
  911. *
  912. * http.createServer(app).listen(80);
  913. * https.createServer({ ... }, app).listen(443);
  914. */
  915. listen(port: number, hostname: string, backlog: number, callback?: (...args: any[]) => void): http.Server;
  916. listen(port: number, hostname: string, callback?: (...args: any[]) => void): http.Server;
  917. listen(port: number, callback?: (...args: any[]) => void): http.Server;
  918. listen(callback?: (...args: any[]) => void): http.Server;
  919. listen(path: string, callback?: (...args: any[]) => void): http.Server;
  920. listen(handle: any, listeningListener?: () => void): http.Server;
  921. router: string;
  922. settings: any;
  923. resource: any;
  924. map: any;
  925. locals: any;
  926. /**
  927. * The app.routes object houses all of the routes defined mapped by the
  928. * associated HTTP verb. This object may be used for introspection
  929. * capabilities, for example Express uses this internally not only for
  930. * routing but to provide default OPTIONS behaviour unless app.options()
  931. * is used. Your application or framework may also remove routes by
  932. * simply by removing them from this object.
  933. */
  934. routes: any;
  935. /**
  936. * Used to get all registered routes in Express Application
  937. */
  938. _router: any;
  939. use: ApplicationRequestHandler<this>;
  940. /**
  941. * The mount event is fired on a sub-app, when it is mounted on a parent app.
  942. * The parent app is passed to the callback function.
  943. *
  944. * NOTE:
  945. * Sub-apps will:
  946. * - Not inherit the value of settings that have a default value. You must set the value in the sub-app.
  947. * - Inherit the value of settings with no default value.
  948. */
  949. on: (event: string, callback: (parent: Application) => void) => this;
  950. /**
  951. * The app.mountpath property contains one or more path patterns on which a sub-app was mounted.
  952. */
  953. mountpath: string | string[];
  954. }
  955. export interface Express extends Application {
  956. request: Request;
  957. response: Response;
  958. }