在我的 Controller 的 update(conn, params) Action 中,如何取出 PUT 请求传入的 JSON 主体?
我将这些值视为 params 中的映射,但其中插入了“id”。如果我传递一个“id”,它就会被覆盖。原来的 body 可能在 conn 的某个地方,但我不知道你是怎么找到的。
最佳答案
您可以使用 body_params
在 Plug.Conn结构。
例如
#PUT /users/1
{"user": {"name": "lol"}, "id": 7}
params["id"]
将是“1”body_params["id"]
将是 7 希望这对你有用。
因为你只能read_body/2有一次,访问请求主体会更复杂一些。您将需要绕过
Plug.Parsers
在您的 Endpoint
对于您的请求并手动阅读正文。从插件文档:
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.
关于elixir - 如何从连接中获取请求正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34165697/