I have a Vue 3 website showing a list fetched from a REST-API (using the fetch method). Then sometimes this list is modified in the original DB and I would like to update my vue component accordingly. The good news is that a webhook is posted to me by the DB service when an entry is modified. However, I do not know how to consume this webhook in my Vue project.
I know how to consume it with an express server with something like
app.post("/hook", (req, res) => {
console.log(req.body)
}
but I don't see how to connect this with my Vue app ?
Maybe it's not even a good approach.
--- Update:
I have implemented @kissu solution (SSE version) but I still have an issue. I have an Express server running : ```js const app = express(); ``` and i wait for a webhook:app.post("/hook", (req, res) => {
x=req.body.my_item;
newUpdate = true;
res.status(200).end()
})
and I have a get route for the SSE
app.get('/events', async function(req, res) {
const headers = {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Credentials' : false,
'Access-Control-Allow-Origin': 'https://grange.vercel.app',
};
res.writeHead(200, headers);
while (true) {
await new Promise(resolve => setTimeout(resolve, 500));
if (newUpdate)
{
res.write(`data: ${x}\n\n`);
res.send(`data: ${x}\n\n`);
newUpdate = false;
}
}
});
and await app.listen(443);
On the Vue side I have
sseClient = this.$sse.create({
format: 'plain',
polyfill: true,
url: 'https://sse.mydomain.fr/events',
withCredentials: false,
});
sseClient.connect()
.catch((err) => console.error('Failed make initial connection:', err));
sseClient.on('', this.handleMessage)
and handleMessage do the job of updating my page.
It works for a while then after a minute of inactivity (or sometimes randomly) I receive an 404 error from the sseserver (on the Vue page) because "Access-Control-Allow-Origin is missing". It looks like somehow, my Vue app cannot grab the header of the SSE sometimes and then fail.
Any suggestion @kissu ?