import { API_BASE_URL } from '@/config/setting'; /** * 统一拼接「当前登录用户」的 WebSocket 地址。 * *
2026-10-21 起统一走 {@code /api} 前缀(后端端点为 {@code /api/chat/{userId}})。 * 原先这里会把 {@code /api} 主动剥掉再拼 {@code /chat/${userId}},现场网关 * (twai-api.gxmu.edu.cn)只对 {@code /api} 放行 WebSocket 升级,导致握手被降级成 * 普通 GET 而返回 404。现在与其它接口同前缀,减少一类环境差异。 * *
若后端回退到旧路径,只需把 {@link USER_WS_PATH} 改成 {@code '/chat'}。 */ const USER_WS_PATH = '/chat'; export const buildUserWebSocketUrl = (userId: number | string): string => { const suffix = `${USER_WS_PATH}/${userId}`; // 绝对地址(生产/联调):https://host/api -> wss://host/api/chat/{userId} if (/^https?:\/\//.test(API_BASE_URL)) { const url = new URL(API_BASE_URL); url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'; url.pathname = url.pathname.replace(/\/+$/, ''); return `${url.toString().replace(/\/$/, '')}${suffix}`; } // 相对地址(VITE_API_URL=/api):与页面同源 const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const base = API_BASE_URL.replace(/\/+$/, ''); return `${protocol}//${window.location.host}${base}${suffix}`; };