프런트엔드 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()가 작동하지 않습니다.
이 포럼 토론을 참조하십시오: EventSource의 onmessage가 작동하지 않습니다.

추천

출처blog.csdn.net/zoubaihan/article/details/130700056