UNPKG

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