问题
Having server issues with an app in Rails 5.0.0.beta2 trying to use ActionCable.
Using localhost:3000 works fine, as that is what most of ActionCable defaults to. But if I try to run the rails server on port 3001, it gives me Request origin not allowed: http://localhost:3001
The ActionCable docs mention using something like ActionCable.server.config.allowed_request_origins = ['http://localhost:3001']
which does work for me if I put it in config.ru
But that seems like a really weird place to put it. I feel like it should be able to go in an initializer file, or my development.rb environment config file.
To further prove my point that it should be allowed to go in there, the setting ActionCable.server.config.disable_request_forgery_protection = true
works to ignore request origin, even when I include it in development.rb.
Why would ActionCable.server.config.disable_request_forgery_protection
work in development.rb, but ActionCable.server.config.allowed_request_origins
doesn't (but does work in config.ru)?
Not a pressing issue, since I have several options as a work around. I just want to know if I'm missing something obvious about how I imagine this should be working.
回答1:
You can put
Rails.application.config.action_cable.allowed_request_origins = ['http://localhost:3001']
in your development.rb
See https://github.com/rails/rails/tree/master/actioncable#allowed-request-origins for more informations
回答2:
From this answer, you can also add the following code to config/environments/development.rb
to allow requests from both http
and https
:
Rails.application.configure do
# ...
config.action_cable.allowed_request_origins = [%r{https?://\S+}]
end
config.action_cable.allowed_request_origins
accepts an array of strings or regular expressions as the documentation states:
Action Cable will only accept requests from specified origins, which are passed to the server config as an array. The origins can be instances of strings or regular expressions, against which a check for the match will be performed.
The regex listed below will match both http
and https
urls from any domain so be careful when using them. It is just a matter of preference which one to use.
[%r{https?://\S+}]
# Taken from this answer[%r{http[s]?://\S+}]
[%r{http://*}, %r{https://*}]
[/http:\/\/*/, /https:\/\/*/]
来源:https://stackoverflow.com/questions/35188892/request-origin-not-allowed-http-localhost3001-when-using-rails5-and-actionca