HTTPoison 请求 CaseClauseError:没有与 JSON 负载匹配的 case 子句

问题描述 投票:0回答:2

我尝试使用 HTTPoison 发出请求时遇到以下 CaseClauseError 消息:

20:13:10.697 [error] #PID<0.2628.0> running Api.Endpoint (connection #PID<0.2608.0>, stream id 2) terminated
Server: dev.company.com:80 (http)
Request: POST /an/endpoint
** (exit) an exception was raised:
    ** (CaseClauseError) no case clause matching: %{entity: %{some: "asdfasdf", parameters: "qwerqwer"}
        (hackney 1.18.1) /home/circleci/project/deps/hackney/src/hackney_request.erl:322: :hackney_request.handle_body/4
        (hackney 1.18.1) /home/circleci/project/deps/hackney/src/hackney_request.erl:87: :hackney_request.perform/2
        (hackney 1.18.1) /home/circleci/project/deps/hackney/src/hackney.erl:378: :hackney.send_request/2
        (httpoison 1.8.0) lib/httpoison/base.ex:846: HTTPoison.Base.request/6
        (web_api 0.1.0) lib/web_api/request.ex:84: WebApi.Request.entity/6
        (web_api 0.1.0) lib/web_api/request.ex:37: anonymous fn/5 in WebApi.Request.request/4
        (elixir 1.11.4) lib/enum.ex:1411: Enum."-map/2-lists^map/1-0-"/2
        (web_api 0.1.0) lib/web_api/request.ex:36: WebApi.Request.request/4

代码看起来像这样:

body = %{entity: %{some: "asdfasdf", parameters: "qwerqwer"}}

HTTPoison.request(
   method,
   uri,
   body,
   headers,
   timeout: 30000,
   recv_timeout: 30000
)

而且有点不清楚如何解决。

elixir httpoison
2个回答
0
投票

我只需要确保请求正文首先被字符串化:

body = if is_nil(body), do: nil, else: Jason.encode!(body)

(这确实有道理,HTTP 客户端不应该选择 JSON 编码。)


0
投票

您应该做的第一件事是确保请求正文是一个字符串,为此您可以在项目中添加以下依赖项:

{:jason, "~> 1.4"}

将依赖项下载到您的项目中:

mix deps.get

然后您可以将将地图转换为字符串的函数应用于您的身体:

body = %{entity: %{some: "asdfasdf", parameters: "qwerqwer"}} |> Jason.encode!()

就是这样,希望这个答案对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.