node.js - 如何将 HTTP/2 与 Nest.js (Node) 结合使用

标签 node.js express http2 nestjs

我了解到 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/

相关文章:

mysql - API 服务器返回 404 错误

javascript - 在 node.js 中使用命名参数

node.js - app.use(express.static(path.join(__dirname, 'public' )));引用错误 : path is not defined what is issue?

ASP.Net HTTP2 PushPromise 很慢

rest - HTTP/2 多路复用是否违反 REST API 规则?

javascript - 不通过 Node 应用程序访问 mongodb atlas 上的旧数据

node.js - 在elasticbeanstalk上安装npm canvas - npm安装错误

node.js - Nodejs HTTP 和 HTTPS 在同一个端口上

node.js - 测试快速应用程序 API 的正确方法?

safari - 为什么 Safari 不支持 http2