【发布时间】:2022-11-23 14:56:24
【问题描述】:
我们计划在 loopback 4 应用程序中实现 http2。我们使用过 http、套接字服务器,但从未使用过 http2。
在我的应用程序中使用 http2 的过程是什么?
【问题讨论】:
标签: loopbackjs loopback4
我们计划在 loopback 4 应用程序中实现 http2。我们使用过 http、套接字服务器,但从未使用过 http2。
在我的应用程序中使用 http2 的过程是什么?
【问题讨论】:
标签: loopbackjs loopback4
以下是您必须在现有应用中执行的操作:
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
【讨论】: