快速搭建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
相关推荐
To_OC7 小时前
写了 5 个表单 Demo 后,我终于彻底搞懂了 React 受控与非受控组件
前端·react.js·前端框架
Sterting7 小时前
第9课 Vue Router 路由
前端·vue.js
用户059540174467 小时前
LangChain Memory 测试踩坑实录:用 pytest 自动化回归对话记忆,我折腾了整整一个周末
前端·css
kyriewen7 小时前
Claude Code后天起默认Auto模式了——我第一时间改了这6个设置
前端·ai编程·claude
风骏时光牛马8 小时前
智能赋能型AI办公一体化系统架构
前端
满栀5858 小时前
vue动态路由效果
前端·javascript·vue.js·前端框架·vue
土豆~8 小时前
文件名没后缀就打不开:前端文件预览的内容嗅探改造
前端·状态模式
Euato_Key9 小时前
全栈视野学习Cookie——理解 Cookie 的本质
前端