node.js - NodeJS 将 SSL 添加到 HTTPserver
问题描述
我正在尝试将 SSL 添加到示例 WebRTC 视频聊天应用程序的 HTTPserver。我已经尝试将 SSL 添加到我的 Lighttpd 和代理中,但是由于混合的 https/非 https 内容,Socket.IO 连接不起作用。我想我需要一个独立的节点 https 服务器应用程序。我是 Node 新手,需要一些帮助...
这是我的应用程序:
索引.ts
import { Server } from "./server";
const server = new Server();
server.listen(port => {
console.log(`Server is listening on http://localhost:${port}`);
});
服务器.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);
自签名证书可以像这样生成:
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。
推荐阅读
- swift - 如何在快速点击按钮时删除表格视图单元格中的特定行
- c - 我不能 typedef 指向已经 typedef 的结构的指针
- python - 检查字符串中是否出现字符串列表的最短方法
- java - 如何使用 JPA 将 db 表放入 DTO 中的属性中
- c# - SQL - 用“where”子句连接三个表
- php - 用 ?? 替换(换行符)加上两个随机字符 在字符串中
- laravel - 为 laravel 安装了代客,但为什么 dnsmasq 不能正确解析?
- keras - 如何修复值错误'无法将输入数组从形状(720,1280,9)广播到形状(1,720,1280)'
- xamarin.forms - 如何删除添加到stackLayout的孩子
- c# - 如何将 CollectionViewSource 传递给转换器?