本地搭建一个https服务

本地搭建一个 https 服务

在本地开发时,一般情况下只需要通过 http 访问 localhost 就能满足绝大多数开发的场景了,但最近在开发一些第三方插件/应用时,由于对方缺少对开发者的支持,只能在本地模拟生产环境才能集成到对方的应用中。其中一个最难的要求就是对方需要打开的页面支持 https。

生成 HTTPS 证书

要起一个 HTTPS 服务就需要证书,这里推荐 https://github.com/FiloSottile/mkcert 工具来生成一个可信任的证书(locally-trusted development certificates)。

注意一下在 windows 环境下安装需要使用 chocolatey 来安装,而 chocolatey 的安装也不像其他的工具一样,需要用到 powershell 来安装。

chocolatey 安装

在官网下载地址( https://chocolatey.org/install )中,我们能找到他的安装程序: https://community.chocolatey.org/install.ps1

注意:安装前需要配置 Get-ExecutionPolicy,需要管理员权限。官方也提供了不需要管理员权限的安装方式:https://docs.chocolatey.org/en-us/choco/setup#non-administrative-install

将代码下载到本地,再右键使用 powershell 运行即可安装。

安装完 chocolatey 即可根据 mkcert 说明安装并创建 https 证书。

使用 HTTPS 证书

使用 mkcert 命令会在当前目录下生成指定域名的证书,要使用证书还需要一个开发服务器来下发证书。

vitejs 开发环境

vitejs 开发环境支持配置 https,只需要在 server.https 中传入证书即可:https://vitejs.dev/config/server-options.html#server-https

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// https://vitejs.dev/config/
export default defineConfig(() => {
return {
server: {
host: "0.0.0.0",
open: "Chrome",
https: {
key: fs.readFileSync("xxx.com+4-key.pem"),
cert: fs.readFileSync("xxx.com+4.pem"),
},
proxy: {},
},
};
});

nodejs 原生写法

vitejs 内部传递的参数也是通过 nodejs 的 https 模块实现,所以也可以直接用 nodejs 原生实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 1、申明严格模式
"use strict";

// 2、引入 https 模块
var https = require("https");
// 3、 引入文件模块,读取证书
var fs = require("fs");

// fs.readFileSync() 指从某处读取文件
var options = {
key: fs.readFileSync("./cert/xx.cn.key"),
cert: fs.readFileSync("./cert/xx.cn.pem"),
};

// 4、创建 一个 https服务 options就是指我们证书
var app = https
.createServer(options, function (req, res) {
// 返回请求头
res.writeHead(200, { "Content-Type": "text/plain" });
// 返回内容
res.end("HTTPS:Hello World!\n");
})
.listen(443, "0.0.0.0");

express 写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var app = require("express")();
var fs = require("fs");
var http = require("http");
var https = require("https");
var privateKey = fs.readFileSync("/path/to/private.pem", "utf8");
var certificate = fs.readFileSync("/path/to/file.crt", "utf8");
var credentials = { key: privateKey, cert: certificate };

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
var PORT = 18080;
var SSLPORT = 18081;

httpServer.listen(PORT, function () {
console.log("HTTP Server is running on: http://localhost:%s", PORT);
});
httpsServer.listen(SSLPORT, function () {
console.log("HTTPS Server is running on: https://localhost:%s", SSLPORT);
});

本地搭建一个https服务
https://www.wobushi.top/2022/本地搭建一个https服务/
作者
Pride Su
发布于
2022年8月1日
许可协议