Angular+SpringBoot实现WebSocket/SSE连接遇跨域及连接拒绝问题求助
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
StompEndpointRegistrysettings, not the global WebMvc CORS rules. - Server-Sent Events (SSE) via
EventSourcealso 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/infoin 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
- Restart your Spring Boot server after making config changes.
- Test the SSE endpoint directly in your browser: Visit
http://localhost:8080/stream-sse—you should see a stream of timestamped messages. - Start your Angular app and retry the WebSocket/SSE connections.
内容的提问来源于stack exchange,提问作者pmueller

