【问题标题】:How to forcefully redirect a user to a certain page properly?如何正确强制将用户重定向到某个页面?
【发布时间】:2019-11-18 16:11:49
【问题描述】:

如果满足“some_condition”,我想将用户重定向到某个页面。例如,如果根本没有创建文章,则用户必须创建文章。重定向必须发生在其中的所有控制器和操作中。

我有一个插头:

defmodule P1 do
  alias Plug.Conn

  def init(opts), do: opts

  def call(conn, opts) do
    if some_condition do

      Phoenix.Controller.redirect(conn, to: MyApp.Router.Helpers.article_path(conn, :new))
      |> Plug.Conn.halt()
    end
  end
end

一个问题是

a) 它将所有请求重定向到“article_path/new”,包括对 js、css 等文件的请求。也就是说,它会在一条路线上连续发生多次。而不是我想要的一个重定向。

b) 页面不会被渲染。当我以这种方式重定向用户时,它将显示为一个空白页面

如何解决这个问题?

【问题讨论】:

    标签: elixir phoenix-framework


    【解决方案1】:

    您应该为不同类型的内容定义different pipelines,并仅在其所属的位置包含此插件。

    有点像

    pipeline :authenticate do
      plug :accepts, ["html"]
      plug :fetch_session
      plug :fetch_flash
      plug :protect_from_forgery
      plug :put_secure_browser_headers
      plug :p1 # yours one
    end
    
    scope "/app", AppWeb do
      pipe_through :authenticate
    
      get "/", ...
      ...
    end
    

    【讨论】:

    • 这不起作用,因为资产仍将通过:authenticate 提供服务,这将导致我的插件模块P1 多次命中。和以前一样
    • 通过:assets 提供资产,我不明白这个问题。
    • 回到我最初的问题。在我的问题中,没有什么像 authenticate 甚至没有类似的东西。您的解决方案仍然不适用于我的情况。这是always redirect to "add article" if conditionNNN
    • 也就是说,在实现方面我的情况不同
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    相关资源
    最近更新 更多