Reputation: 21037
I'm trying to build a JSON backend for Elm. I only want to serve one page - elm.html, one js file - Main.js - and one css file.
I tried following these instructions but there is not enough there to help a complete newbie like me.
So now I have router.ex
scope "/", JwtExample do
pipe_through :browser # Use the default browser stack
get "/elm", RootController, :index
get "/", PageController, :index
end
# Other scopes may use custom stacks.
scope "/api", JwtExample do
pipe_through :api
resources "/users", UserController, except: [:new, :edit]
end
This controller
defmodule JwtExample.RootController do
use JwtExample.Web, :controller
plug :action
def index(conn, _params) do
redirect conn, to: "/elm.html"
end
end
And my files in web/static
and priv/static
But when I surf to /elm I get
no route found for GET /elm.html (JwtExample.Router)
Upvotes: 2
Views: 1770
Reputation: 16394
Here's a solution that also servers the static page for requests to the root url, i. e. https://myapp.test/:
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. It works by defining a short Plug function to change the requested path. My hope is that it's a little faster to to it in the endpoint compared to doing it in a controller.
def redirect_index(conn = %Plug.Conn{path_info: []}, _opts) do
%Plug.Conn{conn | path_info: ["elm.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 elm.html images js favicon.ico robots.txt)
Note that in production, you would usually deal with static assets at application server layer, possibly not hitting Phoenix at all.
Upvotes: 1
Reputation: 21037
OK, so based on psantos answer, I needed to change lib/endpoint.ex to read
plug Plug.Static,
at: "/", from: :jwt_example, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt elm.html)
Upvotes: 1