简体   繁体   English

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

[英]How to use HTTP/2 with Nest.js (Node)

I have read that Express 4.x is not compatible with Node.js native HTTP2 (from 8.4+), and I was hoping for more progess on Express 5.x than it has.我已经读到 Express 4.x 与 Node.js 原生 HTTP2(从 8.4+ 开始)不兼容,我希望 Express 5.x 上的进展比它更多。 But as I started thinking that Express5.x will probably be released to late for my next Node.js project - I came over Nest.js.但是当我开始考虑 Express5.x 可能会在我的下一个 Node.js 项目中发布的很晚时 - 我来到了 Nest.js。

Does anyone know if Nest.js can be used with native HTTP2 support ??有谁知道 Nest.js 是否可以与原生 HTTP2 支持一起使用?

The only Node.js framework that I have heard of that supports this is Fastify.我听说过的唯一支持此功能的 Node.js 框架是 Fastify。 Or are there any other out there ?或者还有其他的吗? Preferable one that support Express plugins.最好是支持 Express 插件的。

You can use HTTP/2 (and SPDY) in NestJS using the node-spdy package:您可以使用node-spdy包在 NestJS 中使用 HTTP/2(和 SPDY):

Setup packages安装包

yarn add spdy
yarn add -D @types/spdy

Generate certificate生成证书

H2 generally requires TLS, so generate a new key and certificate: H2一般需要TLS,所以生成一个新的密钥和证书:

openssl req -x509 -newkey rsa:2048 -nodes -sha256 -keyout test.key -out test.crt

Modify startup修改启动

Next, modify main.ts :接下来,修改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();

Test client测试客户端

$ 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"

Notice HTTP/2 being sent in the response headers.注意HTTP/2在响应头中发送。

As Barry Pollard commented;正如巴里·波拉德 (Barry Pollard) 评论的那样; using a webserver in front for static resources and the Webapp itself, and using Node.js for API purposes, is probably the best approach anyway.对静态资源和 Web 应用程序本身使用前面的网络服务器,并将 Node.js 用于 API 目的,无论如何可能是最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM