当前位置:   article > 正文

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

sse onopen数据流获取不到

问题描述

在使用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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

解决方法

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

event: message\n
data: {BackendValue}\n\n
  • 1
  • 2

其中,BackendValue是你要返回给前端的内容。
所以我们后端返回数据时,比如你要返回一个字符串,那就把字符串的头部拼接上event: message\ndata: , 并把字符串的尾部拼接上\n\n,即在你的数据尾部增加两个换行回车。
JSP格式的表示如下:

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

应该看得很清楚了,如果还不理解,看一下我推荐的几篇文章,就懂了。
参考这篇文章:EventSource onmessage() is not working
参考这篇论坛讨论:EventSource的onmessage不执行

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/464561
推荐阅读
相关标签
  

闽ICP备14008679号