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

ReactJS浏览器端连接SpringBoot WebSocket失败的原因及解决方法

问题:SpringBoot与React应用WebSocket连接失败
  • 本地运行的SpringBoot应用端口为8090,React应用端口为3000,尝试建立WebSocket连接失败
  • Postman可以正常连接ws://localhost:8090/api/web-socket,实现消息收发
  • React应用可正常加载,但无论是使用127.0.0.1还是localhost都无法建立连接,浏览器控制台报错:WebSocket connection to 'ws://localhost:8090/api/web-socket' failed:,无额外错误详情,报错指向browser.js第28行,对应代码为:
else { native_instance = new NativeWebSocket(uri); }

该段所属完整代码块如下:

function W3CWebSocket(uri, protocols) {
var native_instance;

if (protocols) {
    native_instance = new NativeWebSocket(uri, protocols);
}
else {
    native_instance = new NativeWebSocket(uri);
}

用于建立连接的React代码

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {w3cwebsocket as W3CWebSocket} from "websocket";
import './index.css';

const client = new W3CWebSocket('ws://localhost:8090/api/web-socket');

export default class App extends Component{

    onButtonClicked = (value) => {
        client.send(JSON.stringify({
                type: "message",
                msg: value
            }
        ));
}

    componentDidMount() {
        client.onopen = () => {
            console.log('websocket client connected');
        };
        client.onmessage = (message) =>{
            const dataFromServer = JSON.parse(message.data);
            console.log("reply from socket server: ", dataFromServer);
        }
    }

    render() {
        return(
        <div>
            <button onClick={() => this.onButtonClicked("Example message from client to server")}>Send Message(start SAP)</button>
        </div>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('root'));

问题原因及解决方案

该错误由SpringBoot端WebSocket的跨域配置缺失导致:React应用运行在3000端口、SpringBoot运行在8090端口,二者端口不同属于跨域请求,浏览器会校验跨域许可,而Postman不会做跨域校验,所以才会出现Postman连接正常、浏览器无法连接的情况。

解决方法:在SpringBoot的WebSocket配置类中添加跨域许可配置,允许跨域请求:

.setAllowedOrigins("*")

完整配置示例:

registry.addHandler(new SocketTextHandler(), "/your-route").setAllowedOrigins("*");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:57:05