如何在 Rails5(API 模式)应用程序的静态页面中使用 ActionCable 客户端?

How do I use ActionCable client in react static page for the Rails5(API mode) app?

我正在为 React 网站开发 Streaming API with Rails5 api 模式。
在通知功能中使用它。

我在下面的环境中:

<server side>
rails: v5.1.5
ruby: 2.4.2

<client side>
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-router": "^2.7.0",
"actioncable": "^5.1.5",

服务器端代码:
app/channels/notifications_channel.rb

class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "notifications"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

development.rb

config.action_cable.url = "ws://localhost:3000/cable"

application.rb

# websocket
config.action_cable.allowed_request_origins = [
    # Local address of our RoR server
    'http://localhost:3000',
    # Local address we use for our React standalone client
    'http://localhost:8000',
    'chrome-extension://pfdhoblngboilpfeibdedpjgfnlcodoo'
]
ActionCable.server.config.disable_request_forgery_protection = true

routes.rb

mount ActionCable.server => '/cable'

xxx.rb

ActionCable.server.broadcast('notifications', notification: @notification)

客户端:

componentDidMount () {
  this.createSocket()
}

createSocket = () => {
  let App = {};
  App.cable = ActionCable.createConsumer('ws://localhost:3000/cable');

  let subscription = App.cable.subscriptions.create({channel:'NotificationsChannel'}, {
    connected : () => {},
    disconnected : () => {},
    received : (data) => {
      console.log(data)
    }
  });
  console.log(subscription)
};

所以,这是服务器端控制台

Started GET "/cable" for 127.0.0.1 at 2018-03-02 13:37:30 +0800
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2018-03-02 13:37:30 +0800
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION:Upgrade, HTTP_UPGRADE: websocket)
NotificationsChannel is transmitting the subscription confirmation
NotificationsChannel is streaming from notifications

我指的是这个网站 https://www.npmjs.com/package/actioncable and https://blog.heroku.com/real_time_rails_implementing_websockets_in_rails_5_with_action_cable 这个。

但是 data 未显示在客户端控制台中。 如何更改代码?

感谢@GorillaApe

我解决了这个问题。 这是通过设置 cable.ymlaysnc 在这种情况下不起作用。 redis 作为适配器更好。

这是我现在的cable.yml

development:
  adapter: redis
  url: redis://localhost:6379

test:
  adapter: redis
  url: redis://localhost:6379

production:
  adapter: redis
  url: redis://localhost:6379
  channel_prefix: api_notification_production