Handle incoming post json with phoenix

雨燕双飞 提交于 2019-12-08 15:56:23

问题


I'd like to handle an incoming POST with application/json content type. I am simply trying to return posted JSON as response to test like this:

WebhookController controller

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

def handle(conn, params) do
  {:ok, body, conn} = Plug.Conn.read_body(conn)    
  json(conn, %{body: body})
end

router.ex

scope "/webhook", MyApp do
  pipe_through :api

  post "/handle", WebhookController, :handle
end

If the incoming post has content type application/json, then body is empty. If the content type is text or text/plain, then body has the content.

What is the right way to parse incoming application/json request body?

I am using Phoenix 1.2


回答1:


When the Content-Type of the request is application/json, Plug parses the request body and Phoenix passes it as params to the controller action, so params should contain what you want and you don't need to read the body and decode it yourself:

def handle(conn, params) do
  json(conn, %{body: params})
end
$ curl -XPOST -H 'Content-Type: application/json' --data-binary '{"foo": "bar"}' http://localhost:4000/handle
{"body":{"foo":"bar"}}


来源:https://stackoverflow.com/questions/41397527/handle-incoming-post-json-with-phoenix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!