前言
在本地调试时live server默认开启的是http协议,如果我们想使用https协议时可以对live server进行一些配置以启用https协议。
配置步骤
1.安装mkcert
- 打开windows的搜索功能搜索powershell,并以管理员的身份打开。
- 在powershell中输入命令 Get-ExecutionPolicy,如果系统返回 Restricted,则在执行命令:Set-ExecutionPolicy AllSigned ,选择 A(全是)。
- 执行命令以下命令:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
- 执行 choco -? 验证是否安装成功 。
- 安装完成后,执行命令 choco install mkcert,等待安装完成。
2.安装本地CA并将CA加入系统的信任清单中
执行命令 mkcert -install ,本地CA在目录 C:\Users\你的用户名\AppData\Local\mkcert 中。
下面是执行成功后的结果:
The local CA is already installed in the system trust store! 👍
Note: Firefox support is not available on your platform. ℹ️
The local CA is already installed in Java's trust store! 👍
3.生成凭证
执行命令 mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1
注意:请进入需要生成凭证的目录,凭证将在该目录下生成, 例如我指定的目录为 D:\https。
下面是执行成功后的结果:
Created a new certificate valid for the following names 📜
- "example.com"
- "*.example.com"
- "example.test"
- "localhost"
- "127.0.0.1"
- "::1"
Reminder: X.509 wildcards only go one level deep, so this won't match a.b.example.com ℹ️
The certificate is at "./example.com+5.pem" and the key at "./example.com+5-key.pem" ✅
It will expire on 9 December 2023 🗓
执行完成后生成了 example.com+5.pem 和 example.com+5-key.pem,其中 example.com+5.pem 是证书文件,example.com+5-key.pem 是私钥。
4.设置live server的settings
在vscode中打开命令面板,输入 settings,点击 首选项:打开工作区设置 ,找到 live server。(或者找到已下载的插件中的live server插件点击管理再点击拓展设置)。
下拉找到 Live Server > Settings: Https 目录,并设置图中的项和值:
enable | 是否启用https |
cert | 之前生成的证书地址 |
key | 之前生成的密钥地址 |
也可以在点击 在settings.json中编辑 对该文件进行设置:
"liveServer.settings.https": {
"enable": false, //是否启用https
"cert": "D:\\https\\example.com+5.pem", //之前生成的证书地址
"key": "D:\\https\\example.com+5-key.pem", //之前生成的密钥地址
"passphrase": ""
},
杂项
设置后如果不想开启https协议而是用http协议的话可以更改 live server配置中的 liveServer.settings.https 的 enable 为 false。