gpt4 book ai didi

ruby-on-rails - 将 ActionCable 连接到不同的主机

转载 作者:行者123 更新时间:2023-12-02 10:57:56 24 4
gpt4 key购买 nike

我正在运行一个 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 中有一个简单的基本 channel 类,其中包含以下内容:

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 方面,我正在使用 ember-cable 包。我通过使用以下内容扩展 Controller 类来在前端设置我的消费者:

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 应用程序中绝对没有记录任何内容。我还需要设置什么才能跨域进行可操作的工作吗?你知道 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

关于ruby-on-rails - 将 ActionCable 连接到不同的主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40205467/

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