我的设置非常简单。
NodeJs
export default class StreamController {
public static newMessage = async (req: Request, res: Response) => {
const { userid } = req.params;
res.writeHead(200, {
"Connection": "keep-alive",
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
});
setInterval(async () => {
console.log(await MessagesController.hasNewMessage(userid));
res.write(`${JSON.stringify({ hasUnread: await MessagesController.hasNewMessage(userid) })}`);
res.write("\n\n");
}, 5000);
}
}
React
constructor() {
super();
const uid = getUserId();
const eventSource = new EventSource(`http://localhost:8080/stream/messages/${uid}`)
eventSource.onmessage = (e) => {
console.log(e)
}
}
我看到流已经打开,但从服务器没有传递任何事件,而服务器端发出了数据。我做错了什么吗?