Issue
I am using Flask for backend and Angular for frontend. I am implementing Server-Sent Events (SSE) for some task. Unfortunately, I am not able to receive any data from the SSE.
Banckend:
@app.route('/stream')
def stream():
def event_stream():
while True:
time.sleep(1)
yield 'data: some data\n\n'
return Response(event_stream(), mimetype='text/event-stream')
Frontend:
ngOnInit(): void {
var eventSource = new EventSource('http://127.0.0.1:5000/stream')
eventSource.onmessage = (e) => {
console.log(e.data); // Not working
this.eventData = e.data; // Not working
}
}
The issue with this code is the if I am commenting time.sleep(1)
line in the backend, then I am able to see the response in the Chrome's dev tools, but not able to bind it in the HTML file. So, if I keep it like that, then I am not able to see either of them.
I am facing one more issue, when I am terminating the backend (by killing the command promt), I am able to see that the failed calls are still being continuously made from the browser to the event stream. I believe, SSEs are always sent from the server/backend, but in this case the client/browser is requesting for the event. Is my understanding wrong?
I have attached an image for reference.
Solution
Use eventSource
's addEventListener
method:
eventSource.addEventListener('message', (e) => {
this.eventData = e.data;
});
eventSource.addEventListener('error', (e) => { // This will properly close the stream, when it ends.
eventSource.close();
});
Answered By - ngShravil.py
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.