将用户添加到 REST 服务时出现凤凰城错误



我打了这个电话:

curl -X POST -H "Content-Type: application/json" -d '{
  "user": {
    "email": "leo.hetsch@testapp.com",
    "first_name": "Léo",
    "last_name": "Hetsch",
    "password": "notsosecure",
"username": "test1"
  }
}' "http://localhost:4000/api/users"

在服务器上,我得到:

[info] POST /api/users
[debug] Processing by VirtualTeams.UserController.create/2
  Parameters: %{"user" => %{"email" => "leo.hetsch@testapp.com", "first_name" => "Léo", "last_name" => "Hetsch", "password" => "[FILTERED]", "username" => "test1"}}
  Pipelines: [:api]

这是我的用户.ex文件中:

  schema "users" do
    field :email, :string
    field :password, :string
    field :first_name, :string
    field :last_name, :string
    field :api_token, :string
    field :username, :string
    timestamps()
  end
  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \ %{}) do
    struct
    |> cast(params, [:email, :password, :first_name, :last_name, :api_token, :username])
    |> validate_required([:email, :password, :first_name, :last_name, :api_token, :username])
    |> unique_constraint(:email)
    |> unique_constraint(:username)
  end
  def create(params) do
  changeset(%VirtualTeams.User{}, params)
  |> put_change(:password, hashed_password(params["password"]))
  |> put_change(:api_token, :base64.encode(:crypto.strong_rand_bytes(24)))
  |> VirtualTeams.Repo.insert()
end
defp hashed_password(password) do
  Comeonin.Pbkdf2.hashpwsalt(password)
end

只是为了验证我做到了:

mix ecto.migrate
00:40:35.074 [info]  Already up

为什么我会收到错误?

更新:忘记错误:

{"error":"error creating user"}

在我的控制器中,我有以下代码,其中有错误:

def create(conn, %{"user" => user_params}) do
    case User.create(user_params) do
      {:ok, user} ->
        conn
        |> put_status(:created)
        |> render("user.json", user: user)
      {:error, changeset} ->
        conn
        |> put_status(:bad_request)
        |> json(%{error: "error creating user"})
    end

问题似乎是changeset/2需要:api_token,但不存在于请求的参数中。

通常,查看 {:error, changeset} 中的changeset(在本例中由 create/1 返回(以了解哪些验证失败很有用。

最新更新