我了解到 Express 4.x 与 Node.js 原生 HTTP2(从 8.4+ 开始)不兼容,我希望 Express 5.x 能取得比现在更多的进展。 但当我开始认为 Express5.x 可能会在我的下一个 Node.js 项目中较晚发布时 - 我转向了 Nest.js。
有谁知道 Nest.js 是否可以与 native HTTP2 支持一起使用?
我听说过的唯一支持此功能的 Node.js 框架是 Fastify。 或者还有其他的吗?最好是支持 Express 插件的。
最佳答案
您可以使用node-spdy在NestJS中使用HTTP/2(和SPDY)封装:
安装包
yarn add spdy
yarn add -D @types/spdy
生成证书
H2一般需要TLS,因此生成新的 key 和证书:
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -keyout test.key -out test.crt
修改启动
接下来,修改main.ts
:
// main.ts
async function bootstrap() {
const expressApp: Express = express();
const spdyOpts: ServerOptions = {
key: fs.readFileSync('./test.key'),
cert: fs.readFileSync('./test.crt'),
};
const server: Server = spdy.createServer(spdyOpts, expressApp);
const app: NestApplication = await NestFactory.create(
AppModule,
new ExpressAdapter(expressApp),
);
await app.init();
await server.listen(3000);
}
bootstrap();
测试客户端
$ curl -I -k https://localhost:3000/
HTTP/2 200
x-powered-by: Express
content-type: text/html; charset=utf-8
content-length: 12
etag: W/"c-Lve95gjOVATpfV8EL5X4nxwjKHE"
注意 HTTP/2
在响应 header 中发送。
关于node.js - 如何将 HTTP/2 与 Nest.js (Node) 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50274228/