Stephen
Stephen

Reputation: 3982

What's the correct way to respond to error page in a POST action without redirect in Phoenix?

I think it's a basic situation. I have a POST action, and I want to respond a 403 status and show the error page.

def signup(conn, params) do
  ...
  conn
  |> Plug.Conn.send_resp(:forbidden, "Forbidden")
  |> Plug.Conn.halt()
end

However, it will return the 403 but not render the error page. Instead, it throw Failed to load resource: the server responded with a status of 403 () in browser and download a weird signup.dms file.

I have an designed 403.html.eex, does anyone know how to show it correctly?

Upvotes: 1

Views: 620

Answers (2)

Stephen
Stephen

Reputation: 3982

The reason to download a *.dms file is that I didn't set the Content-Type for the response.

def signup(conn, params) do
  ...
  conn
  |> Plug.Conn.update_resp_header("content-type", "text/plain", &(&1 <> "; charset=utf-8"))
  |> Plug.Conn.send_resp(:forbidden, "Forbidden")
  |> Plug.Conn.halt()
end

Upvotes: 1

Paweł Obrok
Paweł Obrok

Reputation: 23164

You need to render your template before you halt. It could look something like this:

conn
|> put_status(:forbidden)
|> put_view(MyApp.ErrorView)
|> render("403.html")
|> halt()

In this case you would need to create MyApp.ErrorView and create 403.html.eex in templates/error.

Upvotes: 0

Related Questions