vue与nginx配置websocket反代

vue配置websocket反代

创建连接

this.url = `ws://${location.host}/UMS-CLUSTER-WS/websocket/test` // 使用location.host的目的是在当前项目运行的域名和端口号下发起ws连接,例如本地为localhost:80
new WebSocket(this.url) // 创建连接

config配置

vue.config.js的反代中进行如下配置

proxy: {
      '/WS': {
        target: clusterWsServer, // 后台线上环境地址
        pathRewrite: { '^/WS': '' },
        ws: true,
        changeOrigin: true
      }
    }

nginx配置websocket反代

  #nginx配置websocket
  location /WS/ {
        proxy_pass  http://****:8666/; #websocket线上后台地址
        proxy_http_version    1.1;
        proxy_set_header      Host              $host;
        proxy_set_header      X-Real-IP         $remote_addr;
        proxy_set_header      X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_read_timeout    120s;
        proxy_set_header      Upgrade           websocket; #配置连接方式为websocket
        proxy_set_header      Connection        Upgrade;
  }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值