首页 > 解决方案 > 【Rails6】Action Cable don't GET '/action'

问题描述

我尝试在 Rails6 上使用 Action Cable。

我可以像下面这样从控制器广播,但无法在浏览器上接收。

ActionCable.server.broadcast "message_channel", message: message.content

因为在本地服务器日志上没有 GET /cable,我猜这是因为我在浏览器上运行的应用程序没有正确初始化 Action Cable。请告诉我如何初始化动作电缆。

我做了什么

mount ActionCable.server => '/cable'
config.action_cable.url = "ws:localhost:3000/cable"
config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/]
ActionCable.server.config.disable_request_forgery_protection = true
module ApplicationCable
  class Channel < ActionCable::Channel::Base
  end
end
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user
    def connect
      self.current_user = find_verified_user
    end

    private

    def find_verified_user
      if verified_user = User.find_by(id: cookies.encrypted[:user_id])
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end
class MessageChannel < ApplicationCable::Channel
  def subscribed
    stream_from "message_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end
// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.

import { createConsumer } from "@rails/actioncable";

export default createConsumer();
import consumer from "./consumer";
consumer.subscriptions.create("MessageChannel", {
  connected() {
    // Called when the subscription is ready for use on the server
    console.log("connected");
  },

  disconnected() {
    // Called when the subscription has been terminated by the server
  },

  received(data) {
    // Called when there's incoming data on the websocket for this channel
    console.log("received");
  },

  speak: function (message) {
    return this.perform("speak", { message: message });
  },
});

标签: javascriptruby-on-railsrubyactioncable

解决方案


推荐阅读