1 .vue文件中写法
data(){
return {
ws: null,
wsUrl: `ws://${location.host}/wsct`,
}
}
........
wsInit(){
this.ws = new WebSocket(this.wsUrl);
}
.........
2 配置开发环境打包规则,一般在vue.config.js中
devServer: {
......
proxy: {
// 代理websocket请求
'/wsct': {
target: '真正开发环境的websoket地址',
changeOrigin: true,//是否允许跨域
pathRewrite: {
'^/wsct': '',//重写,
},
ws: true //开启ws
}
}
},
3 线上nginx代理websocket请求
server{
location /wsct{
proxy_pass '线上websoket地址';
# 开启nginx对websocket的支持
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}