【问题标题】:How to use HTTP/2 with Nest.js (Node)如何将 HTTP/2 与 Nest.js(节点)一起使用
【发布时间】:2018-10-20 19:16:11
【问题描述】:

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

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

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

【问题讨论】:

  • 我不知道你的问题的答案,但作为替代方案,为什么不只是通过它前面的网络服务器(例如 Apache 或 Nginx)并在 HTTP/1.1 上保持 Node 直到 HTTP/2更好地支持它?老实说,在前面有一个用于静态资源的网络服务器通常会更好。

标签: node.js express http2 nestjs


【解决方案1】:

您可以使用 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 在响应标头中发送。

【讨论】:

    【解决方案2】:

    正如巴里·波拉德所说;在前端使用网络服务器来获取静态资源和 Webapp 本身,并将 Node.js 用于 API 目的,这可能是最好的方法。

    【讨论】:

    • 将自己的答案标记为最佳答案似乎有点不公平
    猜你喜欢
    • 2018-10-17
    • 2020-05-24
    • 2021-09-09
    • 2020-12-11
    • 1970-01-01
    • 2015-11-30
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多