有什么方法可以将Spring REST端点的Flux <string>返回到Web浏览器/前端应用程序(即Angular 6)?

时间:2019-05-14 03:26:47

标签: java spring-boot spring-webflux

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

这是用于Apache Tomcat服务器,在STS(Spring工具套件)IDE中运行spring-boot 5,JAVA 8。

@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不可接受”错误。

1 个答案:

答案 0 :(得分:1)

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'
});

您可以在以下博客文章中找到有关服务器发送事件的良好解释: A Look at Server-Sent Events