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: { } },
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论