HTTPS 与多服务器
要创建使用 HTTPS 协议的应用,请在传给 NestFactory.create() 方法的选项对象中设置 httpsOptions 属性:
const httpsOptions = {
key: fs.readFileSync('./secrets/private-key.pem'),
cert: fs.readFileSync('./secrets/public-certificate.pem'),
};
const app = await NestFactory.create(AppModule, {
httpsOptions,
});
await app.listen(process.env.PORT ?? 3000);如果使用 FastifyAdapter,请按下面的方式创建应用:
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ https: httpsOptions }),
);同时运行多个服务器
下面的做法展示了如何创建一个同时监听多个端口(例如同时监听一个 HTTP 端口和一个 HTTPS 端口)的 Nest 应用:
const httpsOptions = {
key: fs.readFileSync('./secrets/private-key.pem'),
cert: fs.readFileSync('./secrets/public-certificate.pem'),
};
const server = express();
const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
await app.init();
const httpServer = http.createServer(server).listen(3000);
const httpsServer = https.createServer(httpsOptions, server).listen(443);由于这些服务器是我们自己用 http.createServer() 和 https.createServer() 创建的,所以在调用 app.close() 时、或进程收到终止信号时,Nest 不会关闭它们。你需要自行关闭,例如借助一个实现了 OnApplicationShutdown 钩子的提供者:
@Injectable()
export class ShutdownObserver implements OnApplicationShutdown {
private httpServers: http.Server[] = [];
public addHttpServer(server: http.Server): void {
this.httpServers.push(server);
}
public async onApplicationShutdown(): Promise<void> {
await Promise.all(
this.httpServers.map(
(server) =>
new Promise((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error);
} else {
resolve(null);
}
});
}),
),
);
}
}
const shutdownObserver = app.get(ShutdownObserver);
shutdownObserver.addHttpServer(httpServer);
shutdownObserver.addHttpServer(httpsServer);提示
ExpressAdapter 从 @nestjs/platform-express 包导入。http 与 https 模块是 Node.js 内置的。
警告
该做法不适用于 GraphQL 订阅。