#node.js #ssl #httpserver
#node.js #ssl #httpserver
Вопрос:
Я пытаюсь добавить SSL на HTTPServer примера приложения для видеочата WebRTC. Я уже пытался добавить SSL в свой Lighttpd и просто прокси, но сокет.Подключение ввода-вывода не работает из-за смешанного содержимого 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);
});
}
}
Ответ №1:
Используйте 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=localhostn[req]ndistinguished_name = dnn[EXT]nsubjectAltName=DNS:localhostnkeyUsage=digitalSignaturenextendedKeyUsage=serverAuth")
Смотрите https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates для получения дополнительной информации.
Комментарии:
1. я это сделал. добавили его в функцию server.ts @ initialize, также изменили http на https. Большое вам спасибо :*