2016-06-09 57 views
7

我想知道elixir/phoenix框架中的当前网址,我该如何获取?如何获取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; 
     } 
} 

代码:

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

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

算我一个 开发模式。

+2

你可以保留原来的标题在nginx的代理服务器。 '''location/{proxy_pass http://127.0.0.1:4000; proxy_set_header主机$主机; }''' –

+0

但我认为如果你在生产模式下运行,其他方法之一将工作。 –

+0

Dude你是最好的,它的工作!谢谢 –

回答

3

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

但也许像这样的内容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 
+0

那么对于主机我得到比“nginx”网址127.0.0.1,是不可能获得该数据? –

+0

你是在'dev'模式还是'prod'模式下运行你的服务器?我想上面的选项之一应该在'prod'模式下工作? –

+1

如果这些都不起作用,您可以从请求头获取主机。 '''Atom.to_string(conn.scheme)<>“://”<> (Enum.into(conn.req_headers,%{})|> Map.get(“host”))<> conn。 request_path'''But我不认为这是一个很好的方法来做到这一点。使用凤凰助手可能是在生产模式下运行应用程序的方式。请参阅'config/prod.exs' –

7

如果你只关心你可以使用conn.request_path持有像"https://stackoverflow.com/users/1"值请求路径。

要获得包括主机URL,你可以使用

MyApp.Router.Helpers.url(conn) <> conn.request_path 

这将返回象"http://localhost:4000/users/1"结果。

+1

我不想localhost:4000,我想要我在Nginx中配置的域名。合理 ? –

+0

'conn.request_path'只返回没有查询字符串的路径,所以它不是完整的甚至是相对的URL。 –