我創(chuàng)建了一條路由/stream,該路由應(yīng)該每秒推送一次字符串“ test”。當我localhost:12346/stream在Chrome上打開此URL()時,它的確打開了一個空白頁面,并且每秒都會在頁面上附加一個“測試”,因此我認為服務(wù)器端可以正常工作。當我在Firefox上打開它時,它將其視為永遠不會完成的文件下載。但是,當我client.html在下面打開時,onmessageEventSource對象的事件從未觸發(fā),因此我沒有任何數(shù)據(jù)。該onopen事件已被觸發(fā),我在控制臺中看到了該事件。為什么是這樣?如何在JavaScript端接收數(shù)據(jù)?server.py:import flaskimport flask_corsimport timeapp = flask.Flask(__name__)app.debug = Trueflask_cors.CORS(app)def event_stream(): while True: time.sleep(1) yield 'test\n'@app.route('/stream')def stream(): return flask.Response(event_stream(), mimetype='text/event-stream')app.run(port=12346, threaded=True)client.html:<!DOCTYPE html><html> <body> <script> var source = new EventSource('http://localhost:12346/stream'); source.onopen = e => console.log('opened', event); source.onerror = e => console.log('error', event); source.onmessage = e => console.log('onmessage', event); </script> </body></html>
即使Flask服務(wù)器推送似乎起作用,EventSource.onmessage也不會觸發(fā)
炎炎設(shè)計
2021-05-21 19:06:01