javascript - 【Rails6】Action Cable don't GET '/action'
问题描述
我尝试在 Rails6 上使用 Action Cable。
我可以像下面这样从控制器广播,但无法在浏览器上接收。
ActionCable.server.broadcast "message_channel", message: message.content
因为在本地服务器日志上没有 GET /cable,我猜这是因为我在浏览器上运行的应用程序没有正确初始化 Action Cable。请告诉我如何初始化动作电缆。
我做了什么
- 配置/路由.rb
mount ActionCable.server => '/cable'
- 配置/环境/development.rb
config.action_cable.url = "ws:localhost:3000/cable"
config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/]
ActionCable.server.config.disable_request_forgery_protection = true
- 应用程序/频道/application_cable/channel.rb
module ApplicationCable
class Channel < ActionCable::Channel::Base
end
end
- 应用程序/频道/application_cable/connection.rb
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
- 应用程序/频道/message_channel.rb
class MessageChannel < ApplicationCable::Channel
def subscribed
stream_from "message_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
- 应用程序/javascript/频道/customer.js
// 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();
- 应用程序/javascript/channels/message_channel.js
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 });
},
});
解决方案
推荐阅读
- rabbitmq - 如果已经存在,RabbitMQ 是否创建队列/交换?
- spring-boot - 结合 oauth2+jwt 配置多个身份验证提供程序
- node.js - 在此示例中,如何使用 docker-compose 允许 2 个容器正确共享 .sock 文件?
- flutter - Flutter ButtonBar 儿童尺寸
- c# - 使用 svcutil 从 xsd 生成 DataContract 的问题
- python - 根据特定键合并字典列表
- junit - 在 JUnit 的 @After 中清理特定的测试用例方法
- ios - Mac 能识别 iPhone,Xcode 不能
- html - Twitter 时间线未加载
- firebase - 我可以使用 StreamBuilder 在 Firestore 中收听单个文档吗?