const https = require('https'); const fs = require('fs'); const path = require('path'); const selfsigned = require('selfsigned'); const handler = require('serve-handler'); const PORT = 8443; const CERT_DIR = path.join(__dirname, 'cert'); // 确保证书目录存在 if (!fs.existsSync(CERT_DIR)) { fs.mkdirSync(CERT_DIR, { recursive: true }); } const CERT_PATH = path.join(CERT_DIR, 'localhost.pem'); const KEY_PATH = path.join(CERT_DIR, 'localhost-key.pem'); async function startServer() { let cert, key; if (fs.existsSync(CERT_PATH) && fs.existsSync(KEY_PATH)) { console.log('使用已生成的自签名证书...'); cert = fs.readFileSync(CERT_PATH); key = fs.readFileSync(KEY_PATH); } else { console.log('正在生成自签名证书...'); const attrs = [{ name: 'commonName', value: 'localhost' }]; const pems = await selfsigned.generate(attrs, { keySize: 2048, algorithm: 'sha256', extensions: [ { name: 'subjectAltName', altNames: [ { type: 2, value: 'localhost' }, { type: 7, ip: '127.0.0.1' } ] } ] }); fs.writeFileSync(CERT_PATH, pems.cert); fs.writeFileSync(KEY_PATH, pems.private); cert = pems.cert; key = pems.private; console.log('自签名证书已生成并保存'); } // 创建 HTTPS 服务器 const server = https.createServer({ key, cert }, (req, res) => { return handler(req, res, { public: __dirname, rewrites: [ { source: '**', destination: '/index.html' } ] }); }); server.listen(PORT, () => { console.log(`前端 HTTPS 服务已启动: https://localhost:${PORT}`); console.log('注意:浏览器会提示证书不安全,请点击"高级"->"继续访问"'); }); } startServer().catch(err => { console.error('启动失败:', err); process.exit(1); });