【问题标题】:how to use http2 in loopback 4 application?如何在 loopback 4 应用程序中使用 http2?
【发布时间】:2022-11-23 14:56:24
【问题描述】:

我们计划在 loopback 4 应用程序中实现 http2。我们使用过 http、套接字服务器,但从未使用过 http2。

在我的应用程序中使用 http2 的过程是什么?

【问题讨论】:

标签: loopbackjs loopback4


【解决方案1】:

以下是您必须在现有应用中执行的操作:

第一步:安装spdy

npm i spdy

第二步:配置index.ts

更改 src/index.ts 中的主要功能:

import spdy from "spdy";

export async function main(options: ApplicationConfig = {}) {
  
  // specify cert and key file paths for SSL
  const serverOptions: spdy.ServerOptions = {
    key: fs.readFileSync(
      path.join(__dirname, '..', 'keys', 'localhost-privkey.pem'),
    ),
    cert: fs.readFileSync(
      path.join(__dirname, '..', 'keys', 'localhost-cert.pem'),
    ),
  };

  // setting listenOnStart to false will not start the default httpServer
  options.rest.listenOnStart = false;

  // Replace YourApplication with your class
  const app = new YourApplication(options);
  await app.boot();
  await app.start();

  // create server
  const server = spdy.createServer(serverOptions, app.requestHandler);

  // to avoid process exit on warnings
  server.on('warning', console.warn);

  server.listen(3000, () => {
    console.log('Listening on https://localhost:3000/');
  });

  return app;
}

我们在上面的代码中所做的就是,阻止启动默认的 http 服务器,并使用 spdy 和环回的请求处理程序 app.requestHandler 启动服务器,它将用于所有传入请求。

查看这个 pastebin 包含更改后的整个 index.ts 文件内容。

为本地主机使用生成证书和密钥:

openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' 
  -keyout localhost-privkey.pem -out localhost-cert.pem

您可能还需要允许 Chrome 中的自签名证书以及 /explorer 才能按预期工作。

就是这样,您现在可以运行您的应用程序,并享受 http2 的强大功能:)

博文:https://shubhmp.medium.com/how-to-use-http2-in-loopback-4-applications-5e83881c7b38

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多