凤凰城:如何提供单页应用程序

时间:2016-05-31 18:53:42

标签: phoenix-framework

我想将Phoenix设置为静态index.html,无论发送到哪个路由,都不会更改URL,同时提供对非html资源的访问权限(.js,.css,.jpg ,...),因为我的SPA(在Elm中)会查看路线并找出要做的事情。

根据thisthis,我尝试了以下内容,但没有成功

endpoint.ex

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

router.ex

  scope "/", Api do
    pipe_through :browser # Use the default browser stack
    get "/*path", PageController, :index  # :elm
  end

PageController.ex

defmodule Api.PageController do
  use Api.Web, :controller

  plug :action  # Edit: now removed

  def index(conn, _params) do
    conn
    |> put_layout(false)
    |> render("index.html")
    # Edit: replaced 3 lines above by: html(conn, File.read!("priv/static/index.html"))
  end

  def elm(conn, _params) do
      redirect conn, to: "/index.html"
  end
end

使用:index我得到与Phoenix相关的(但不是标准的主页)页面和控制台错误(Plug.Conn.AlreadySentError) the response was already sent,而:elm我最终得到/index.html并且丢失了路由信息。

1 个答案:

答案 0 :(得分:2)

only: ~w(... index.html)

conn
|> put_layout(false)
|> render("index.html")

您似乎尝试渲染不起作用的静态index.htmlput_layout/2禁用或更改包装器布局。 render/2设置要用作内容的文件。默认此文件位于/web/templates/MODULE/

您可以使用Phoenix.Controller.html/2功能发送自定义html内容。使用File.read!/2读取文件并将内容发送给客户端。

def index(conn, _params) do
  html(conn, File.read!("priv/static/index.html"))
end

我不确定是否有其他清洁解决方案,但这应该有效。 希望这会有所帮助。

修改

通过从控制器中删除AlreadySentError来解决plug :action问题。它从版本0.14.0开始自动调用。

  

请参阅这些0.13.x to 0.14.0 upgrade instructions,以加快现有应用的速度。

     
      
  • 向后不兼容的更改      
        
    • [控制器] plug :action现在自动调用
    •   
  •