频道在Chatrooms上挂起频道正在传输订阅确认,收到的(数据)未显示console.log

时间:2019-06-12 06:49:33

标签: coffeescript ruby-on-rails-5 actioncable

app/channels/application_cable/connection.rb:14
An unauthorized connection attempt was rejected
def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable'
    end

    protected

    def find_verified_user #line 12 No output from logger
      Rails.logger.debug env['warden'].user
      verified_user = User.find_by(id: cookies.signed['user.id'])
      if verified_user && cookies.signed['user.expires_at'] > Time.now
        verified_user
      else
        reject_unauthorized_connection
      end
    end

citing the two upvoted answers here:

Authenticating ActionCable connections

这里是文件,其中包含应成功从服务器上加载的消息中继作业接收的内容。

App.chatrooms = App.cable.subscriptions.create "ChatroomsChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    console.log(data)
    active_chatroom = $("[data-behavior='messages'][data-chatroom-id='#{data.chatroom_id}']").append("<div><strong>#{data.username}:</strong> #{data.message}</div>")
    if active_chatroom.length > 0
      active_chatroom.append("<div><strong>#{data.username}:</strong> #{data.body}</div>")
    else
      $("[data-behavior='chatroom-link'][data-chatroom-id='#{data.chatroom_id}']").css("font-weight", "bold")
    # Called when there's incoming data on the websocket for this channel

  send_message: (chatroom_id, body) ->
    @perform "send_message", {chatroom_id: chatroom_id, body: body}

服务器加载消息时,它将在消息中继作业中显示正确的消息。

这是文件的另一个咖啡脚本。

$(document).on 'turbolinks:load', ->
  $('#new_groupmessage').on 'keypress', (e) ->
    if e && e.keyCode == 13
      e.preventDefault()
      $(this).submit()
  $('#new_groupmessage').on "submit", (e) ->
    e.preventDefault()
    chatroom_id = $("[data-behavior='messages']").data("chatroom-id")
    body = $("#groupmessage_body")
    App.chatrooms.send_message(chatroom_id, body.val())
    body.val("")

就这样您可以看到html了:


<div data-behavior='messages' data-chatroom-id='<%= @chatroom.id %>' class=messages style="margin-left: 140px; border-left: 1px black solid; padding-left: 2px;">
    <% @chatroom.groupmessages.order(created_at: :desc).limit(100).reverse.each do |groupmessage| %>
        <%= render groupmessage %>
    <% end %>
</div>

<%= form_for [@chatroom, Groupmessage.new] do |f| %>
    <%= f.text_area :body, rows: 1, class: "form-control", autofocus: true %>
    <%= f.submit %>
<% end %>

非常简单的数据表单和显示。

class MessageRelayJob < ApplicationJob
  queue_as :default

  def perform(message)
    ActionCable.server.broadcast "chatrooms:#{message.chatroom.id}", {
      username: message.user.username,
      body: GroupmessagesController.render(message),
      chatroom_id: message.chatroom.id
    }
    # Do something later
  end
end

消息中继作业也很简洁。

控制台日志:

未经授权的连接尝试被拒绝

0 个答案:

没有答案