【问题标题】:Request origin not allowed: http://localhost:3001 when using Rails5 and ActionCable不允许请求来源:使用 Rails5 和 ActionCable 时的 http://localhost:3001
【发布时间】:2016-05-13 08:22:37
【问题描述】:

Rails 5.0.0.beta2 中的应用程序在尝试使用 ActionCable 时遇到服务器问题。

使用 localhost:3000 可以正常工作,因为这是大多数 ActionCable 的默认设置。但是如果我尝试在端口 3001 上运行 rails 服务器,它会给我Request origin not allowed: http://localhost:3001

ActionCable 文档提到使用 ActionCable.server.config.allowed_request_origins = ['http://localhost:3001'] 之类的东西,如果我把它放在 config.ru 中,它对我有用

但这似乎是一个非常奇怪的地方。我觉得它应该可以放在初始化文件或我的 development.rb 环境配置文件中。

为了进一步证明我的观点应该允许进入,设置 ActionCable.server.config.disable_request_forgery_protection = true 可以忽略请求来源,即使我将其包含在 development.rb 中。

为什么ActionCable.server.config.disable_request_forgery_protection 可以在 development.rb 中工作,而 ActionCable.server.config.allowed_request_origins 不能(但在 config.ru 中可以)?

这不是一个紧迫的问题,因为我有几个选项可以解决。我只是想知道我是否遗漏了一些关于我认为这应该如何工作的明显内容。

【问题讨论】:

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


    【解决方案1】:

    你可以放 Rails.application.config.action_cable.allowed_request_origins = ['http://localhost:3001'] 在你的 development.rb 中

    更多信息请见https://github.com/rails/rails/tree/master/actioncable#allowed-request-origins

    【讨论】:

      【解决方案2】:

      this answer,您还可以将以下代码添加到config/environments/development.rb,以允许来自httphttps 的请求:

      Rails.application.configure do
        # ...
      
        config.action_cable.allowed_request_origins = [%r{https?://\S+}]
      end
      

      config.action_cable.allowed_request_origins 接受字符串数组或正则表达式作为documentation states

      Action Cable 将只接受来自指定来源的请求,即 作为数组传递给服务器配置。起源可以是 字符串或正则表达式的实例,对其进行检查 比赛将进行。

      下面列出的正则表达式将匹配来自任何域的httphttps url,因此在使用它们时要小心。使用哪一个只是偏好问题。

      • [%r{https?://\S+}] # 取自this answer
      • [%r{http[s]?://\S+}]
      • [%r{http://*}, %r{https://*}]
      • [/http:\/\/*/, /https:\/\/*/]

      【讨论】:

        【解决方案3】:

        对于我的颤振应用程序,请求来源为零。所以,需要在列表中添加nil

        我已经在config/environments/development.rb 中添加了这段代码,它可以工作了!

        config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/, /file:\/\/*/, 'file://', nil]
        

        【讨论】:

          猜你喜欢
          • 2013-03-28
          • 2013-04-09
          • 2012-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多