首页 > 解决方案 > 有什么方法可以返回 Flux从 Spring REST 端点到 Web 浏览器/前端应用程序(即 Angular 6)?

问题描述

我想将 Flux 返回到浏览器,但是当我到达终点时,它给了我“406 不可接受”错误。

这适用于运行 spring-boot 5、JAVA 8 的 Apache Tomcat 服务器。在 STS(Spring Tool Suite)IDE 中。

@RestController
public class CloudFoundry {
    @GetMapping(value = "/LogApplication", produces =
            MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> logApplication() throws Throwable {
        return Flux.just("a", "b", "c", "d");

    }
}

当我在本地主机上到达终点时,它应该给我字符串流,但它给了我“406 不可接受”错误。

标签: javaspring-bootspring-webflux

解决方案


MediaType.TEXT_EVENT_STREAM_VALUE用于需要适当使用的服务器发送事件。

这是您在前端需要具备的:

// Declare an EventSource
const eventSource = new EventSource('http://server.url/LogApplication');
// Handler for events without an event type specified
eventSource.onmessage = (e) => {
  // Do something - event data etc will be in e.data
};
// Handler for events of type 'eventType' only eventSource.addEventListener('eventType', (e) => {
  // Do something - event data will be in e.data,
  // message will be of type 'eventType'
});

您可以在以下博客文章中找到关于服务器发送事件的一个很好的解释: 查看服务器发送事件


推荐阅读