I want to use Server-Sent Events for my MERN project. I am having an issue and couldnt fix it yet.
export const getPosts = async (req, res) => {
try {
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
const posts = await Post.find();
res.write(`data: ${JSON.stringify(posts.reverse())}\n\n`);
res.on('close', () => {
console.log('client dropped me');
res.end();
});
} catch (e) {
res.status(404).json({ msg: e.message });
}
};
this is how I get posts, but I do want to SSE follow flow of posts. I want SSE follow the data in MongoDB, trigger when there is a change.