我一直试图让基本服务器启动并使用以下代码(后端的nodejs+express和前端的响应)运行事件,但是当我试图通过终端更新count时,onmessage并没有触发。
以下是流程:
启动并运行服务器。localhost:9000.
0.
POST调用来更新通知计数的,如下所示:curl -X POST -H "Content-Type: application/json“-d '{"count":10}‘-s http://localhost:9000/notification
在运行服务器的终端外壳中,可以看到触发了0.回调,但是count仍然是
这是我试过的代码。获取主题中提到的错误(在浏览器的控制台中看到)和UI不使用更新的通知count.Please更新,让我知道我做错了什么:
服务器代码(NodeJS+Express):
const sseHandler = (req: express.Request, res: express.Response) => {
console.log("server sent event handler triggered");
//Mandatory headers and http status to keep connection open
const headers = {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache'
};
res.writeHead(200, headers);
//After client opens connection send all notifications as string
const data = `count:${notificationCount}\n\n`;
console.log(data);
res.write(data);
// Generate an id based on timestamp and save res
// object of client connection on clients list
// Later we'll iterate it and send updates to each client
// In Real world scenario, client list should be saved to the DB
const clientId = Date.now();
const newClient = {
id: clientId,
res,
};
clients.push(newClient);
// When client closes connection we update the clients list
// avoiding the disconnected one
req.on('close', () => {
console.log(`${clientId} Connection closed`);
clients = clients.filter(c => c.id !== clientId);
});
};
// Iterate clients list and use write res object method to send latest notification count
const sendEventsToAll = (count:number) => {
console.log("send event to all");
clients.forEach(c => c.res.write(`count:${count}\n\n`));
};
// Middleware for POST /notification endpoint
const updateNotification = async (
req: express.Request,
res: express.Response,
) => {
let currentCount= req.body.count;
console.log("post count is: ", currentCount);
// Send recently updated notification count as POST result
res.json({count: currentCount});
// Invoke iterate and send function
return sendEventsToAll(currentCount);
}反应码
const Nav = () => {
const router = useRouter();
const [ notificationCount, setNotificationCount ] = useState(0);
useEffect(() => {
console.log("rendered on client");
const events = new EventSource('http://localhost:9000/events');
events.onmessage = (event) => {
console.log("Entering on message callback");
console.log(event);
// console.log(event.data);
// const parsedData = JSON.parse(event.data);
// setNotificationCount(() => parsedData.count);
};
}, [notificationCount]);
// record rendering counter
metrics.recordCounter({
name: "NavBar",
eventName: "render",
value: 1,
});
return (
<nav>
<ul>
<li className={router.pathname === "/" ? "active" : ""}>
<Link href="/">
<a>Home</a>
</Link>
</li>
<li className={router.pathname === "/dangerously_set" ? "active" : ""}>
<Link href="/xss-testing">
<a>XSS Testing</a>
</Link>
</li>
{links.map(({ key, href, label }) => (
<li key={key}>
<a href={href}>{label}</a>
</li>
))}
<a href="#" className="notification">
<span>Notification</span>
<span className="badge">{notificationCount}</span>
</a>
</ul>
);
}发布于 2020-06-24 09:04:53
我不得不停止默认压缩响应体,这就做到了这一点。下面是我放置的检查(响应头检查Content-Type):
const shouldCompress = (
req: express.Request,
res: express.Response
): boolean => {
// don't compress responses explicitly asking not
if (req.headers["x-no-compression"] || res.getHeader('Content-Type') === 'text/event-stream') {
return false;
}
// use compression filter function
return compression.filter(req, res);
};我的nodejs+express代码如下所示使用压缩中间件:
import compression from "compression";
...
..
.
.
.
/**
* Express application setup
*/
const expressApp = express();
// setup compression in express
expressApp.use(compression({ filter: shouldCompress }));此外,来自服务器的响应应该有以下字段:https://javascript.info/server-sent-events#server-response-format
发布于 2022-11-04 19:07:58
你的数据格式不好!您需要包括这些字段:消息可能包含以下字段:
数据:-消息主体,多个数据序列被解释为单个消息,各部分之间有\n。id:-更新lastEventId,在重新连接时发送最后一个事件ID。retry:-建议对ms中的重连接进行重试延迟。没有办法从JavaScript设置它。事件:-事件名称,必须位于数据之前:。
事件应该是“消息”,以便在客户端调用onmessage!
https://stackoverflow.com/questions/62538985
复制相似问题