Request origin not allowed: http://localhost:3001 when using Rails5 and ActionCable
Asked Answered
M

3

43

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.

Melgar answered 3/2, 2016 at 22:21 Comment(0)
L
59

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

Lamppost answered 16/2, 2016 at 20:28 Comment(0)
H
7

For my flutter app, request origin was nil. So, needed to add nil in the list.

I have added this code in config/environments/development.rb, and it works!

config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/, /file:\/\/*/, 'file://', nil]
Hematuria answered 23/1, 2021 at 9:52 Comment(0)
B
5

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:\/\/*/]
Bentwood answered 27/11, 2018 at 18:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.