为了实现在手机上访问PWA应用开发预览,需要搭建一个https服务
这里主要是实施了两个步骤
第一个:搭建https服务
第二个:转发https到本地http服务
利用openssl创建私钥和证书
-
生成私钥:
openssl genpkey -algorithm RSA -out key.pem
-
使用生成的私钥生成自签名证书:
openssl req -new -key key.pem -x509 -out cert.pem
这两个命令将生成私钥和相应的自签名证书,以便你可以将它们用于 HTTPS 服务器或其他安全通信需求。
利用nodejs创建一个https服务
const https = require("https");
const fs = require("fs");
const os = require("os");
const privateKeyPath = "key.pem";
const certificatePath = "cert.pem";
const privateKey = fs.readFileSync(privateKeyPath, "utf8");
const certificate = fs.readFileSync(certificatePath, "utf8");
const credentials = { key: privateKey, cert: certificate };
// 获取网络接口信息
const networkInterfaces = os.networkInterfaces();
let ip = "";
// 遍历网络接口并找到局域网IP地址
for (const interfaceName in networkInterfaces) {
const interfaces = networkInterfaces[interfaceName];
for (const iface of interfaces) {
if (iface.family === "IPv4" && !iface.internal) {
ip = iface.address;
}
}
}
const httpsserver = https.createServer(credentials, (req, res) => {
res.writeHead(200);
res.end('Hello, HTTPS World!');
});
const PORT = 443; // HTTPS默认端口
httpsserver.listen(PORT, ip, () => {
console.log(`HTTPS服务器运行 https://${ip}`);
});
利用第三方模块转发服务到本地dev http服务
// 假设本地服务为8000
const proxyTarget = `http://localhost:8000`; // 本地HTTP服务器地址
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({ target: proxyTarget });
//将上文中的httpsserver内替换为下文
const httpsserver = https.createServer(credentials, (req, res) => {
proxy.web(req, res);
});