arthur
arthur

Reputation: 619

Flask-React Server Side Event

I am trying to implement a simple push function from Python-Flask to React for in app notifications

On the backend i got the following python code

@app.route("/stream", methods=['GET'])
def stream():
    print("push notif start", flush=True)
    def eventStream():
        while True:
            # Poll data from the database
            # and see if there's a new message
            today = datetime.date.today()
            print("push notif", flush=True)
            print(today, flush=True)
            yield f"event: notifications\ndata:{today}\n\n"
            time.sleep(5)
    
    return flask.Response(eventStream(), mimetype='text/event-stream')

On the front end, React: const eventSource = new EventSource("/stream");

eventSource.onmessage = function(e) {
    console.log(e);
    console.log(e.data);
};

When I run this, in the console I get an error:

EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.

Also, can't understand why, I don't see any of the flask's prints from my function. This is the same example as in almost every basic example that I could find that dealing with SSE.

Thanks

Upvotes: 1

Views: 897

Answers (1)

arthur
arthur

Reputation: 619

Well that is kind of silly, but the answer is simple - they do not write in the manuals that you need to use the full URL on the front side.

A mistake fit a true junior...

Upvotes: 1

Related Questions