问题
I want to run an angularJS front end with a phoenix backend for my site. I would like my root route to direct the user to a pre-built page in the static directory which contains my angular client and then use phoenix to run the API. I have done this in the past with ruby on rails by route matching like this:
get '/', to: redirect('/foobar.html')
Is there a way to do something similar with phoenix?
回答1:
Not right now. You need to create a controller and then in the controller:
defmodule MyApp.RootController do
use MyApp.Web, :controller
plug :action
def index(conn, _params) do
redirect conn, to: "/foobar.html"
end
end
回答2:
In production, many people use nginx or other servers in from of their app and these servers should handle static assets. Finding the index can be done with a location rule such as:
location / {
try_files $uri $uri/index.html @proxy;
}
Otherwise, here's a solution that maps a request to the root path to index.html with a short function plug that can be added to your endpoint.ex
without involving controllers:
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)
回答3:
From Jose's answer, I would modify it a little so it serves the index.html
file directly instead of sending a 3xx
HTTP response.
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
来源:https://stackoverflow.com/questions/29919143/route-to-a-static-page-in-phoenix-framework