利用nodejs搭建一個本地的https服務

為了實現(xiàn)在手機上訪問PWA應用開發(fā)預覽,需要搭建一個https服務

這里主要是實施了兩個步驟
第一個:搭建https服務
第二個:轉發(fā)https到本地http服務

利用openssl創(chuàng)建私鑰和證書

  1. 生成私鑰:

    openssl genpkey -algorithm RSA -out key.pem
    
  2. 使用生成的私鑰生成自簽名證書:

    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);
  });
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容