【VSCode】在 VSCode 中运行 HTML 页面并通过 HTTPS 访问
在 Visual Studio Code 中运行 HTML 页面并通过 HTTPS 访问,通常必要借助本地开辟服务器并设置 SSL 证书。以下是几种常见方法:方法 1:使用 Live Server 扩展 + 自署名证书
步骤 1:生成自署名证书
[*] 使用 OpenSSL 生成证书(需提前安装 OpenSSL):
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
[*]按提示填写信息(可直接回车跳过)。
[*]生成 key.pem(私钥)和 cert.pem(证书)文件。
[*] 将生成的证书文件(如 key.pem 和 cert.pem)放在项目目次中。
步骤 2:设置 Live Server
[*]安装 Live Server 扩展。
[*]打开 VS Code 设置(Ctrl + ,),搜索 Live Server,找到以下设置:
[*]Live Server > Settings: Https:启用(设为 true)。
[*]Live Server > Settings: Cert:填写证书路径(如 cert.pem)。
[*]Live Server > Settings: Key:填写私钥路径(如 key.pem)。
[*]右键 HTML 文件,选择 Open with Live Server,欣赏器将通过 https://localhost:5500 访问。
方法 2:使用 Node.js 快速搭建 HTTPS 服务器
步骤 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:运行服务器
[*]确保已生成 key.pem 和 cert.pem(方法同上)。
[*]在终端中执行:node server.js
[*]欣赏器访问 https://localhost:3000。
方法 3:使用 http-server(保举)
步骤 1:安装 http-server
npm install -g http-server
步骤 2:生成可信本地证书(保举使用 mkcert)
[*]安装 mkcert(更安全的本地证书):# Windows (Chocolatey)
choco install mkcert
# macOS (Homebrew)
brew install mkcert
# Linux
sudo apt install mkcert
[*]生成并信托证书: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(适用于前端工程化项目)
[*]在 webpack.config.js 中设置:module.exports = {
// ...
devServer: {
https: {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
},
port: 8080
}
};
[*]运行 webpack serve。
解决欣赏器安全警告
[*]自署名证书:欣赏器会提示“不安全”,可手动信托(Chrome 中输入 thisisunsafe 快速绕过)。
[*]mkcert 证书:已自动信托,无警告。
选择最适合你的方法,快速在本地启用 HTTPS 开辟环境!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]