【问题标题】:SSE `this.eventSource.onmessage` call fails. Error `"EventSource's response has a MIME type ("application/json") that is not "text/event-stream"SSE `this.eventSource.onmessage` 调用失败。错误`“EventSource 的响应具有不是“text/event-stream”的 MIME 类型(“application/json”)
【发布时间】:2020-05-01 16:38:42
【问题描述】:

Angular 服务器发送事件this.eventSource.onmessage 调用失败并出现错误"EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection." 我在Chrome 开发工具(附图片)中看到有两个Content-Type 被返回。

后端代码:Spring Reactor/REST

    @GetMapping(value="/events",produces = "text/event-stream;charset=UTF-8")
    public Flux<ConsumerEvent> getProductEvents(){
        return kafkaService.getReceiverRecordAllFlux()
                .map(record->
                    new ConsumerEvent(record.topic(),record.value())
                );
        }
}

前端:Angular

public startKafkaTopicInfoEventSource(): void {
    let url = BASE_URL;
    this.eventSource = new EventSource(url); 
    this.eventSource.onmessage = (event) => {//Error: EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection
        this.zone.run(() => {
        // some code here
      })

    }
// other code here
}

方法this.eventSource.onmessage给出错误EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection.

任何帮助都会很棒!

【问题讨论】:

  • 您的产品标签应该做正确的事。尝试改用produces = MediaType.TEXT_EVENT_STREAM,就像这里的例子:baeldung.com/spring-server-sent-events?
  • @MyStackRunnethOver 嗨,我已经这样做了。但问题仍然存在。如果您看到我在问题中附加的图像,我会得到两个 Content-Type 值。不知道为什么?当我在浏览器localhost:8181/events 中检查终点时,我成功地获得了输出,就像我刚刚附加的更新图像一样。问题在于通过 Angular 客户端调用 REST Url。不知道具体在哪里。
  • 这很奇怪。如果删除 ;charset=UTF-8 会发生什么?
  • 是的。 onmessage 给出了这个问题。如果我删除字符集,我想我仍然会遇到同样的问题。不过我会检查一下。
  • 您是否尝试过返回 ServerSentEvent 而不是 ConsumerEvent SSE 需要具有特定格式。试试ServerSentEvent.&lt;ConsumerEvent&gt;builder().data(new ConsumerEvent(record.topic(),record.value())).build()

标签: java angular spring-kafka server-sent-events spring-reactive


【解决方案1】:

我在使用 ASP.NET(和 nodeJS)时遇到了同样的问题。

我不知道这是否有帮助,但我经历过,如果您使用 Moesif Origin & CORS Changer(在标准配置中,我没有测试自定义的)一些标题会被添加或覆盖(选择“新”的) 由插件(至少是 Content-Type 和 X-Content-Type-Options),正如我们在您的开发工具屏幕截图中看到的那样。

所以也许您在 Chrome 中安装的某些插件会导致这种情况。尝试在不同的浏览器中运行或不使用插件。

希望我能帮助别人并度过愉快的一天!

【讨论】:

    猜你喜欢
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 2017-05-21
    • 2018-09-11
    • 2019-02-07
    相关资源
    最近更新 更多