简体   繁体   English

Phoenix 中的静态 HTML 页面

[英]Static HTML page in Phoenix

I'm trying to build a JSON backend for Elm.我正在尝试为 Elm 构建一个 JSON 后端。 I only want to serve one page - elm.html, one js file - Main.js - and one css file.我只想提供一页 - elm.html,一个 js 文件 - Main.js - 和一个 css 文件。

I tried following these instructions but there is not enough there to help a complete newbie like me.我尝试按照这些说明进行操作,但不足以帮助像我这样的新手。

So now I have router.ex所以现在我有了 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还有我在web/staticpriv/static

But when I surf to /elm I get但是当我冲浪到 /elm 我得到

no route found for GET /elm.html (JwtExample.Router)没有找到 GET /elm.html 的路由(JwtExample.Router)

OK, so based on psantos answer, I needed to change lib/endpoint.ex to read好的,所以根据 psantos 的回答,我需要更改 lib/endpoint.ex 以读取

  plug Plug.Static,
    at: "/", from: :jwt_example, gzip: false,
    only: ~w(css fonts images js favicon.ico robots.txt elm.html)

Here's a solution that also servers the static page for requests to the root url, ie https://myapp.test/ :这是一个解决方案,它也为对根 url 的请求提供静态页面,即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.这是一个解决方案,它使用一个简短的功能插件将请求映射到 index.html 的根路径,该插件可以添加到您的endpoint.ex而不涉及控制器。 It works by defining a short Plug function to change the requested path.它通过定义一个简短的 Plug 函数来改变请求的路径。 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.请注意,在生产中,您通常会在应用程序服务器层处理静态资产,可能根本不会影响 Phoenix。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM