Angular应用无法接收Spring WebFlux后端Server-Sent Events(SSE)问题求助
Angular应用无法接收Spring WebFlux后端Server-Sent Events(SSE)问题求助
我正在构建一个Spring WebFlux后端+Angular前端的应用,后端发送Server-Sent Events(SSE),但Angular应用无法接收这些事件,不过用Postman或curl测试后端是完全正常的。
以下是我目前的实现:
Backend (WebFlux)
WebFlux控制器使用MediaType.TEXT_EVENT_STREAM_VALUE发送SSE:
@GetMapping(value = "/purchasedItems", produces = MediaType.TEXT_EVENT_STREAM_VALUE) @ResponseStatus(HttpStatus.ACCEPTED) public Flux<PurchasedItemData> findAllPurchasedItem(ServerHttpResponse response){ response.getHeaders().add("Cache-Control", "no-cache, no-transform"); response.getHeaders().add("Connection", "keep-alive"); return purchaseService.getPurchasedItems() .doOnNext(item -> System.out.println("Sending item: " + item.getName())) .doOnError(error -> System.out.println("Error sending items: "+ error.getMessage())) .doFinally(signalType -> System.out.println("Streaming finished: " + signalType)); }
用curl或Postman测试这个端点时,能正常看到事件流。
Frontend (Angular)
我使用原生EventSource API来消费SSE:
private apiUrl = 'http://localhost:8080/paypro/purchasedItems'; fetchPurchasedItems(): Observable<any> { return new Observable(observer => { const eventSource = new EventSource(this.apiUrl); eventSource.onmessage = (event) => { try { debugger; const data = JSON.parse(event.data); console.log('Received SSE data:', data); // Debugging line observer.next(data); } catch (error) { console.error('Error parsing SSE data:', event.data, error); observer.error(error); } }; eventSource.addEventListener('message', (evt) => { console.log('Received SSE data:', evt.data); // Debugging line observer.next(evt); }); eventSource.onerror = (error) => { console.error('EventSource error:', error); debugger; observer.error(error); eventSource.close(); }; return () => eventSource.close(); }); }
在Angular组件中的调用:
public loadData() { // this.purchasedItems$ = this.service.fetchPurchasedItems(); this.isLoading = true; this.service.fetchPurchasedItems().subscribe({ next: (data) => { console.log('Fetched data:', data); debugger; this.purchasedItems=[...this.purchasedItems,...data]; this.cd.detectChanges(); // Trigger change detection }, error: (err) => { console.error('Error fetching data', err); this.isLoading = false; } }); }
Proxy Configuration
开发环境下,我用代理配置将请求重定向到后端:
proxy.conf.json:
{ "/paypro/*": { "target": "http://localhost:8080", "secure": false, "logLevel": "debug", "changeOrigin": true } }
问题
- Angular应用中,EventSource立即触发
onerror事件,没有收到任何数据 - 浏览器Network标签显示请求已发送,但连接立即关闭,没有任何SSE数据
- 后端日志没有任何错误
我已尝试的方案
- 用curl和Postman测试
/purchasedItems端点——完全正常 - 确保响应头包含
Content-Type: text/event-stream - 仔细检查Angular的代理配置
- 给WebFlux后端添加CORS设置:
@Bean public CorsWebFilter corsWebFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("http://localhost:4200"); config.addAllowedMethod("*"); config.addAllowedHeader("*"); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); }
是什么原因导致Angular应用无法消费WebFlux后端的SSE?该如何解决这个问题?
非常感谢任何帮助!
备注:内容来源于stack exchange,提问作者Yoni Shkolsky
相关产品推荐
相关产品推荐

