NodeJS 添加 SSL 到 HTTP 服务器

NodeJS add SSL to HTTPserver

我正在尝试将 SSL 添加到示例 WebRTC 视频聊天应用程序的 HTTP 服务器。 我已经尝试将 SSL 添加到我的 Lighttpd 和代理,但 Socket.IO 连接因混合 https/non https 内容而无法工作。我想我需要一个独立的节点 https 服务器应用程序。 我是 Node 新手,需要一些帮助...

这是我的应用程序:

index.ts

import { Server } from "./server";

const server = new Server();

server.listen(port => {
  console.log(`Server is listening on http://localhost:${port}`);
});

server.ts

import express, { Application } from "express";
import socketIO, { Server as SocketIOServer } from "socket.io";
import { createServer, Server as HTTPServer } from "http";
import path from "path";

export class Server {
  private httpServer: HTTPServer;
  private app: Application;
  private io: SocketIOServer;

  private activeSockets: string[] = [];

  private readonly DEFAULT_PORT = +process.env.PORT || 3000;

  constructor() {
    this.initialize();
  }

  private initialize(): void {
    this.app = express();
    this.httpServer = createServer(this.app);
    this.io = socketIO(this.httpServer);

    this.configureApp();
    this.configureRoutes();
    this.handleSocketConnection();
  }

  ...

  public listen(callback: (port: number) => void): void {
    this.httpServer.listen(this.DEFAULT_PORT, () => {
      callback(this.DEFAULT_PORT);
    });
  }
}

使用https库代替http:

const https = require('https');
const fs = require('fs');
const privateKey = fs.readFileSync('./localhost.key', 'utf8');
const certificate = fs.readFileSync('./localhost.crt', 'utf8');

const credentials = {
  key: privateKey,
  cert: certificate,
};

const httpsServer = https.createServer(credentials, this.app);

self-signed 证书可以这样生成:

openssl req -x509 -out localhost.crt -keyout localhost.key \
  -newkey rsa:2048 -nodes -sha256 \
  -subj '/CN=localhost' -extensions EXT -config <( \
   printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")

有关详细信息,请参阅 https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates