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.
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 7Hope 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.
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
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