当前位置: 代码网 > it编程>编程语言>Javascript > webpack dev-server代理websocket问题

webpack dev-server代理websocket问题

2024年09月07日 Javascript 我要评论
webpack dev-server 代理 websocket在写东西的时候遇到websocket在开发中需要代理,并且基于http,部署后利用nginx代理并使用https的情况,想协调两种配置但不

webpack dev-server 代理 websocket

在写东西的时候遇到websocket在开发中需要代理,并且基于http,部署后利用nginx代理并使用https的情况,想协调两种配置但不太会写。尝试之后记下来。

首先用到https之后肯定是不能在页面中直接使用url去访问各个后端的,因此务必配置proxy。

proxy

开发环境中使用proxy进行多后端转发配置,转发表尽量与nginx配置相对应,方便部署。

下为用到的配置匿名版。

proxytable: {
      //多后端配置
      '/a': {
        //target: http://xxxxx/xxxxxx
        target: config.a_target,//如上一行写成地址即可
        //changeorigin: true,
        pathrewrite: {
          '^/a':'/'
        }
      },
      '/b':{
        target:config.b_target,
        pathrewrite: {
          '^/b':'/'
        }
      },
      '/c':{
        target: config.c_target,
        ws:true,//支持websokcet
        changeorigin: true,
        pathrewrite: {
          '^/c':'/'
        }
      },
      '/':{
        target: config.real_target, 
        //ws: true,//支持websocket
        changeorigin: true,
        pathrewrite: {
        }
      },

websocket

创建websocket时与http请求不同,不能使用/c/前缀直接匹配,而是要使用带有协议与地址端口等完整的路径

代码如下:

//根据http协议判断是否为ws或wss
let proto = document.location.protocol == 'http:'? 'ws:': 'wss:';
//取地址+端口,配置80端口时port是空的,所以判断一下
let address = document.location.port? 
document.location.hostname + ':' + document.location.port:  document.location.hostname ;
//拼接请求地址
const wsuri = proto + "//" + address + "/c/"+this.robotid;
console.log(wsuri);
this.websock = new websocket(wsuri);

部署后可能会遇到websocket不停断开重连,此时不启用根路径的websocket即可

'/':{
        target: config.real_target, 
        //ws: true,//注释掉,不启用即可
        changeorigin: true,
        pathrewrite: {
        }
      },

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com