Skip to content

Instantly share code, notes, and snippets.

@dandynaufaldi
Created October 25, 2020 20:45
Show Gist options
  • Save dandynaufaldi/b1360174505fb098390a37744743b7d3 to your computer and use it in GitHub Desktop.
Save dandynaufaldi/b1360174505fb098390a37744743b7d3 to your computer and use it in GitHub Desktop.
Consume SSE in client
function appendChat(chat) { ... }
function sendChat() {
event.preventDefault();
const chatForm = document.getElementById("chat-form");
const chatMessage = chatForm.elements.message.value;
const xhr = new XMLHttpRequest();
xhr.open('POST', 'chat');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (xhr.status === 201) {
chatForm.elements.message.value = "";
}
};
xhr.send(JSON.stringify({
user: currentUser,
message: chatMessage
}));
}
const source = new EventSource("{{ url_for('sse.stream') }}");
source.addEventListener('chat', function (event) {
const chat = JSON.parse(event.data);
appendChat(chat)
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment