I have an express app, with a server connected to a client. I have server data that I want to send to the client, and a button on the client that I want to trigger a function on the server. I have successfully implemented the server-> client connection through the following code:
client js
const source = new EventSource('/events');
source.addEventListener('message', message => {
...
});
server js
express()
...
.get('/events', async function(req, res) {
res.set({
'Cache-Control': 'no-cache',
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive'
});
res.flushHeaders();
while (true) {
await new Promise(resolve => setTimeout(resolve, 1000));
res.write(`data: some text\n\n`);
}
})
...
This lets me send data to the client from the server. However, I also have a button on the client that I would like to call a function on the server. I think I've seen methods with ajax, but I am trying to avoid that if possible. Is there a way to do basically the reverse of the code above, where I can trigger a server event from the client (like a client sent event instead of the server sent event I have above), without ajax? Thanks