如何在凤凰框架中获取当前的url

Jer*_*Ges 9 elixir phoenix-framework

我想知道目前使用elixir/phoenix框架的网址,我怎么能得到这个?

编辑#1:

我的nginx配置文件:

server {
        client_max_body_size 100M;

        listen  80;

        server_name *.babysittingbordeaux.dev *.babysittingparis.dev

        access_log  /usr/local/var/log/nginx/baby-access.log;
        error_log   /usr/local/var/log/nginx/baby-error.log;


        location / {
            proxy_pass http://127.0.0.1:4000;
        }
}
Run Code Online (Sandbox Code Playgroud)

码:

Atom.to_string(conn.scheme) <> "://" <> (Enum.into(conn.req_headers, %{}) |> Map.get("host")) <> conn.request_path
Run Code Online (Sandbox Code Playgroud)

那个例子返回http://127.0.0.1:4000/,我想得到http://www.babysittingbordeaux.dev/

我正处于开发模式.

ven*_*laf 7

如果您只对请求路径感兴趣,可以使用conn.request_path其中包含的值"/users/1".

要获取包含您可以使用的主机的URL

MyApp.Router.Helpers.url(conn) <> conn.request_path
Run Code Online (Sandbox Code Playgroud)

这会返回一个结果"http://localhost:4000/users/1".


小智 7

您可以使用Phoenix.Controller.current_url/1

current_url(conn)
Run Code Online (Sandbox Code Playgroud)

端点配置将定义 URL:

config :my_app_web, MyAppWeb.Endpoint, url: [host: "example.com"]
Run Code Online (Sandbox Code Playgroud)


ste*_*n_m 4

我不确定哪种方法是最好的。

但也许里面有类似这样的插图IndexController

  def index(conn, params) do

    url_with_port = Atom.to_string(conn.scheme) <> "://" <>
                    conn.host <> ":" <> Integer.to_string(conn.port) <>
                    conn.request_path

    url =  Atom.to_string(conn.scheme) <> "://" <>
            conn.host <>
            conn.request_path

    url_phoenix_helper = Tester.Router.Helpers.index_url(conn, :index, params["path"]) # <-- This assumes it is the IndexController which maps to index_url/3

    url_from_endpoint_config = Atom.to_string(conn.scheme) <> "://" <>
                               Application.get_env(:my_app, MyApp.Endpoint)[:url][:host]  <>
                               conn.request_path

url_from_host_header =  Atom.to_string(conn.scheme) <> "://" <> 
                        (Enum.into(conn.req_headers, %{}) |> Map.get("host")) <> 
                        conn.request_path

    text = ~s"""

      url_with_port :: #{url_with_port}

      url :: #{url}

      url_phoenix_helper :: #{url_phoenix_helper}

      url_from_endpoint_config :: #{url_from_endpoint_config}

      url_from_host_header :: #{url_from_host_header}
    """

    text(conn, text)
  end
Run Code Online (Sandbox Code Playgroud)