用凤凰处理传入的json帖子 [英] Handle incoming post json with phoenix
问题描述
我想处理具有application/json
内容类型的传入POST.我只是想返回已发布的JSON作为对测试的响应,如下所示:
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控制器
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
如果传入的帖子的内容类型为application/json
,则正文为空.如果内容类型为text
或text/plain
,则正文具有内容.
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.
解析传入的application/json
请求正文的正确方法是什么?
What is the right way to parse incoming application/json
request body?
我正在使用Phoenix 1.2
I am using Phoenix 1.2
推荐答案
当请求的Content-Type为application/json
时,Plug解析请求主体,Phoenix将其作为params
传递给控制器动作,因此params
应该包含您想要的内容,而您无需自己阅读并自行解码:
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"}}
这篇关于用凤凰处理传入的json帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!