代码之家  ›  专栏  ›  技术社区  ›  mackeee

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

  •  1
  • mackeee  · 技术社区  · 7 年前

    我现在正在开发Rails5 API模式的流式API,用于React网站。
    在通知功能中使用它。

    我在下面的环境中:

    <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",
    

    服务器端代码:
    应用程序/频道/通知\u频道。rb型

    class NotificationsChannel < ApplicationCable::Channel
      def subscribed
        stream_from "notifications"
      end
    
      def unsubscribed
        # Any cleanup needed when channel is unsubscribed
      end
    end
    

    发展rb型

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

    应用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
    

    路线。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 https://blog.heroku.com/real_time_rails_implementing_websockets_in_rails_5_with_action_cable 这个。

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   mackeee    7 年前

    感谢@Gorillape

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

    这是我的 缆绳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