gpt4 book ai didi

node.js - HTTP2 的 Express 类型

转载 作者:太空宇宙 更新时间:2023-11-04 01:48:27 29 4
gpt4 key购买 nike

我想将 Node 10 中的 http2 模块与 Express 和 TypeScript (2.8.x) 结合使用。

可以使用以下内容实例化服务器:

import * as http2 from "http2";

let server = http2.createServer({}, app).listen(8080);

问题是我会收到 app 的类型错误。问题是 http2.createServer 希望第二个参数的类型为:

(request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => void

问题是,根据@types/expressapp的类型是( apparently ):

(req: Request | http.IncomingMessage, res: Response | http.ServerResponse): any

现在我可以做一个像这样的丑陋的 Actor :

import * as http2 from "http2";

let server = http2.createServer({}, (app as any) as ((request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => void)).listen(8080);

但是问题确实是稍后当我编写 Express 处理程序时,似乎我必须将它们写为:

(req: express.Request, res: express.Response) => {
let req2 = (req as any) as http2.Http2ServerRequest;
let res2 = (res as any) as http2.Http2ServerResponse;
...
}

...为了访问所有 http2 功能(例如推送),不是​​吗?

所以我必须在两端进行这些转换。现在,如果有一个 @types/express-http2 拥有所有 Express 类型,但假设底层核心为 http2,那么我认为这一切都不一定。但我找不到这样的东西。

我认识到这是一个棘手的类型问题,因为据我所知,所有 Express 类型都是在假设 http 作为底层服务层的情况下编写的。据我了解,Express 本身可以很好地与 http2 配合使用,但问题是类型不能干净地工作。

我错过了什么吗?

附注- 我更喜欢 Express,但如果有另一个基于 Node 的 Web 框架能够更好地支持 http2 和 TypeScript 的组合,我也可以考虑。

最佳答案

这行不通。 express 在内部使用 http 模块。

您可以像您正在做的那样对其进行转换,但您通过将其转换为any然后再次转换为http2.Http2ServerRequest而最终它不是一个http2.Http2ServerRequest,这在某种程度上是一种黑客行为。

有一个针对 http2 支持的开放 PR:https://github.com/expressjs/express/pull/3390

关于node.js - HTTP2 的 Express 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50574125/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com