user5268025
user5268025

Reputation:

I am not getting any return response data in SSE [Server Sent Event] EventSource onMessage object from Flask backend?

onMessage object is not receiving any data from backend. Why it is happening. Here is my code using flask in backend.

flask.py

@app.route("/ride-list/",methods=["POST","GET"])
@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
def ride_list():
    conn=sqlite3.connect('shyori.db')
    cursor=conn.cursor()
    result=cursor.execute("SELECT * FROM ride;")
    result=list(result)
    conn.commit()
    conn.close()
    resp=jsonify(ride=result)
    resp.content_type="text/event-stream"
    return resp

demo.js

<script>
    var source=new EventSource("http://127.0.0.1:5000/ride-list/");
    console.log(source.onMessage);
    source.onMessage=function (e) {
        console.log(e);
    };
</script>

Upvotes: 0

Views: 2067

Answers (1)

Marcelo Vidigal
Marcelo Vidigal

Reputation: 49

You should use data: msg like this,

before your msg put data:...

Event Stream Format

Sending an event stream from the source is a matter of constructing a plaintext response, served with a text/event-stream Content-Type, that follows the SSE format. In its basic form, the response should contain a "data:" line, followed by your message, followed by two "\n" characters to end the stream:

data: My message\n\n

Upvotes: 4

Related Questions