為了實現(xiàn)在手機上訪問PWA應用開發(fā)預覽,需要搭建一個https服務
這里主要是實施了兩個步驟
第一個:搭建https服務
第二個:轉發(fā)https到本地http服務
利用openssl創(chuàng)建私鑰和證書
-
生成私鑰:
openssl genpkey -algorithm RSA -out key.pem -
使用生成的私鑰生成自簽名證書:
openssl req -new -key key.pem -x509 -out cert.pem
這兩個命令將生成私鑰和相應的自簽名證書,以便你可以將它們用于 HTTPS 服務器或其他安全通信需求。
利用nodejs創(chuàng)建一個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 };
// 獲取網(wǎng)絡接口信息
const networkInterfaces = os.networkInterfaces();
let ip = "";
// 遍歷網(wǎng)絡接口并找到局域網(wǎng)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}`);
});
利用第三方模塊轉發(fā)服務到本地dev http服務
// 假設本地服務為8000
const proxyTarget = `http://localhost:8000`; // 本地HTTP服務器地址
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({ target: proxyTarget });
//將上文中的httpsserver內(nèi)替換為下文
const httpsserver = https.createServer(credentials, (req, res) => {
proxy.web(req, res);
});