不允许请求源:使用 Rails5 和 ActionCable 时 http://localhost:3001



尝试使用ActionCable的Rails 5.0.0.beta2中遇到服务器问题。

使用 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 中确实有效)?

这不是一个紧迫的问题,因为我有几个选择作为解决方法。我只是想知道我是否错过了一些关于我想象这应该如何工作的明显的东西。

你可以把 Rails.application.config.action_cable.allowed_request_origins = ['http://localhost:3001']在您的开发中.rb

有关详细信息,请参阅 https://github.com/rails/rails/tree/master/actioncable#allowed-request-origins

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

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

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

从这个答案中,您还可以将以下代码添加到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接受字符串或正则表达式数组,如文档所述:

行动电缆将仅接受来自指定来源的请求,这些请求 作为数组传递给服务器配置。起源可以是 字符串或正则表达式的实例,根据这些实例检查 比赛将被执行。

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

  • [%r{https?://S+}] # 取自这个答案
  • [%r{http[s]?://S+}]
  • [%r{http://*}, %r{https://*}]
  • [/http://*/, /https://*/]

最新更新