[英]Is it possible to consume text/event-stream with JavaScript in a WebBrowser?
We have a Rest Service that returns a text/event-stream
from a POST endpoint, which contains a series of JSON Objects.我们有一个 Rest 服务,它从 POST 端点返回一个
text/event-stream
,其中包含一系列 JSON 对象。 (It is a Spring Boot / Kotlin RestController that returns a kotlinx.coroutines.flow.Flow<SomeJSONObject>
) Now we want to consume this event-stream in a angular WebApplication, processing each object as it arrives. (It is a Spring Boot / Kotlin RestController that returns a
kotlinx.coroutines.flow.Flow<SomeJSONObject>
) Now we want to consume this event-stream in a angular WebApplication, processing each object as it arrives. Unfortunately we don't know how this works.不幸的是,我们不知道这是如何工作的。 We tried the obvious things, like:
我们尝试了显而易见的事情,例如:
this.http.post(url, request)
or或者
this.http.post(url, request).toPromise().then(value =>...
and和
this.http.post(url, request).subscribe(value =>...
It seems like the browser does not even make a request and does not receive any data.似乎浏览器甚至没有发出请求,也没有收到任何数据。 The backend service works fine, we can see this by calling the endpoint with eg postman.
后端服务工作正常,我们可以通过调用端点来看到这一点,例如 postman。
It would be enaugh to have any hint how this works in JavaScript, then it will also work in angular.有任何提示在 JavaScript 中如何工作就足够了,然后它也将在 angular 中工作。
text/event-stream
is the mime type associated with Server-sent Events. text/event-stream
是与服务器发送事件关联的 mime 类型。 You can read more about them and see some code examples here and there are plenty of tutorials online showing how to use them with Angular, such as this one .您可以在此处阅读有关它们的更多信息并查看一些代码示例,并且在线有大量教程展示了如何将它们与 Angular 一起使用,例如这个。
Here's a simple example of handling a Server-sent Event in plain Javascript - yourSSEURL
is the URL that returns the text/event-stream:这是在普通 Javascript 中处理服务器发送事件的简单示例 -
yourSSEURL
是返回文本/事件流的 URL:
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("yourSSEURL");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.