Reputation: 50
I'm trying to consume sse response in javascript. The onopen and onerror works well but onmessage not.
var conn = new EventSource(`${config.serverHost}/log/stream/${this.streamId}`)
conn.onopen = (evt) => {
console.log('connected to ' + logSourceId)
}
conn.onmessage = (evt) => {
console.log(evt)
}
conn.onerror = (evt) => {
console.error(evt)
}
Connection establishes successfully and events received can be found in Chrome Network Recording as following image shown. But onmessage is never triggered!
Any comment will be appreciated.
Upvotes: 1
Views: 949
Reputation: 165059
You appear to be using named events (something along the lines of "log streami...").
To support these, you need to use the addEventListener
format.
// assuming the event name is "log streaming"
conn.addEventListener("log streaming", e => {
console.log("log streaming", e)
})
FYI, onmessage
is for any un-named events, aka those event streams without an event
property.
event
A string identifying the type of event described. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use
addEventListener()
to listen for named events. Theonmessage
handler is called if no event name is specified for a message.
Upvotes: 5