Rails 5 ActionCable拒绝了未经授权的连接尝试

时间:2018-12-29 04:04:25

标签: ruby-on-rails-5 actioncable

在此处遵循Hartle教程:https://www.learnenough.com/action-cable-tutorial#sec-upgrading_to_action_cable

当我进入第4步时,添加ActionCable不会传输聊天消息,并且出现错误:

#include <mutex>

template<typename T>
struct my_lock {
    T &mtx;
    my_lock(T &t) : mtx{t} { lock(); }
    ~my_lock() { unlock(); }

    void lock() & { mtx.lock(); };
    void unlock() & { mtx.unlock(); };
};


std::mutex mtx;

int main()
{
    my_lock<std::mutex> {mtx}; // A 

    my_lock<std::mutex lck{mtx}; // B
}

以下是相关文件:

A

消息控制器:

B

room.coffee:

<!--script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.log('Error', err));
    }
</script-->

routes.rb:

User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ?  [["LIMIT", 1]]
An unauthorized connection attempt was rejected

参考分支在我的机器上可以正常工作,但是我的教程分支无法使用AC。

更新:

跳到本教程的第5部分,我添加了connection.rb,该内容在本教程的开始版本中是空白的,如下所示:

connection.rb:

room_channel.rb:

class RoomChannel < ApplicationCable::Channel
  def subscribed
    stream_from "room_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

广播似乎在一个方向上起作用。我有两个选项卡打开。但是只有一个可以广播消息。另一方面,控制台显示此错误:

  class MessagesController < ApplicationController
  before_action :logged_in_user
  before_action :get_messages

  def index
  end

  def create
    message = current_user.messages.build(message_params)
    if message.save
      ActionCable.server.broadcast 'room_channel',
                               message: render_message(message)
      message.mentions.each do |mention|
        ActionCable.server.broadcast "room_channel_user_#    {mention.id}",
                                     mention: true
      end
    end
  end

  private

    def get_messages
      @messages = Message.for_display
      @message  = current_user.messages.build
    end

    def message_params
      params.require(:message).permit(:content)
    end

    def render_message(message)
      render(partial: 'message', locals: { message: message })
    end
end

在日志中,使用上述connection.rb,对空用户的搜索就消失了,显示如下:

App.room = App.cable.subscriptions.create "RoomChannel",
  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) ->
    # Called when there's incoming data on the websocket for this     channel
    alert data.content

0 个答案:

没有答案