自学内容网 自学内容网

前端 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;
         target: "ws://localhost:8888",  #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;
}

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


原文地址:https://blog.csdn.net/liyu_ya/article/details/134874634

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!