mkcert: 本地https快速解决方案
mkcert: https证书生成工具
安装
# install
brew install mkcert
# check
❯ mkcert --version
v1.4.4
在系统安装证书
可以用在 keychain 里搜索 mkcert 查看证书安装情况。
❯ mkcert -install
Created a new local CA 💥
Sudo password:
The local CA is now installed in the system trust store! ⚡️
开发域名
生成 key/cert 对应的 pem 文件,一般文件名(针对 localhost)如下:
localhost+2-key.pem
localhost+2.pem
mkcert localhost 127.0.0.1 ::1
Created a new certificate valid for the following names 📜
- "localhost"
- "127.0.0.1"
- "::1"
The certificate is at "./localhost+2.pem" and the key at "./localhost+2-key.pem" ✅
It will expire on 6 October 2024 🗓
证书使用
var fs = require("fs"),
https = require("https"),
express = require("express");
var port = 8000;
var app = express();
var options = {
key: fs.readFileSync("localhost+2-key.pem"),
cert: fs.readFileSync("localhost+2.pem"),
};
https.createServer(options, app).listen(port, function () {
console.log("Express server listening on port " + port);
});
app.get("/", function (req, res) {
res.writeHead(200);
res.end("hello world\n");
});
mkcert 与 react 结合
- React 的 https 问题: 红色的 https 提示,感觉不友好
- 参考: https://ncoughlin.com/posts/https-on-localhost-with-react/
使用步骤
- 创建
.pem
文件 (用这个命令可以产生2个文件:mkcert localhost 127.0.0.1 ::1
) - 添加
.env
文件,并设置如下 - 因为适用于本机,可以考虑加到
.gitignore
文件里去
.env
配置
- 可以修改路径
HTTPS=true
SSL_CRT_FILE=.cert/localhost+2.pem
SSL_KEY_FILE=.cert/localhost+2-key.pem
公司项目配置
- 主域名与公司项目相同,配置 hosts:
127.0.0.1 dev.beta.aigene.org.cn
- mkcert https证书生成,路径为:
cd ~/github/softwares/mkcerts/ && mkcert localhost 127.0.0.1 ::1 dev.beta.aigene.org.cn
- cra 里的 https 配置,项目底下的
.env
文件(刻这个.env
加入到.gitignre
里)
SSL_CRT_FILE=$HOME/github/software/mkcerts/localhost+3.pem
SSL_KEY_FILE=$HOME/github/software/mkcerts/localhost+3-key.pem
HTTPS=true
PORT=3000
参考
- https://github.com/FiloSottile/mkcert
- https://blog.dteam.top/posts/2019-04/%E6%9C%AC%E5%9C%B0https%E5%BF%AB%E9%80%9F%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88mkcert.html
- https://stackoverflow.com/questions/11804202/how-do-i-setup-a-ssl-certificate-for-an-express-js-server
- https://web.dev/how-to-use-local-https/
- https://ncoughlin.com/posts/https-on-localhost-with-react/