What is the equivalent of 'head :ok' from

2020-04-02 07:41发布

问题:

I want to return a response that has no content (merely headers) like this one

def show
  head :ok
end

回答1:

You can use Plug.Conn.send_resp/3 with empty body:

# 200 OK
send_resp(conn, 200, "")
send_resp(conn, :ok, "") # same as above
# 401 Unauthorized
send_resp(conn, 401, "")
send_resp(conn, :unauthorized, "") # same as above

send_resp can take the status (second argument) as an integer or one of the supported atoms mentioned here: https://hexdocs.pm/plug/Plug.Conn.Status.html#code/1.



回答2:

@dogbert answers was spot on. Additionally you can read up on relevant documentation from official phoenix guide. The relevant information - http://www.phoenixframework.org/docs/controllers#section-sending-responses-directly

...Let's say we want to send a response with a status of "201" and no body whatsoever. We can easily do that with the send_resp/3 function.

def index(conn, _params) do
  conn
  |> send_resp(201, "")
end