Question

I'm trying to implement basic Rails 4 code with Event Wource API & Action controller live. Everything is fine but I'm not able to reach event listener.

Controller code:

  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 code:

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);
};

When I reload the page, my console output was "OPEN state" & then "Error State". Event listener code was not displaying.

  1. When I'm curling the page, "message: Hellow world!" was displaying.

  2. I changed in development.rb

    config.cache_classes = true
    config.eager_load = true

  3. My browsers are chrome & firefox are latest versions, so no issues with them

Where I'm missing? suggestions please!

Was it helpful?

Solution

Event format for server-sent events is

"data: message text\n\n"

So, in your case it should be like:

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

Check this MDN page for reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top