Setting up a basic event stream to the server
suggest changeYou can set up a browser page to listen for incoming server events with the EventSource object. Pass the constructor the path of the server endpoint that subscribes the client to those events.
Example:
var eventSource = new EventSource("api/my-events");
Events are categorized by name, and a listener must be set up for each name. The default event name is message, which uses .onmessage.
eventSource.onmessage = function(event) {
var data = JSON.parse(event.data);
// do something with data
}
The function runs each time the server pushes a message event. event.data is text. The stream response itself should use text/event-stream. Parse event.data when that text is JSON.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents