我正在尝试使用Event Wource API和Action控制器实时实现基本的Rails 4代码。一切都很好,但我无法联系事件监听器。

控制器代码:

  class HomeController < ApplicationController
            include ActionController::Live
     def tester
            response.headers["Content-Type"] = "text/event-stream"
            3.times do |n|
            response.stream.write "message: hellow world! \n\n"
            sleep 2
    end
end


js代码:

var evSource = new EventSource("/home/tester");

evSource.onopen = function (e) {
  console.log("OPEN state \n"+e.data);
};

evSource.addEventListener('message',function(e){
console.log("EventListener .. code..");
},false);

evSource.onerror = function (e) {
   console.log("Error State  \n\n"+e.data);
};


重新加载页面时,控制台输出为“ OPEN状态”,然后为“错误状态”。事件侦听器代码未显示。


当我卷曲页面时,“消息:Hellow world!”正在显示。
我在development.rb中更改了

config.cache_classes = true
config.eager_load = true
我的浏览器是chrome&firefox是最新版本,因此没有问题


我在哪里失踪?建议请!

最佳答案

服务器发送的事件的事件格式为

"data: message text\n\n"


因此,在您的情况下,应为:

response.stream.write "data: hello world! \n\n"


检查this MDN page以供参考。

07-28 03:17