I'm trying to build a phoenix application, and I handle a POST request. I want to get the request body, and I can't seem to find any documentation on how to do it.
Doing some reverse engineering I got to the following code:
defmodule MyApp.Controllers.Pages do
  use Phoenix.Controller
  def post(conn) do
    {_, {_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, body, _, _, _, _, _, _}} = conn.adapter
    text conn, "#{inspect body}"
  end
end
with routing:
defmodule MyApp.Router do
  use Phoenix.Router
  post "/test", MyApp.Controllers.Pages, :post
end
There must be a better way, no?
Expected behavior:
curl -XPOST localhost:4000/test -d 'this is a test'
$ "this is a test"
I am using Phoenix version 0.6.1 and I was not able to get the approaches above to work. I have though found the following to work:
defmodule MyApp.MyController do
  use Phoenix.Controller
  plug :action 
  def login(conn, _params) do
    {:ok, data, _conn_details} = Plug.Conn.read_body(conn)
    # ...
  end
end
The request body is returned in data. Not sure if this is the "official" way to get the request body, but thought I would share it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With