如何在 Nest.js (Node) 中使用 HTTP/2

iTo*_*eTS 4 node.js express http2 nestjs

我读到 Express 4.x 与 Node.js 原生 HTTP2(从 8.4+ 开始)不兼容,我希望 Express 5.x 上的进展比它更多。但是当我开始考虑 Express5.x 可能会在我的下一个 Node.js 项目中发布的很晚时 - 我来到了 Nest.js。

有谁知道 Nest.js 是否可以与原生 HTTP2 支持一起使用?

我听说过的唯一支持此功能的 Node.js 框架是 Fastify。或者还有其他的吗?最好是支持 Express 插件的。

Jef*_*xon 5

您可以使用node-spdy包在 NestJS 中使用 HTTP/2(和 SPDY):

安装包

yarn add spdy
yarn add -D @types/spdy
Run Code Online (Sandbox Code Playgroud)

生成证书

H2一般需要TLS,所以生成一个新的密钥和证书:

openssl req -x509 -newkey rsa:2048 -nodes -sha256 -keyout test.key -out test.crt
Run Code Online (Sandbox Code Playgroud)

修改启动

接下来,修改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();
Run Code Online (Sandbox Code Playgroud)

测试客户端

$ 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"
Run Code Online (Sandbox Code Playgroud)

注意HTTP/2在响应头中发送。