我想为我的网站运行一个带有 phoenix 后端的 angularJS 前端。我希望我的根路由将用户引导到包含我的角度客户端的静态目录中的预构建页面,然后使用 phoenix 运行 API。我过去通过这样的路线匹配使用 ruby on rails 做到了这一点:
get '/', to: redirect('/foobar.html')
有没有办法用凤凰做类似的事情?
我想为我的网站运行一个带有 phoenix 后端的 angularJS 前端。我希望我的根路由将用户引导到包含我的角度客户端的静态目录中的预构建页面,然后使用 phoenix 运行 API。我过去通过这样的路线匹配使用 ruby on rails 做到了这一点:
get '/', to: redirect('/foobar.html')
有没有办法用凤凰做类似的事情?
不是现在。您需要创建一个控制器,然后在控制器中:
defmodule MyApp.RootController do
use MyApp.Web, :controller
plug :action
def index(conn, _params) do
redirect conn, to: "/foobar.html"
end
end
在生产中,许多人在他们的应用程序中使用 nginx 或其他服务器,这些服务器应该处理静态资产。可以使用位置规则来查找索引,例如:
location / {
try_files $uri $uri/index.html @proxy;
}
否则,这是一个将请求映射到 index.html 的根路径的解决方案,它带有一个简短的功能插件,可以在endpoint.ex
不涉及控制器的情况下添加到您的:
def redirect_index(conn = %Plug.Conn{path_info: []}, _opts) do
%Plug.Conn{conn | path_info: ["index.html"]}
end
def redirect_index(conn, _opts) do
conn
end
plug :redirect_index
# This is Phoenix's standard configuration of Plug.Static with
# index.html added.
plug Plug.Static,
at: "/", from: :phoenix_elm_starter_template, gzip: false,
only: ~w(css fonts index.html images js favicon.ico robots.txt)
根据 Jose 的回答,我会对其进行一些修改,以便它index.html
直接为文件提供服务,而不是发送3xx
HTTP 响应。
defmodule MyApp.RootController do
use MyApp.Web, :controller
plug :action
def index(conn, _params) do
conn
|> put_resp_header("content-type", "text/html; charset=utf-8")
|> Plug.Conn.send_file(200, "priv/static/index.html")
end
end