Hi everyone. I’m trying to fetch the body of a post request and I keep getting Plug.Conn.Unfetched
This is what I have in my route handler
import Plug.Conn
use Plug.Router
plug(Plug.Parsers,
parsers: [:json],
pass: ["text/*"],
json_decoder: Poison
)
plug(:match)
plug(:dispatch)
post "/login" do
with %{"email" => email, "password" => password} <- conn.body_params do
changeset= Login.changeset(%{
"email"=> email, "password" => password
})
case Login.execute(changeset) do
{:ok, lgn}->
conn
|> put_resp_content_type("application/json")
|> send_resp(
200,
Poison.encode!(%{data: lgn})
)
_->
conn
|> put_resp_content_type("application/json")
|> send_resp(
200,
Poison.encode!(%{error: "invalid login details"})
)
end
else
_ ->
conn
|> put_resp_content_type("application/json")
|> send_resp(
400,
Poison.encode!(%{error: "invalid input"})
)
end
end
I’m tying to run the test below and it keeps failing
test "trade username and password for access tokens and refresh tokens", t do
{:ok, resp_body} = HttpRequest.post("/api/auth/login", %{"email"=> t.user.email, "password"=> "NNNdnsfsndkn???234."})
IO.inspect(resp_body)
assert is_binary(resp_body["accessToken"])
assert is_binary(resp_body["refreshToken"])
end
HttpRequest is an test helper I wrote to send http request
defmodule Test.HttpRequest do
def post(path, body, opts \\ []) do
callers =
self()
|> :erlang.term_to_binary()
|> Base.encode16()
IO.inspect(body)
case :post
|> Finch.build(
"http://localhost:4001" <> path,
[{"content-type", "application/json"}, {"user-agent", callers}] ++ opts,
Jason.encode!(body)
)
|> Finch.request(HttpRequests) do
{:ok, %Finch.Response{body: body, status: 200}} ->
{:ok, Jason.decode!(body)}
x ->
x
end
end
end