eventsource.onmessage 未被调用 - flask 应用程序

eventsource.onmessage is not invoked - flask application

我一直在开发一个 flask 应用程序,并试图在其中实现 SSE。检查下面我的代码:

index.py

@app.route('/stream', methods=['GET'])
@cross_origin()
def stream():
    def listenstream():
        print("listening")
        displaytext =  { 'requestdata':  'Sampledata', 'responsedata' : 'Sample Data'}
        displaytext=json.dumps(displaytext)
        yield 'event: message\n'
        yield 'data : '+displaytext+'\n\n'
        time.sleep(1.5)

    return Response(response=listenstream(),status=200,mimetype="text/plain",content_type='text/event-stream')

custom.js

var eventSource = new EventSource("/stream");

eventSource.onmessage = function (e) {
   console.log("Onmessage"+e)
}


eventSource.onerror = function (e) {
   console.log("Onerror"+JSON.stringify(e))
}

eventSource.onopen = function (e) {
   console.log("Onopen"+JSON.stringify(e))
}

这里 eventSource.onerror => {"isTrusted":true} ,eventSource.onopen => {"isTrusted":true} 但是 eventSource.onmessage 没有被调用。我在 js 文件中尝试了 addEventListener:

var eventSource = new EventSource("/stream");
eventSource.addEventListener('message', (e) => {

console.log("Received update")
})

如果我渲染到 link 'http://localhost:5000/stream',它给出:

event: message

data : {"requestdata": "Sampledata", "responsedata": "Sampledata"}

但是我需要link“http://localhost:5000”上的数据。这是正确的做法吗?

将不胜感激:)

以下更新解决了我的问题:

index.py

     yield "event: {0}\ndata: {1}\n\n".format("listen",displaytext)

return Response(listenstream(), mimetype="text/event-stream")

custom.js

var eventSource = new EventSource("/stream");
eventSource.addEventListener('listen', function(e){ 

//Code here
},false);