如何将我的 Ngrok 隧道动态添加到 Rails 6 中的 config.hosts?

How do I dynamically add my Ngrok tunnel to config.hosts in Rails 6?

我试图在 config.hosts 中将我的 ngrok 隧道主机名列入白名单,但每次我启动 Ngrok 时它都会改变。有没有办法获取我的 Ngrok 隧道的 public url,这样我就不必使用 hosts.clear

Ngrok 有一个内置的 JSON API,可以在 localhost:4040/api/tunnels 上找到。

# lib/ngrok_client.rb
module NgrokClient
  def self.tunnels
    response = Net::HTTP.get(URI('http://localhost:4040/api/tunnels'))
    begin
      JSON.parse(response).dig("tunnels")
    rescue JSON::ParserError => e
      Rails.logger.error %q{
        Failed to parse reponse from Ngroks internal API. Are you sure its running?
      }
    end
  end
  def self.public_urls
    tunnels.select do |h|
      # TODO - don't hardcode the host name
      h.dig("config", "addr") == "http://localhost:3000"
    end.map { |h| URI(h["public_url"]).hostname }.uniq
  end
end
# config/environments/development.rb
Rails.application.configure do
  # ...
  require 'ngrok_client'
  config.hosts += NgrokClient.public_urls
end

还有 ngrok-tunnel gem 可用于从中间件层启动 ngrok 作为一个不那么hacky的灵魂。

只需像这样配置config/environments/development.rb

Rails.application.configure do

  ...

  config.hosts << '.ngrok.io'
end

这将允许来自 ngrok.io.

的任何子域的请求

对我不起作用 (Rails 6) 但正则表达式对我有用。

config.hosts << %r{.+\.ngrok.io$}