前端EventSource收不到流数据及EventSource的onmessage不执行问题

问题描述

在使用EventSource的onmessage接收后台数据时,发现不论怎么写,都没法在前端展示后台返回过来的数据,但是event.error和open是可以执行的,前段代码如下:



  
  EventSource Example


get my page!

var source = new EventSource("/interface"); source.onmessage = function(event) {. //这里不执行 // Update the content of the HTML page with the data received from the EventSource document.getElementById("messages").innerHTML += event.data; }; source.onerror = function(event) { //这却能执行 console.log("EventSource error:", event); }; source.onopen = function(event) { //这也能执行 console.log("EventSource connection opened"); };

解决方法

EventSource在前端是有自己的一套解析格式的,即:

event: message\n
data: {BackendValue}\n\n

其中,BackendValue是你要返回给前端的内容。

所以我们后端返回数据时,比如你要返回一个字符串,那就把字符串的头部拼接上event: message\ndata: , 并把字符串的尾部拼接上\n\n,即在你的数据尾部增加两个换行回车。

JSP格式的表示如下:

out.write("event: message\n");
out.write("data:" + value + "\n\n");

应该看得很清楚了,如果还不理解,看一下我推荐的几篇文章,就懂了。

参考这篇文章:EventSource onmessage() is not working

参考这篇论坛讨论:EventSource的onmessage不执行

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/aba3c83d62.html