美文网首页
nodejs http-proxy 反向代理 websocket

nodejs http-proxy 反向代理 websocket

作者: 此昵称已被狗抢占 | 来源:发表于2021-02-23 12:57 被阅读0次
    const httpProxy = require("http-proxy");
    const http = require("http");
    const url = require("url");
    
    const proxy = new httpProxy.createProxyServer();
    
    const proxyServer = http.createServer(function (req, res) {
      proxy.web(req, res);
    });
    
    proxyServer.on("upgrade", function (req, socket, head) {
      const { pathname } = url.parse(req.url);
    
      if (pathname.indexOf("/test") === 0) {
        proxy.ws(req, socket, {
          target: `http://127.0.0.1:10002/`,
          changeOrigin: true, // 等用于 req.headers.host = "127.0.0.1:10002"
          ignorePath: true, // 等同于 req.url="/"
        });
      }
    });
    
    proxyServer.listen(8000);
    

    相关文章

      网友评论

          本文标题:nodejs http-proxy 反向代理 websocket

          本文链接:https://www.haomeiwen.com/subject/qhyrfltx.html