index.d.ts 35 KB

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