方案一:使用 Chocolatey 安装 mkcert(推荐)
步骤 1:以管理员身份打开 PowerShell
右键点击 PowerShell 图标,选择"以管理员身份运行"。
步骤 2:安装 Chocolatey
复制下面整段命令,粘贴到 PowerShell 里运行:
powershell
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
步骤 3:安装 mkcert
安装完成后,重新打开一个新的 PowerShell 窗口(仍需管理员权限),然后运行:
powershell
choco install mkcert -y
步骤 4:初始化 mkcert
安装完成后,按提示初始化。如果你把 mkcert.exe 放在了 C:\tools 且已加到 PATH:
powershell
mkcert -install
mkcert localhost 127.0.0.1 ::1
编写 HTTPS 服务器脚本
在项目目录下新建一个文件 server.js,内容如下(注意证书文件名要与第 2 步生成的一致):
javascript
const https = require('https');
const fs = require('fs');
const path = require('path');
const options = {
key: fs.readFileSync(path.join(__dirname, 'localhost+2-key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'localhost+2.pem'))
};
const server = https.createServer(options, (req, res) => {
let filePath = req.url === '/' ? '/index.html' : req.url;
filePath = path.join(__dirname, filePath);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end('File not found');
return;
}
const ext = path.extname(filePath);
const mime = {
'.html': 'text/html',
'.js': 'application/javascript',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.json': 'application/json'
}[ext] || 'text/plain';
res.writeHead(200, { 'Content-Type': mime });
res.end(data);
});
});
const PORT = 8080;
server.listen(PORT, '0.0.0.0', () => {
console.log(`HTTPS server running on https://0.0.0.0:${PORT}`);
const os = require('os');
const interfaces = os.networkInterfaces();
console.log('手机请访问以下地址(确保同一 Wi-Fi):');
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
console.log(` https://${iface.address}:${PORT}`);
}
}
}
});
步骤 5:启动服务
bash
node server.js