Phoenix LiveView form_for 在 POST 引发 NoRouteError

Phoenix LiveView form_for raising NoRouteError at POST

所以我正在尝试制作一个 phoenix 实时取景应用程序,但当我试图将其实施到我现有的项目中时遇到了一个问题。我使用 phoenix.html 提供的 form_for 创建了一个表单,它在我的实时套接字上向服务器发出 post 请求。我不认为这不应该发生,因为我成功地完成了演示并且它允许我 post 到实时视图。这是错误:

[debug] ** (Phoenix.Router.NoRouteError) no route found for POST /test_live/1 (OkayfivePhxWeb.Router)
(okayfive_phx 0.1.0) lib/phoenix/router.ex:330: OkayfivePhxWeb.Router.call/2
(okayfive_phx 0.1.0) lib/okayfive_phx_web/endpoint.ex:1: OkayfivePhxWeb.Endpoint.plug_builder_call/2
(okayfive_phx 0.1.0) lib/plug/debugger.ex:130: OkayfivePhxWeb.Endpoint."call (overridable 3)"/2
(okayfive_phx 0.1.0) lib/okayfive_phx_web/endpoint.ex:1: OkayfivePhxWeb.Endpoint.call/2
(phoenix 1.4.16) lib/phoenix/endpoint/cowboy2_handler.ex:42: Phoenix.Endpoint.Cowboy2Handler.init/4
(cowboy 2.7.0) /mnt/c/Users/oriont/dev/okayfive_phx/deps/cowboy/src/cowboy_handler.erl:41: :cowboy_handler.execute/2
(cowboy 2.7.0) /mnt/c/Users/oriont/dev/okayfive_phx/deps/cowboy/src/cowboy_stream_h.erl:320: :cowboy_stream_h.execute/3
(cowboy 2.7.0) /mnt/c/Users/oriont/dev/okayfive_phx/deps/cowboy/src/cowboy_stream_h.erl:302: :cowboy_stream_h.request_process/3
(stdlib 3.11.2) proc_lib.erl:249: :proc_lib.init_p_do_apply/3

这里是现场控制器:(test_live.ex)

defmodule OkayfivePhxWeb.TestLive do
  use Phoenix.LiveView

  alias OkayfivePhx.Quizzes

  def mount(_params, _session, socket) do
    {:ok, assign(socket, count: 0)}
  end

  def handle_params(%{"id" => id}, _url, socket) do
    {:noreply,
     assign(socket, %{
       user: id,
       changeset: Quizzes.change_student_answer(%Quizzes.StudentAnswer{})
     })}
  end

  def render(assigns), do: OkayfivePhxWeb.QuizView.render("test.html", assigns)

  def handle_event("save", %{"user" => _user_params}, socket) do
    IO.inspect("GET SAVED ON")

    {:noreply, socket}
  end
end

这里是 test.html.leex:

<%= f = form_for @changeset, "#", [phx_submit: :save, phx_hook: "SavedForm"] %>

  <%= label f, :answer %>
  <%= text_input f, :answer, phx_debounce: "blur" %>
  <%= error_tag f, :answer %>

  <div>
    <%= submit "Save", phx_disable_with: "Saving..." %>
  </div>
</form>

所以我尝试做其他事情,这是一个只使用 html 和属性的表单:

<form phx-change="validate" phx-submit="save">
  <input type="text" name="user[email]" phx-debounce="blur"/>
  <input type="text" name="user[username]" phx-debounce="2000"/>
  <input type="submit" value="Submit">
</form>

令我惊讶的是,此表单不会引发无路由错误。但是,它仍然没有调用我在 test_live.ex

中定义的 handle_event 函数

这是我的路由器:

pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_live_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

scope "/", OkayfivePhxWeb do
    pipe_through :browser
...
    live "/test_live/:id", TestLive
...

  end

感谢任何帮助。谢谢!

其实我也想通了,现在觉得自己好傻。原因是我没有使用带有实时视图渲染的布局,这意味着:

<%= @inner_content %>

确保这在您的布局中,并且布局实际有效。

否则,您的表单将发出 post 请求,而不是通过网络套接字。