javascript - eventSource 不会触发 onmessage 函数

标签 javascript node.js eventsource

我使用express模块​​在node.js中创建了一个服务器。它公开了一个 get api,用于通过始终保持事件状态的打开连接定期向客户端发送事件。

const cors = require('cors');
const app = express();
app.use(cors());
const port = 3001;

app.get('/sse-server', function (request, response) {
    response.status(200).set({
        "connection": "keep-alive",
        "cache-control": "no-cache",
        "content-Type": "text/event-stream"
    });
    let data = { name: "Mithoon Kumar"}
    setInterval(()=>{ response.write(JSON.stringify(data));}, 0)

})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

我还在node.js中创建了一个客户端,它使用eventsource来接收服务器发送的事件

console.log("EventSource", EventSource);
const eventSource = new EventSource('http://127.0.0.1:3001/sse-server');

eventSource.onopen = (event) => {
   console.log("event", event);
};

eventSource.onerror = (error) => {
    console.log("error", error);
}

eventSource.onmessage = (message) => {
    console.log("message", message);
}

问题是 onmessage 方法永远不会被触发。如果我在 Chrome 浏览器中打开链接 ( http://127.0.0.1:3001/sse-server ),它会在页面上显示消息。

最佳答案

显然,EventSource 仅适用于其文档中定义的特定格式。正如您在 this example 中看到的那样,消息数据应以 data: [YOUR_DATA]\n\n 格式发送。

您应该在服务器端使用类似的内容:

app.get('/event-stream', (req, res) => {    
    res.status(200).set({
        "connection": "keep-alive",
        "cache-control": "no-cache",
        "content-Type": "text/event-stream"
    });

    let data = { name: "Mithoon Kumar" }
    const intervalId = setInterval(() => {
        res.write(`data: ${JSON.stringify(data)}\n\n`);
    }, 1000);

    req.on('close', () => {
        clearInterval(intervalId);
    });
});

关于javascript - eventSource 不会触发 onmessage 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59154961/

相关文章:

node.js - 加载共享库 : libgtk-x11-2. 0.so.0 时出错:

javascript - 带有 Sequelize 的 Node.js 数据库模块

javascript - 用EventSource获取User的在线状态靠谱吗?

javascript - 与阿多尼斯 react

node.js - 请求 - 如何 "emitter.setMaxListeners()"?

javascript - 替代多个“if 语句?

java - 为 Android 实现 Kaazing EventSource

spring - 在 Angular 5 中接收 Flux SSE

javascript - javascript 中的 SVG 翻译转换在 IE 11 中不起作用

javascript - 数组推送在 toArray 函数内部不起作用使用 mongoDB