首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript EventSource被挂起的状态卡住了

Javascript EventSource被挂起的状态卡住了
EN

Stack Overflow用户
提问于 2020-02-08 10:47:53
回答 1查看 1K关注 0票数 3

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

因此,数据没有加载到React仪表板中,而是在加载时被卡住。我可以看到早些时候开放的溪流,尽管我关闭了它们:

代码语言:javascript
复制
  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()
  }, []);

这是什么原因,我该如何解决呢?

EN

回答 1

Stack Overflow用户

发布于 2022-03-14 22:46:55

"http://localhost:8080“表示您正在使用webpack-dev-server,并且由于您没有在eventSource中设置withCredentials:true,这意味着您允许CORS的"*”通配符,但您必须在webpack.config.js中设置CORS策略。

代码语言:javascript
复制
 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并记录错误:

代码语言:javascript
复制
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()
  }, []);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60126031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档