webpack dev-server代理websocket问题
作者:AlsikeMou
这篇文章主要介绍了webpack dev-server代理websocket问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
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: {
}
},总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
