繁体   English   中英

将ActionCable连接到其他主机

[英]Connecting ActionCable to different host

我正在将Rails 5应用程序作为后端服务器运行,而将ember应用程序作为前端应用程序运行。 它们是托管在两个不同域上的两个单独的应用程序-例如backend.devfrontend.dev

rails应用程序在app/channels/application_cable/connection.rb中有一个简单的连接类,如下所示:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    def connect
      Rails.logger.debug("env: #{env.inspect}")
      Rails.logger.info("cookies.signed: #{cookies.signed.inspect}")
    end
  end
end

我在app/channels/application_cable/channel.rb有一个简单的基本频道类,内容如下:

module ApplicationCable
  class Channel < ActionCable::Channel::Base
  end
end

app/channels/events_channel.rb该类的单个实现:

class EventsChannel < ApplicationCable::Channel
  def subscribed
    Rails.logger.debug("env: #{env.inspect}")
    Rails.logger.info("cookies.signed: #{cookies.signed.inspect}")
    stream_from 'events'
  end
end

在余烬方面,我正在使用ember-cable软件包。 我通过使用以下扩展控制器类在前端设置了使用者:

cableService: Ember.inject.service('cable'),

setupConsumer: Ember.on('init', function() {
  let service = this.get('cableService');
  let consumer = service.createConsumer(`ws://backend.dev`);
  let channel = 'EventsChannel';

  consumer.subscriptions.create(channel, {
    disconnected() {
      Ember.debug(`${channel}#disconnected`);
    },

    connected() {
      Ember.debug(`${channel}#connected`);
    },

我相当确定我的使用者设置正确,因为当我将以下输出发送到js控制台时,我看到了一些调试输出:

DEBUG: EventsChannel#disconnected

但是,我也在控制台中也看到了一个奇怪的错误:

WebSocket connection to 'ws://backend.dev/' failed: Error during WebSocket handshake: Unexpected response code: 200

我不确定该如何处理响应代码错误,并且绝对没有任何东西记录在我的rails应用程序中。 我需要设置其他任何内容才能跨域进行Actioncable工作吗? 知道200响应代码在这里意味着什么吗?

尝试这个:

# routes.rb
Rails.application.routes.draw do
  # your code
  mount ActionCable.server => '/cable'
end

然后在您的应用中:

let consumer = service.createConsumer(`ws://backend.dev/cable`);

如果您遇到握手问题,则几乎没有解决方案:

  1. 检查您的前端应用程序是否与protocol 07或更高版本兼容。

  2. 检查您的网站是否位于config.action_cable.allowed_request_origins

  3. config.web_socket_server_url = 'ws://backend.dev/cable'到您的ENV cofig文件中。

  4. 您可以使用快速的“肮脏”黑客。 只需将以下内容添加到您的ENV cofig文件中:

     config.action_cable.disable_request_forgery_protection = true 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM