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

问题描述

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

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>EventSource Example</title>
</head>
<body>
<h1>get my page!</h1>
  <div id="messages"></div>
  <script>
    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");
    };
  </script>
</body>
</html>

解决方法

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不执行

猜你喜欢

转载自blog.csdn.net/zoubaihan/article/details/130700056
今日推荐