Flask 和 jQuery - "onMessage" 事件未被调用
Flask and jQuery - "onMessage" event not being called
我正在为一个项目开发 Web 界面,需要绘制一个实时图表,其中包含一些我将从我正在构建的 API 中获得的数据。 API 在 http://SERVER_IP:5000/signal and my web interface on http://SERVER_IP:80/ 上运行,它们都使用 Flask。
一开始我遇到了 CORS 问题,然后才发现 Flask-CORS。我尝试实现它,现在我在浏览器控制台上没有收到任何错误,但也没有任何消息!我添加了一些用于调试的控制台消息,但它似乎不正确。
在我的仪表板上,我尝试使用以下代码到达 API:
const source = new EventSource("http://SERVER_IP:5000/signal", {withCredentials: true});
console.log ("Things started!!!");
source.onmessage = function (event) {
console.log ("An event's just happened");
// parse data and do stuff
}
在我的 API 中,我这样设置 Flask-CORS:
self.__cors = CORS(self.__app, supports_credentials = True)
路线如下:
@self.__app.route('/signal')
def get_signal():
import json
def get_data():
while True:
json_data = json.dumps(...)
yield "{}\n\n".format(json_data)
time.sleep(1)
return Response(get_data(), mimetype='text/event-stream')
然后,当我打开网络浏览器并打开控制台时,我可以看到 "Things started!!!" 消息,但没有 "An event's just happened",图表上也没有数据。
我的回复格式有误。正如我发现 here,我的 "get_data" 方法应该产生 "data: ...",所以在我的数据后添加 "data: " 之后,事情开始运行得很好。
我正在为一个项目开发 Web 界面,需要绘制一个实时图表,其中包含一些我将从我正在构建的 API 中获得的数据。 API 在 http://SERVER_IP:5000/signal and my web interface on http://SERVER_IP:80/ 上运行,它们都使用 Flask。
一开始我遇到了 CORS 问题,然后才发现 Flask-CORS。我尝试实现它,现在我在浏览器控制台上没有收到任何错误,但也没有任何消息!我添加了一些用于调试的控制台消息,但它似乎不正确。
在我的仪表板上,我尝试使用以下代码到达 API:
const source = new EventSource("http://SERVER_IP:5000/signal", {withCredentials: true});
console.log ("Things started!!!");
source.onmessage = function (event) {
console.log ("An event's just happened");
// parse data and do stuff
}
在我的 API 中,我这样设置 Flask-CORS:
self.__cors = CORS(self.__app, supports_credentials = True)
路线如下:
@self.__app.route('/signal')
def get_signal():
import json
def get_data():
while True:
json_data = json.dumps(...)
yield "{}\n\n".format(json_data)
time.sleep(1)
return Response(get_data(), mimetype='text/event-stream')
然后,当我打开网络浏览器并打开控制台时,我可以看到 "Things started!!!" 消息,但没有 "An event's just happened",图表上也没有数据。
我的回复格式有误。正如我发现 here,我的 "get_data" 方法应该产生 "data: ...",所以在我的数据后添加 "data: " 之后,事情开始运行得很好。