如何从连接中获取请求正文?

How do I get the request body from a connection?

在我的控制器的 update(conn, params) 操作中,如何取出 PUT 请求传入的 JSON 主体?

我将值视为参数中的映射,但其中插入了 "id"。如果我传递 "id" 它会被覆盖。原体可能在conn的某个地方,但我不知道你是怎么得到的。

您可以在 Plug.Conn 结构上使用 body_params

例如

#PUT /users/1
{"user": {"name": "lol"}, "id": 7}
  • params["id"] 将是“1”
  • body_params["id"] 将是 7

希望这对你有用。

由于您只能 read_body/2 一次,因此访问请求正文有点复杂。您需要绕过 Endpoint 中的 Plug.Parsers 来处理您的请求并手动阅读正文。

来自插件文档:

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.

如果人们在使用 Plug, you're looking to use Plug.Parsers 时想到这一点。

具体来说,您可以在路由器文件中执行以下操作:

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

  # ...

  post "/" do
    IO.puts inspect conn.body_params
  end