已配置setAllowedOrigins仍跨端口遭CORS拦截:STOMP over WebSocket问题
解决WebSocket连接404与CORS错误问题
核心问题分析
404错误是根源,CORS提示是因为服务器返回404时未附带CORS响应头,优先解决404才能彻底消除CORS报错。结合你的配置,以下是针对性解决方案:
1. 适配Spring Boot版本更新CORS配置
如果你的Spring Boot版本是2.4及以上,setAllowedOrigins("*")已被弃用,且对SockJS的/info请求支持不佳,改用setAllowedOriginPatterns:
@Override public void registerStompEndpoints(final StompEndpointRegistry registry) { registry.addEndpoint("/ws-endpoint") .setAllowedOriginPatterns("*") // 替换setAllowedOrigins .withSockJS(); }
setAllowedOriginPatterns支持更灵活的跨域规则,能正确处理SockJS的预检请求。
2. 确认SockJS依赖是否完整
服务器端未正确处理/info请求,大概率是缺少SockJS相关依赖。检查你的构建配置是否包含WebSocket starter:
Maven(pom.xml):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
Gradle(build.gradle):
implementation 'org.springframework.boot:spring-boot-starter-websocket'
缺少依赖会导致SockJS端点无法正常初始化,直接返回404。
3. 排查Spring Security拦截(如果使用)
若项目集成了Spring Security,需对WebSocket端点放行并配置CORS:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() .authorizeRequests() .antMatchers("/ws-endpoint/**").permitAll() // 放行WebSocket端点 .anyRequest().authenticated(); } // 配置全局CORS规则(可选,与WebSocket配置二选一即可) @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOriginPatterns(Arrays.asList("*")); config.addAllowedMethod("*"); config.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
Spring Security的默认拦截会阻断WebSocket的预检请求,导致404。
4. 验证WebSocket配置类是否被扫描
确保WebSocketConfig类所在包在Spring Boot的扫描范围内(即与启动类同包或子包),否则配置不会生效,端点无法注册。
5. 客户端连接路径验证
确认客户端使用的路径与服务器配置完全一致:
// 确保路径末尾没有多余斜杠,与服务器配置的/ws-endpoint匹配 var socket = new SockJS('http://localhost:8080/ws-endpoint');
内容的提问来源于stack exchange,提问作者BJagger
相关产品推荐
相关产品推荐

