使用HTTPoison对Plug路由器发出的POST请求失败

时间:2018-11-02 18:49:32

标签: elixir cowboy plug

我正在尝试使用HTTPoison向plug路由器发出POST请求。我的GET请求成功,只有POST失败。我不确定问题是Plug还是HTTPoison:

# server.ex

defmodule MyServer do
  use Application
  use Plug.Router

  import Plug.Conn, only: [put_resp_header: 3, send_resp: 3]

  alias Plug.Adapters.Cowboy

  plug(:match)

  plug(Plug.Parsers,
    parsers: [:json],
    pass: ["*/*", "application/json", "text/plain"],
    json_decoder: Poison
  )

  plug(:dispatch)

  post "/myserver/url" do
    conn
    |> send_resp(200, Poison.encode!(%{}))
  end

  def start(_type, _args) do
    port = Application.get_env(:server, :cowboy_port, 8030)
    IO.puts("Started server on http://localhost:#{port}/")

    children = [
      Cowboy.child_spec(:http, __MODULE__, [], port: port)
    ]

    Supervisor.start_link(children, strategy: :one_for_one)
  end
end

和客户:

# client.ex

host = "http://localhost:8030"

host
|> Path.join("/myserver/url")
|> HTTPoison.post!(Poison.encode!(%{}))
|> IO.inspect()

我得到的响应是500。我不确定为什么,因为路由器中的路由配置为接受POST。有人知道我在做什么错吗?

更新

人们要求提供堆栈跟踪。没有一个。但这是500条回复:

..%HTTPoison.Response{
  body: "",
  headers: [
    {"server", "Cowboy"},
    {"date", "Fri, 02 Nov 2018 20:57:01 GMT"},
    {"content-length", "0"}
  ],
  request_url: "http://localhost:8030/myserver/url"
  status_code: 500
}

1 个答案:

答案 0 :(得分:-1)

问题出在这一行:

send_resp(200, Poison.encode!(stuff))

您尚未定义名为stuff的变量,因此它引发了一个异常,该异常返回了500 Internal Server Error