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

Angular+SpringBoot实现WebSocket/SSE连接遇跨域及连接拒绝问题求助

Angular + Spring Boot: WebSocket/SSE Connection Refused & CORS Issues Despite setAllowedOrigins("*")

Let's break down your issues step by step—both WebSocket and SSE are hitting cross-origin or connection problems even though your regular REST endpoints work, so we need to dig into how these protocols handle CORS differently from standard REST.

First: Why Regular REST Works, But WebSocket/SSE Don't

Standard REST endpoints rely on Spring's WebMvc CORS configuration (either global or via @CrossOrigin annotations). However:

  • WebSocket (especially with SockJS) uses a separate handshake mechanism that's governed by the StompEndpointRegistry settings, not the global WebMvc CORS rules.
  • Server-Sent Events (SSE) via EventSource also have strict CORS requirements that aren't always covered by default global configurations.

Fix 1: Resolve WebSocket CORS/Connection Issues

Your WebSocketConfig uses setAllowedOrigins("*"), but there are two common pitfalls here:

a) Browser Limitations for Wildcard Origins with WebSocket

Some browsers (like Chrome) restrict wildcard * origins for WebSocket connections as a security measure. Instead, explicitly specify your Angular app's origin:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/notification");
        registry.setApplicationDestinationPrefixes("/swns");
    }
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/notifications")
                .setAllowedOrigins("http://localhost:4200") // Replace with your Angular URL/port
                .withSockJS();
    }
}

b) Verify Connection Reachability

The ERR_CONNECTION_REFUSED error might not just be CORS:

  • Confirm your Spring Boot app is actually running on localhost:8080 (check console logs for port info).
  • Test the SockJS handshake directly: Run curl http://localhost:8080/notifications/info in your terminal. If you get a JSON response like {"entropy":...}, the server is reachable—problem is CORS. If not, your server isn't listening on that port.

Fix 2: Resolve SSE CORS Issues

EventSource requires explicit CORS approval for the SSE endpoint. Your current controller doesn't include CORS configuration, so add it directly:

@CrossOrigin(origins = "http://localhost:4200") // Match your Angular origin
@GetMapping("/stream-sse")
public Flux<ServerSentEvent<String>> streamEvents() {
    return Flux.interval(Duration.ofSeconds(1))
            .map(sequence -> ServerSentEvent.<String>builder()
                    .id(String.valueOf(sequence))
                    .event("periodic-event")
                    .data("SSE - " + LocalTime.now().toString())
                    .build());
}

Alternatively, if you use a global CORS config, ensure it includes the /stream-sse path:

@Configuration
public class GlobalCorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:4200")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

Final Testing Steps

  1. Restart your Spring Boot server after making config changes.
  2. Test the SSE endpoint directly in your browser: Visit http://localhost:8080/stream-sse—you should see a stream of timestamped messages.
  3. Start your Angular app and retry the WebSocket/SSE connections.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 06:47:37