我正在尝试将事件从服务器发送到客户端,并在客户端注册它。
我的转到代码:
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Fprintf(w, "id: %v\nevent: msg\nmessage: %v\n\n", id, "hello")
fmt.Printf("id: %v\nevent: msg\nmessage: %v\n\n", id, "hello")
id++
客户端JS:
function dump_event(e) {
console.log("received event")
$("#output").append("id: " + e.lastEventId + "\nevent: " +e.type + "\nmessage: " + e.data + "\n\n");
}
$(function() {
$("#listen").on('click', function (e) {
e.preventDefault()
if (source != null) {
source.close();
}
source = new EventSource($("#backend").val() + $("#channel").val());
source.addEventListener('msg', dump_event);
source.addEventListener('timeout', dump_event);
});
尽管提琴手确实显示我实际上已接收到数据,但它不是控制台记录的。我真的很感谢您的帮助,我在做错什么吗?