服务器发送的事件 EventStream 不触发 "onmessage" 但 Chrome 调试在 "EventStream" 选项卡中显示数据

Server sent event EventStream does not trigger "onmessage" but Chrome Debug shows data in "EventStream" tab

我将 SSE 与 javascript 的内置逻辑 EventStream 一起使用。虽然有 onopen return 成功结果,但 onmessage 回调不起作用。 奇怪的是,在 EventStream 选项卡的 Chrome 中,数据结果按照我的预期列出。

这是我的 EventSource 的 JS 片段

var eventSource;
  $(function () {
    eventSource  = new EventSource('get/status/');

    eventSource.onopen = function () {
      console.log("Sse connection opened");
    };

    eventSource.onerror = function () {
      console.log("error occured");
    };

    eventSource.onmessage = function (event) {
      console.log("received");
    };

  });

如您所见,正在发出数据,但从未触发 onmessage。有人可以向我解释这种行为吗?

编辑onopenonerror 都起作用。

根据屏幕截图,您的事件流包含类型为 "foo" 的事件,而不是 "message"。这只是默认类型(事件流中缺少 event 字段)。来自 the spec:

  1. Initialize event's type attribute to message, […]

  2. If the event type buffer has a value other than the empty string, change the type of the newly created event to equal the value of the event type buffer.

在这里,您应该将监听器设置为监听 "foo" 事件:

eventSource.addEventListener("foo", function() {...})