快速搭建HTTPS本地开发环境

方案一:使用 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
相关推荐
ℋᙚᵐⁱᒻᵉ鲸落5 小时前
移动端滑动手势冲突:overflow: auto导致外层横向滑动失效
前端·javascript·css·vue.js·html
默_笙6 小时前
🎃 前端学了 Next.js,后端该学啥?NestJS 就是 Node 版的蜜雪冰城
前端·javascript
前端snow7 小时前
ai agent --- 实现 openclaw 定时间效果
前端
码云之上7 小时前
换模型之后,Chatbot 为什么要自己做 compact?
前端·agent·前端工程化
星栈8 小时前
自定义 UI-UX-Pro-Max 的 CSV 知识库,把 AI 生成的后台拉回行业该有的样子
前端·agent·weui
研☆香8 小时前
简单的图片上传 删除 预览
前端
ITresearchGuest8 小时前
我用 AI 一小时写了一个世界杯数据可视化平台|前端 VibeCoding 初体验
前端·人工智能·信息可视化
慧一居士9 小时前
Vite项目中使用Less步骤,详细使用示例
前端·css
花间相见10 小时前
【LangChain组件03】—— LangChain Agents 执行与状态:工作流程与状态管理实战
java·前端·langchain
kyriewen10 小时前
面试官让我用 AI 重构一个 8 年陈的 React 组件——他说他不看代码,只看我会不会拆
前端·javascript·面试