Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get request body in phoenix?

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"
like image 251
Uri Agassi Avatar asked Mar 20 '23 09:03

Uri Agassi


1 Answers

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.

like image 169
Rachel Bowyer Avatar answered Mar 28 '23 21:03

Rachel Bowyer