java - 有什么方法可以返回 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 不可接受”错误。
解决方案
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'
});
您可以在以下博客文章中找到关于服务器发送事件的一个很好的解释: 查看服务器发送事件
推荐阅读
- python - 安装速度(clang:错误:不支持的选项'-fopenmp'错误:命令'gcc'失败,退出状态为1)
- mysql - 如何替换sql中的前7位
- c++ - C++ 如何从 Char 数组中取出一个字符串,然后将其保存为单独的字符串以供以后解析?
- primeng - 如何在 PrimeNg 中编辑单元格后设置自动宽度列?
- python - print 给出不同的输出
- excel - 将数据范围从无宏工作簿复制到另一个无宏工作簿
- node.js - Heroku 中的 Node-js 并发
- javascript - 在 HTML 中加载本地图像,但在作为数据属性传递时不加载
- laravel - 如何在 Laravel 中验证请求用户?
- r - stat_compare_meanspaired = TRUE 似乎配对了错误的值