gpt4 book ai didi

javascript - Rails 的 ActionCable 服务器端使用参数订阅

转载 作者:行者123 更新时间:2023-12-03 00:40:55 25 4
gpt4 key购买 nike

我正在使用 Ruby on Rails 作为后端构建 REST API。该 API 由 VueJS 前端使用。我没有使用Rails的前端,前端是完全独立的。

我已经使用 ActionCable 建立了 WebSocket 连接,但我很难将参数发送到订阅。

我有以下 ruby channel :

class WorkChannel < ApplicationCable::Channel
def subscribed
stream_from "works-#{params[:creator_id]}"
end
end

在我的 JavaScript 前端中,我使用以下代码订阅 channel :

const msg = {
command: 'subscribe',
identifier: JSON.stringify({
channel: 'WorkChannel',
}),
};
socket.send(JSON.stringify(msg));

如果我删除 stream_from 中的变量,则订阅成功。部分。

在我读过的所有指南和教程中,我只找到一个解释如何在不使用 Rails 前端方法的情况下与 ActionCable 进行通信。请参阅here获取完整指南。

但是,本指南不会将数据发送到订阅,我在文档中找不到它。

我需要发送以模拟 App.cable.subscriptions.create({channel: 'WorkChannel',
creator_id: 1 }
行为的对象的 JSON 语法是什么? ?

我尝试了不同的语法,但没有一个有效:

const msg = {
command: 'subscribe',
identifier: JSON.stringify({
channel: 'WorkChannel',
}),
creator_id: 1,
};

或者

const msg = {
command: 'subscribe',
identifier: JSON.stringify({
channel: 'WorkChannel',
creator_id: 1,
}),
};

甚至

const msg = {
command: 'subscribe',
identifier: JSON.stringify({
channel: 'WorkChannel',
}),
data: {
creator_id: 1,
},
};

最佳答案

您不想将用户 ID 作为参数发送,它可能会被利用。想象一下,用户暂停 js 执行,更改 user_id 并恢复,他将收到发送给其他用户的消息。

我建议您尝试从登录用户获取当前用户 ID,例如 https://guides.rubyonrails.org/action_cable_overview.html#server-side-components

# app/channels/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

正确的当前用户检测可能会根据您使用的身份验证系统而变化,如果您使用设计,您可能需要像这样从warden获取用户:https://stackoverflow.com/a/38702351/1430810

关于javascript - Rails 的 ActionCable 服务器端使用参数订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com