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

React.js与Spring Boot WebSocket连接失败问题求助

排查React.js SockJS客户端与Spring Boot WebSocket连接失败问题

核心排查方向及修复方案

1. 跨域配置缺失或错误

前端http://localhost:3000与后端http://localhost:1998属于不同端口,必须配置跨域允许:

  • Spring Boot WebSocket配置:在WebSocketConfig中指定允许的源(Spring Boot 2.4+推荐用setAllowedOriginPatterns):
    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
        @Override
        public void configureMessageBroker(MessageBrokerRegistry config) {
            config.enableSimpleBroker("/topic");
            config.setApplicationDestinationPrefixes("/app");
        }
    
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/ws")
                    .setAllowedOriginPatterns("http://localhost:3000") // 测试阶段可临时用"*",生产环境指定具体域名
                    .withSockJS();
        }
    }
    
  • Spring Security兼容:如果项目用了Spring Security,需放行WebSocket端点的跨域请求:
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and()
                .authorizeRequests()
                .antMatchers("/ws/**").permitAll()
                .anyRequest().authenticated();
        }
    }
    

2. 客户端连接路径错误

React端必须匹配后端配置的WebSocket端点路径:

import SockJS from 'sockjs-client';
import { Stomp } from '@stomp/stompjs';

const connectWebSocket = () => {
    const socket = new SockJS('http://localhost:1998/ws'); // 必须与后端addEndpoint的路径一致
    const stompClient = Stomp.over(socket);
    
    stompClient.connect({}, 
        (frame) => console.log('连接成功:', frame),
        (error) => console.error('连接失败:', error)
    );
};

注意:不能省略端点路径(比如只写http://localhost:1998),否则会返回404错误。

3. 依赖版本不兼容

确保前后端WebSocket相关依赖版本匹配:

  • React端:推荐使用sockjs-client@1.5.x + @stomp/stompjs@6.x.x,避免使用过于老旧或预览版依赖;
  • Spring Boot端:使用官方starter依赖spring-boot-starter-websocket,无需额外指定版本(由Spring Boot parent管理)。

4. 消息路由配置不匹配

检查后端控制器与客户端的消息路径是否对应:

  • 后端控制器示例:
    @Controller
    public class WebSocketController {
        @MessageMapping("/sendMessage") // 客户端需发送到/app/sendMessage
        @SendTo("/topic/messages")
        public String handleMessage(String message) {
            return "收到消息: " + message;
        }
    }
    
  • 客户端发送消息时必须加上/app前缀(对应配置中的setApplicationDestinationPrefixes):
    stompClient.send('/app/sendMessage', {}, JSON.stringify({ content: 'Hello' }));
    

5. 浏览器网络请求排查

打开Chrome开发者工具(F12)→ Network标签:

  • 筛选WS类型,查看WebSocket请求的状态码:
    • 403:权限或跨域配置问题;
    • 404:端点路径错误;
  • 检查请求头的Origin字段是否为http://localhost:3000,确认后端已允许该源。

内容的提问来源于stack exchange,提问作者Erdem Öden

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:54:58