用凤凰处理传入的json帖子 [英] Handle incoming post json with phoenix

查看:91
本文介绍了用凤凰处理传入的json帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想处理具有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,则正文为空.如果内容类型为texttext/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆