為了實(shí)現(xiàn)在手機(jī)上訪問PWA應(yīng)用開發(fā)預(yù)覽侨核,需要搭建一個(gè)https服務(wù)
這里主要是實(shí)施了兩個(gè)步驟
第一個(gè):搭建https服務(wù)
第二個(gè):轉(zhuǎn)發(fā)https到本地http服務(wù)
利用openssl創(chuàng)建私鑰和證書
-
生成私鑰:
openssl genpkey -algorithm RSA -out key.pem
-
使用生成的私鑰生成自簽名證書:
openssl req -new -key key.pem -x509 -out cert.pem
這兩個(gè)命令將生成私鑰和相應(yīng)的自簽名證書,以便你可以將它們用于 HTTPS 服務(wù)器或其他安全通信需求。
利用nodejs創(chuàng)建一個(gè)https服務(wù)
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)絡(luò)接口信息
const networkInterfaces = os.networkInterfaces();
let ip = "";
// 遍歷網(wǎng)絡(luò)接口并找到局域網(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默認(rèn)端口
httpsserver.listen(PORT, ip, () => {
console.log(`HTTPS服務(wù)器運(yùn)行 https://${ip}`);
});
利用第三方模塊轉(zhuǎn)發(fā)服務(wù)到本地dev http服務(wù)
// 假設(shè)本地服務(wù)為8000
const proxyTarget = `http://localhost:8000`; // 本地HTTP服務(wù)器地址
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);
});