Skip to content

HTTPS

如果你想创建一个使用 HTTPS 协议的应用,可以在传给 NestFactory.create() 的选项对象中设置 httpsOptions 属性:

typescript
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,则应这样创建应用:

typescript
const app = await NestFactory.create<NestFastifyApplication>(
  AppModule,
  new FastifyAdapter({ https: httpsOptions }),
);

同时监听多个服务器

下面这个示例展示了如何创建一个同时监听多个端口的 Nest 应用,例如同时监听一个非 HTTPS 端口和一个 HTTPS 端口。

typescript
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() 或收到终止信号时,NestJS 不会自动关闭它们。这个关闭动作需要我们自己实现:

typescript
@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 导入;httphttps 则是 Node.js 原生模块。

警告

这个方案不适用于 GraphQL Subscriptions

基于 NestJS 官方文档翻译