UNPKG

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