Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the request body from a connection?

In the update(conn, params) action of my controller, how do I get out the JSON body passed in by the PUT request?

I see the values as a map in params, but with an "id" inserted into it. And if I pass an "id" it gets overwritten. The original body is probably somewhere in conn, but I don't know how you get to it.

like image 280
Matt Avatar asked Dec 08 '15 20:12

Matt


2 Answers

You can use body_params on the Plug.Conn struct.

e.g.

#PUT /users/1
{"user": {"name": "lol"}, "id": 7}
  • params["id"] will be "1"
  • body_params["id"] will be 7

Hope this works for you.

Since you can only read_body/2 once, accessing the request body is a little more involved. You will need to bypass Plug.Parsers in your Endpoint for your requests and read the body manually.

From the Plug docs:

If you need to access the body multiple times, it is your responsibility to store it. Finally keep in mind some plugs like Plug.Parsers may read the body, so the body may be unavailable after accessing such plugs.

like image 53
Gazler Avatar answered Sep 26 '22 17:09

Gazler


If folks come to this when using Plug, you're looking to use Plug.Parsers.

Specifically you can do the following in your router file:

  plug Plug.Parsers, parsers: [:json],
                     pass:  ["text/*"],
                     json_decoder: Poison
  plug :match
  plug :dispatch

  # ...

  post "/" do
    IO.puts inspect conn.body_params
  end
like image 42
Gowiem Avatar answered Sep 22 '22 17:09

Gowiem