websocket 通过代理转发配置(webpack\nginx)

4,070 阅读1分钟

代码如下

websock = new WebSocket('ws://' + location.host + '/wsProxy/')
注意此处必须使用location.host,获取localhost和端口号,因为部署到服务器你这端口号不能写死吧。

webpack配置:

'/wsProxy/': {
        target: 'http://后台服务IP:后台服务PORT', // 后台的websocket服务地址
        changeOrigin: false,
        ws: true,
        secure: false,
        pathRewrite: {
          '^/wsProxy/': ''
        }
      },

注意后台对应websocket服务地址,此处配置成http://

nginx配置:

location /wsProxy/ {
            proxy_pass http://wsServer/;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }

upstream wsServer {
        server 后台服务IP:后台服务PORT;
    }
map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }