Lunaxy Li
Lunaxy Li

Reputation: 50

Server Side Event - onmessage not firing

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)
}

enter image description here

Connection establishes successfully and events received can be found in Chrome Network Recording as following image shown. But onmessage is never triggered!

enter image description here

Any comment will be appreciated.

Upvotes: 1

Views: 949

Answers (1)

Phil
Phil

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. The onmessage handler is called if no event name is specified for a message.

Upvotes: 5

Related Questions