工作过程的随心小记
vue项目中,遇到的前端需要在本地代码中连接线上环境(假如线上环境是172.16.131.20)的websocket,且线上环境是https环境的,具体要如何操作呢?
其实发送websocket也是发送请求,本地连接线上接口联调,vue项目就是利用的webpack的proxy代理来实现的,同理,ws也是一样的,可以通过配置代理来实现。
实现代码
taskProgress () {
// window.location.host 也可以直接写自己电脑的地址
// wsPath 全路径比如是10.25.35.5:8080/bendi/api-icsmp-platform-center/socket/taskSocket
let wsPath = `ws://${window.location.host}/bendi/api-icsmp-platform-center/socket/taskSocket`
if (typeof WebSocket === 'undefined') {
this.info(this.$t('lang.error'))
} else {
// 实例化socket
this.socket = new WebSocket(wsPath)
this.socket.onmessage = this.getMessage
}
}
vue.config.js里面的配置
proxy: {
// 拦截websocket的转发
'/bendi/api-icsmp-platform-center': {
target: `https://172.16.131.20/api-icsmp-platform-center`, // 此处就是https,不是wss,因为ws属性设置为true,会自动将https转成wss协议
ws: true,
changeOrigin: true,
pathRewrite: {
'^/bendi/api-icsmp-platform-center': ``
}
},
// 业务功能接口的代理转发
'/api-icsmp-platform-center': {
target: `http://172.16.131.20:10900/api-icsmp-platform-center`,
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api-icsmp-platform-center': ``
}
}
}