首页 > 解决方案 > 从 NodeJs 到 React 客户端的通知不起作用(服务器发送事件)

问题描述

每当有人访问我的 NodeJs 请求时,我都会尝试向我的 React UI 发送通知。请求如下:

 app.get('/notification', (req, res) => {
        res.writeHead(200, {
            "Connection": "keep-alive",
            "Content-Type": "text/event-stream",
            "Cache-Control": "no-cache",
            "Access-Control-Allow-Origin": "*"
          });
            
           
        if(req.query.id == 'audio')
        {
            res.write(`data: TEST\n\n`);
            res.write("\n\n");
        }

        res.end();

  })
  .listen(5000, () => {
    console.log("Server running at http://127.0.0.1:5000/");
  });

在我的组件构造函数( App )中,我使用了 EventSource,如下所示:

constructor(props) {
    super(props);

    this.eventSource = new EventSource( 'http://' + CONSTANTS.IP_API +':5000/notification');
    this.eventSource.onmessage = function(e) {
            console.log(e.data);
    };
 }

但是,正如您可能已经猜到的那样,它不起作用。

我不知道这是否是 EventSource 的预期工作方式以及我是否不理解这一点,但是在调用 时http://localhost:5000/notification?id=audio,我看到我的结果显示为响应,但此结果未显示在 UI 控制台中。似乎 EventSource 侦听器没有捕捉到它......

监听器每秒都尝试连接,但我需要一个实时监听器。EventSource 适合这个吗?或者我应该改用 socket.io 吗?

在此先感谢,如果这听起来微不足道,请原谅我,我从 NodeJs 开始并做出反应:)

标签: node.jsreactjsserver-sent-eventseventsource

解决方案


推荐阅读