vue项目部署在nginx,vue开发环境代理websocket请求,线上nginx代理websocket请求。

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";
        }
}
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 配置nginx代理websocketnginx.conf中添加以下配置 ``` map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name yourdomain.com; location / { proxy_pass http://localhost:3000; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } location /ws { proxy_pass http://localhost:8080; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } } ``` 这里的配置是在80端口监听,当请求路径为/ws时,转发到本地8080端口,实现websocket代理。同时也需要注意添加Upgrade和Connection的头信息。 2. 使用vue建立一个websocket请求vue项目中,可以使用socket.io-client来建立websocket连接。在main.js中添加以下代码 ``` import io from 'socket.io-client' const socket = io('http://yourdomain.com/ws', { transports: ['websocket'] }) socket.on('connect', () => { console.log('connected') }) socket.on('message', (data) => { console.log(data) }) socket.on('disconnect', () => { console.log('disconnected') }) socket.emit('message', 'hello') ``` 这里的代码是建立一个连接到yourdomain.com的websocket,同时添加了三个事件监听:connect表示连接成功,message表示接收到消息,disconnect表示断开连接。最后还发送了一条消息。 这样,当websocket请求发送到yourdomain.com时,nginx会将请求转发到本地的8080端口,建立websocket连接。vue项目中可以使用socket.io-client来发送和接收消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值