簡體   English   中英

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

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

我已經讀到 Express 4.x 與 Node.js 原生 HTTP2(從 8.4+ 開始)不兼容,我希望 Express 5.x 上的進展比它更多。 但是當我開始考慮 Express5.x 可能會在我的下一個 Node.js 項目中發布的很晚時 - 我來到了 Nest.js。

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

我聽說過的唯一支持此功能的 Node.js 框架是 Fastify。 或者還有其他的嗎? 最好是支持 Express 插件的。

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

安裝包

yarn add spdy
yarn add -D @types/spdy

生成證書

H2一般需要TLS,所以生成一個新的密鑰和證書:

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在響應頭中發送。

正如巴里·波拉德 (Barry Pollard) 評論的那樣; 對靜態資源和 Web 應用程序本身使用前面的網絡服務器,並將 Node.js 用於 API 目的,無論如何可能是最好的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM