简体   繁体   中英

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. (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.

It would be enaugh to have any hint how this works in JavaScript, then it will also work in angular.

text/event-stream is the mime type associated with Server-sent Events. 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 .

Here's a simple example of handling a Server-sent Event in plain Javascript - yourSSEURL is the URL that returns the text/event-stream:

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...";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM