【VSCode】在 VSCode 中运行 HTML 页面并通过 HTTPS 访问

发布于:2025-04-19 ⋅ 阅读:(16) ⋅ 点赞:(0)

在 Visual Studio Code 中运行 HTML 页面并通过 HTTPS 访问,通常需要借助本地开发服务器并配置 SSL 证书。以下是几种常见方法:


方法 1:使用 Live Server 扩展 + 自签名证书

步骤 1:生成自签名证书
  1. 使用 OpenSSL 生成证书(需提前安装 OpenSSL):

    openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
    
    • 按提示填写信息(可直接回车跳过)。
    • 生成 key.pem(私钥)和 cert.pem(证书)文件。
  2. 将生成的证书文件(如 key.pemcert.pem)放在项目目录中。

步骤 2:配置 Live Server
  1. 安装 Live Server 扩展
  2. 打开 VS Code 设置(Ctrl + ,),搜索 Live Server,找到以下设置:
    • Live Server > Settings: Https:启用(设为 true)。
    • Live Server > Settings: Cert:填写证书路径(如 cert.pem)。
    • Live Server > Settings: Key:填写私钥路径(如 key.pem)。
  3. 右键 HTML 文件,选择 Open with Live Server,浏览器将通过 https://localhost:5500 访问。

方法 2:使用 Node.js 快速搭建 HTTPS 服务器

步骤 1:创建服务器脚本
  1. 新建文件 server.js,写入以下代码:
    const https = require('https');
    const fs = require('fs');
    const path = require('path');
    
    const options = {
      key: fs.readFileSync('key.pem'),    // 私钥路径
      cert: fs.readFileSync('cert.pem')   // 证书路径
    };
    
    const server = https.createServer(options, (req, res) => {
      const filePath = path.join(__dirname, req.url === '/' ? 'index.html' : req.url);
      fs.readFile(filePath, (err, data) => {
        if (err) {
          res.writeHead(404);
          res.end('File not found');
        } else {
          res.writeHead(200);
          res.end(data);
        }
      });
    });
    
    server.listen(3000, () => {
      console.log('HTTPS server running on https://localhost:3000');
    });
    
步骤 2:运行服务器
  1. 确保已生成 key.pemcert.pem(方法同上)。
  2. 在终端中执行:
    node server.js
    
  3. 浏览器访问 https://localhost:3000

方法 3:使用 http-server(推荐)

步骤 1:安装 http-server
npm install -g http-server
步骤 2:生成可信本地证书(推荐使用 mkcert)
  1. 安装 mkcert(更安全的本地证书):
    # Windows (Chocolatey)
    choco install mkcert
    
    # macOS (Homebrew)
    brew install mkcert
    
    # Linux
    sudo apt install mkcert
    
  2. 生成并信任证书:
    mkcert -install
    mkcert localhost
    
    • 生成 localhost.pem(证书)和 localhost-key.pem(私钥)。
步骤 3:启动 HTTPS 服务器
http-server --ssl --cert localhost.pem --key localhost-key.pem -p 8080
  • 访问 https://localhost:8080

方法 4:使用 Webpack-dev-server(适用于前端工程化项目)

  1. webpack.config.js 中配置:
    module.exports = {
      // ...
      devServer: {
        https: {
          key: fs.readFileSync('key.pem'),
          cert: fs.readFileSync('cert.pem')
        },
        port: 8080
      }
    };
    
  2. 运行 webpack serve

解决浏览器安全警告

  • 自签名证书:浏览器会提示“不安全”,可手动信任(Chrome 中输入 thisisunsafe 快速绕过)。
  • mkcert 证书:已自动信任,无警告。

选择最适合你的方法,快速在本地启用 HTTPS 开发环境!


网站公告

今日签到

点亮在社区的每一天
去签到