-1

I have been trying to post a new user to my sanity content lake using the sanity mutation but for almost a week now, I kept on getting same error. This is the error:

http://localhost:3000/api/register net::ERR_ABORTED 500 (Internal Server Error)

and

Uncaught (in promise) Error: Failed to submit form
at handleSubmit

This this the submit function:

const Register = () => {
  const [firstName, setFirstName] = useState("");
  const [surname, setSurname] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const handleSubmit = async (e: any) => {
    e.preventDefault();
    const response = await fetch("/api/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ firstName, surname, email, phone, password }),
    });
    if (!response.ok) {
      throw new Error("Failed to submit form");
    }
  };

and this is the API route:

export async function POST(request: Response) {
  const { firstName, surname, email, phone, password } = await request.json();

  await fetch(`https://${projectId}.api.sanity.io/v2021-10-21/data/mutate/${dataset}`, {
    method: "post",
    headers: {
      "Content-type": "application/json",
      Authorization: `Bearer ${sanity_API_Token}`,
    },
    body: JSON.stringify({ _type: "user", firstName, surname, email, phone, password }),
  });

  return NextResponse.json({ message: "Added successful" });
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rengkat
  • 23
  • 8

1 Answers1

0

it can happen due to many reasons

  • Validate the request payload: Ensure that the fetch request's payload (JSON.stringify({ _type: "user", firstName, surname, email, phone, password })) is properly formatted and matches the expected data structure on the server-side. Check that all the required fields are included and have valid values.
  • Test the Sanity API endpoint separately using tools like Postman or cURL to ensure that it is functioning as expected
  • Verify that the necessary variables such as projectId, dataset, and sanity_API_Token are correctly set with the appropriate values.
sameraze agvvl
  • 397
  • 4
  • 11