You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript无法连接Go搭建的WebSocket服务,但Postman可正常连接

WebSocket连接失败问题排查

我尝试连接一个Go语言实现的WebSocket路由,Postman无需额外配置就能成功连接并接收消息,其握手详情如下:

Connected to 0.0.0.0:1323/ws/earthquakes/stream
Handshake Details
Request URL: http://0.0.0.0:1323/ws/earthquakes/stream
Request Method: GET
Status Code: 101 Switching Protocols
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: xxx
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 0.0.0.0:1323
Response Headers
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: xxx

但我用以下JavaScript代码尝试连接时:

const ws = new WebSocket(wsURL + "earthquakes/stream", "echo-protocol");

Firefox提示错误:Firefox cannot establish connection with the server.(Firefox无法与服务器建立连接)。我试过把wsURL从ws://0.0.0.0:1323/ws/改成http://0.0.0.0:1323/ws/来匹配Postman的请求URL,但JavaScript会自动把http协议转为ws协议。

我原本以为不存在前端容器和后端的网络隔离问题,毕竟Postman能正常连接,但最后发现问题所在:前端和后端都处于Docker网络中,而测试用的浏览器并未接入这个Docker网络,因此需要在Go后端配置AllowedOrigin(允许的源)。

内容的提问来源于stack exchange,提问作者canersevdiceginibekleyenoglu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 15:06:14