我正在将现有的生产应用程序从 jquery 转换为 react.js。后端是用 Java (spring boot) 编写的。现有应用程序使用 Server-Sent Events 将某些类型的通知从服务器后端推送到 Web 客户端。现有的生产应用程序运行良好。
对于 UI 重写,我正在使用由 CRA(Create React App)端口 3000 和默认代理制作的 react.js,通过我的 spring boot 服务器在同一台机器上运行在端口 7001 上,所有这些都在开发环境中。
在 React 中,EventSource 被实例化,请求被传递到 spring boot 服务器。它正在注册用户,一切看起来都很好。当要从 springboot 发送通知消息以做出反应时,我看到在 React 中调用了 onopen() 消息处理程序,并且 readyState 从 0(待处理)转换为 1(打开)。然后什么也没有发生。永远不会调用消息处理程序。 javascript 控制台或 springboot 服务器后端没有错误(即使为所有包启用了 DEBUG 级别)。我在浏览器网络选项卡中没有看到任何错误(在本例中为 Firefox)。在另一个浏览器中,我运行了一个旧的 jquery 客户端,它确实收到了消息。
"proxy": "https://localhost:7001",
"private": true,
"dependencies": {
"@ant-design/icons": "^5.0.1",
"@reduxjs/toolkit": "^1.9.4",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"antd": "^5.4.2",
"antd-mobile": "^5.29.1",
"antd-mobile-icons": "^0.3.0",
"axios": "^1.3.5",
"bounce.js": "^0.8.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^8.0.5",
"react-router-dom": "^6.10.0",
"react-scripts": "5.0.1",
"web-vitals": "^3.3.1"
},
来自 React 功能组件的代码片段:
const eventSource = new EventSource("/api/register/39/event/944?registrationCode=MDB");
console.log(`DEBUG: eventSource.readyState=${eventSource.readyState}`);
useEffect(() => {
console.log(`DEBUG: useEffect| eventSource.readyState=${eventSource.readyState}`);
eventSource.onopen = (e) => {
console.log("DEBUG: eventSource connection open!",e);
console.log(`DEBUG: onopen | eventSource.readyState=${eventSource.readyState}`);
};
eventSource.onerror = (e) => {
if (e.readyState === EventSource.CLOSED) {
console.log("DEBUG: eventSource connection CLOSED! Trying to reconnect!");
}
};
eventSource.onmessage = (event) => {
console.log("DEBUG: onmessage received! result=",event.data);
};
// return function cleanup() {
// console.log(
// `DEBUG: EventSourceController.cleanup() called. Closing open stream.`
// );
// eventSource.close();
// };
//[eventSource]
});
我已经在网上搜索了关于 SSE 和 React 是否有任何有趣的业务可以寻找,但没有任何东西跳出来。
有这个类似的未回答的问题here但我没有足够的声誉点来投票甚至提供评论。
我没有理由相信消息类型会像 这篇文章 所建议的那样在后端被覆盖,因为我在旧的 jquery 应用程序中使用相同的消息处理程序并且它能够毫无问题地接收消息。
你能展示从服务器发送的数据示例吗?
您确定
event
字段(在已发送的消息中)为空,不存在或等于message
?
eventSource.onmessage
仅在客户端(浏览器)收到具有 undefined 或 message
类型的事件时调用。