Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting raw HTTP request body in Phoenix

I've followed this issue to get the raw body from a POST in my controller but the body only shows up if the encoding is set to application/x-www-form-urlencoded. When I test with curl I can read the POST body but the body shows up empty when the encoding is set to text/xml. In my router.ex I have:

pipeline :api do
  plug :accepts, ["xml"]
end

In my controller I have:

def parse(conn, params) do
  xml = conn.private[:raw_body]
  Logger.debug(xml)
  text conn, xml
end

In endpoint.ex:

def copy_req_body(conn, _) do
  Plug.Conn.put_private(conn, :copy_raw_body, true)
end

plug :copy_req_body

I'm new to Phoenix and Elixir so I'm not sure how to debug this. Why does the encoding of the HTTP request make a difference to the reading of the raw body data? My application needs to accept text/xml and read the request body as a string.

like image 412
Reed G. Law Avatar asked Dec 19 '22 18:12

Reed G. Law


1 Answers

Pretty simple way. Not sure if it's "wrong" or not though.

defmodule YourApp.YourController do
  use YourApp.Web, :controller

  def receive_obm(conn, params) do
    {:ok, body, _conn} = Plug.Conn.read_body(conn)

    IO.inspect(body)
  end
end
like image 155
JustGage Avatar answered Dec 30 '22 04:12

JustGage