路由到 phoenix-framework 中的静态页面
Route to a static page in phoenix-framework
我想 运行 一个 angularJS 前端和我网站的 phoenix 后端。我希望我的根路由将用户定向到包含我的 angular 客户端的静态目录中的预构建页面,然后使用 phoenix 到 运行 API。我过去在 rails 上通过 ruby 通过这样的路由匹配来完成此操作:
get '/', to: redirect('/foobar.html')
有没有办法用 phoenix 做类似的事情?
现在还没有。您需要创建一个控制器,然后在控制器中:
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
我想 运行 一个 angularJS 前端和我网站的 phoenix 后端。我希望我的根路由将用户定向到包含我的 angular 客户端的静态目录中的预构建页面,然后使用 phoenix 到 运行 API。我过去在 rails 上通过 ruby 通过这样的路由匹配来完成此操作:
get '/', to: redirect('/foobar.html')
有没有办法用 phoenix 做类似的事情?
现在还没有。您需要创建一个控制器,然后在控制器中:
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