Created
October 25, 2020 20:45
-
-
Save dandynaufaldi/b1360174505fb098390a37744743b7d3 to your computer and use it in GitHub Desktop.
Consume SSE in client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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