快速搭建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
相关推荐
十有八七1 小时前
手搓 Agent(一):先有大脑——大模型只会做一件事
前端·人工智能·后端
锋行天下1 小时前
「踩坑实录」给 LangGraph Agent 接两个 FastMCP,我被 langchain 偷偷改了工具名
前端·人工智能·后端
跳跳的小星星1 小时前
自研组件】Vue2 + ElementUI 通用列表页封装 wkjp-list-page,一套配置搞定搜索、动态表格、分页、增删改
前端
tryCbest2 小时前
Vue3—— 第 18 篇:Vue 2 到 Vue 3 迁移指南——升级避坑全记录
前端·vue.js
保利威视频SaaS小张2 小时前
企业直播接入笔记 12|企业内训直播怎么做签到和学时统计,防挂机这件事比想象中难
java·前端·数据库·笔记·视频云·polvy·polyv
bysking2 小时前
GitHub Actions 快速入门+场景实践案例
前端·后端·github
广州华水科技3 小时前
单北斗GNSS变形监测系统在大坝安全维护中的重要性
前端
anyup3 小时前
自带 uni-app x 页面级能力,uView Pro X 8 个开箱即用的工具函数
前端·vue.js·uni-app
涛涛ing3 小时前
别拿 Chrome 跑通了就提测:把这段 AI 写的代码发到 Safari 上,我差点丢了工作
前端
墨林陌3 小时前
用 AI 给娃做了一个识物游戏:一份 2.3MB 的单文件 HTML,126 张卡片、三种玩法,手机平板打开就能玩
前端