node.js - 从 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 开始并做出反应:)
解决方案
推荐阅读
- c# - ASPNetCore API IFormFile 返回“无效输入”
- django - Django Rest Framework 将额外的参数传递给 Serializer
- ios - 将base64字符串格式的图片上传到服务器
- asp.net - 如何在 ASP.Net 应用程序的 react.js 前端处理身份验证状态
- ruby - Ruby Nokogiri 抓取数据 URL
- django - Django 为管理员和员工用户建模清洁方法
- c++ - Makefile 创建两个库 - 一个依赖于另一个
- android - android NDK致命错误:stdio.h:没有这样的文件或目录#include
- java - Java 盒子的最大体积 --objects/array
- vue.js - 通过 Vue Computed Setter 调用 Vuex Action