前端 webSocket配置代理

vue, react. nginx 配置反向代理,解决跨域问题

前端请求

如果配置了 wss 协议, 可以将ws 替换为 wss

这里和我们通常使用的方式不同websocket 需要传入完整的地址,然后才能去做代理

  let url = `${location.protocol === 'https' ? 'wss' : 'ws'}://${location.host}/ws/socket/io`;  const socket = new WebSocket(url);

 vite.config.ts给 将 proxy

如果配置了 wss 协议, 可以将ws 替换为 wss

   "/ws": {        target: "ws://localhost:8888", // 后端地址        changeOrigin: true, //支持跨域        ws: true, // 是否启用WebSocket代理        rewrite: (path) => path.replace(/^\/ws/, ""), // 重写      },

服务器 nginx 代理配置 ,配置后刷新就好了

        # nginx配置websocket    location /ws/ {        rewrite /ws/(.*) /$1 break;        proxy_pass http://127.0.0.1:7000/;   #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;        proxy_set_header Connection Upgrade;}

大概就这样,如果有问题后面胡补充@

评论
暂无评论

登录后可发表评论

点击登录