Mac如何在本地开发中使用 HTTPS

1,663 阅读1分钟

本地申请HTTPS证书

1. 在本地新建一个文件夹,并进入该文件夹。

mkdir https-test
cd https-test

2. 安装 mkcert。

brew install mkcert
brew install nss # if you use Firefox

3. 将 mkcert 添加到本地根 CA。

mkcert -install

4. 为您的站点(localhost)生成一个由 mkcert 签名的证书。

mkcert localhost

# 如果您使用像 mysite.example 这样的自定义主机名,请使用以下命令:
# mkcert mysite.example

使用 http-server 搭建本地静态资源的HTTPS服务

1. 安装 http-server

npm install -g http-server

2. 启动 http-server 服务

# http-server -S -C {PATH/TO/CERTIFICATE-FILENAME}.pem -K {PATH/TO/CERTIFICATE-KEY-FILENAME}.pem

http-server . -p 3009 -S -C ./localhost.pem -K ./localhost-key.pem

3. 访问 https 的静态资源文件,点击允许访问。

使用 node xxx.js 方式使用

1. node xxx.js

const https = require('https');
const fs = require('fs');
const PORT = 3008;
const options = {
	key: fs.readFileSync('./localhost-key.pem'),
	cert: fs.readFileSync('./localhost.pem'),
	port: PORT
};
https
	.createServer(options, function (req, res) {
		console.log(req, res);
		// server code
		// res.send('xxx');
		if (req.url == '/') {
			// set response header
			res.writeHead(200, {
				'Content-Type': 'text/html'
			});
			// set response content    
			res.write('<html><body><p>This is home Page.</p></body></html>');
			res.end();

		} else if (req.url == "/student") {
			res.writeHead(200, {
				'Content-Type': 'text/html'
			});
			res.write('<html><body><p>This is student Page.</p></body></html>');
			res.end();
		} else if (req.url == "/admin") {
			res.writeHead(200, {
				'Content-Type': 'text/html'
			});
			res.write('<html><body><p>This is admin Page.</p></body></html>');
			res.end();
		} else {
			res.end('Invalid Request!');
		}
	}).listen(PORT);
console.log(`Node.js web server at port ${PORT} is running..`)

可能会遇到的一些坑:

1. brew 总是安装 mkcert 失败:

# 问题描述:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 安装失败
curl: (7) Failed to connect to raw.githubusercontent.com port 443: Connection refused

# 解决方案:(使用国内镜像源)
# 执行以下命令:
/bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"

2. 根据安装 mkcert过程中的提示,安装必要依赖。

参考链接:

web.dev/how-to-use-…

若有收获,就点个赞吧