我一直在尝试使用以下代码来启动并运行基本服务器发送的事件(nodejs + express用于后端,React在前端上),但是当我尝试更新{{1时,onmessage
不会触发}}通过终端。
这是流程:
count
。localhost:9000
。0
调用通过cURL更新通知计数,如下所示:curl -X POST -H“内容类型:application / json” -d'{“ count”:10}'-s http:// localhost:9000 / notification
POST
回调,但是/events
仍然是count
。这是我尝试的代码。在主题(在浏览器的控制台中看到)和UI中提到的获取错误不会随着更新的通知计数而更新。请让我知道我做错了什么:
服务器代码(NodeJS + Express):
0
反应代码
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);
}
答案 0 :(得分:1)
我不得不停止响应正文的默认压缩,从而达到了目的。这是我放置的支票(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