我使用服务器发送的事件和Javascript EventSource API作为实时反应仪表板,我有多个选项卡,每个选项卡都使用一个EventSource。当我在不同的选项卡之间导航时,事件流就会被挂起,就像下面屏幕快照上的最后一个"live“流一样:

因此,数据没有加载到React仪表板中,而是在加载时被卡住。我可以看到早些时候开放的溪流,尽管我关闭了它们:
const [data, setData] = useState(undefined);
const reportDataEventSource = new EventSource(
"http://localhost:8080/report/heatMap/live"
);
useEffect(() => {
reportDataEventSource.onmessage = e => {
setData(JSON.parse(e.data));
};
return () => reportDataEventSource.close()
}, []);这是什么原因,我该如何解决呢?
发布于 2022-03-14 22:46:55
"http://localhost:8080“表示您正在使用webpack-dev-server,并且由于您没有在eventSource中设置withCredentials:true,这意味着您允许CORS的"*”通配符,但您必须在webpack.config.js中设置CORS策略。
devServer: {
historyApiFallback: true,
watchOptions: { aggregateTimeout: 300, poll: 1000 },
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
}
},如果这不能解决问题,请设置onError并记录错误:
useEffect(() => {
// this also should be inside useEffect
reportDataEventSource.onmessage = e => {
setData(JSON.parse(e.data));
};
reportDataEventSource.onerror = () => {
// error log here
reportDataEventSource.close();
}
return () => reportDataEventSource.close()
}, []);https://stackoverflow.com/questions/60126031
复制相似问题