0

I am facing a problem with fetching /api/user in nextjs.13

// @/app/page.tsx
"use client";
import { FormEvent } from "react";

export default function Home() {
  async function handlePost(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();

    let formData = new FormData(event.currentTarget);

    try {
      const response = await fetch("/api/user", {
        method: "POST",
        body: formData,
      });
      const data = await response.json();
    } catch (error) {
      console.log(error);
    }
  }

  return (
    <form
      onSubmit={handlePost}
      className="flex flex-col gap-5 w-[300px] m-auto mt-[200px]"
    >
      <input type="text" name="name" id="name" />
      <input type="email" name="email" id="email" />
      <input type="password" name="password" id="password" />
      <button type="submit">Submit</button>
    </form>
  );
}
// @/app/api/user/route.ts
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

interface PostRequest {
  body: {
    name: string;
    email: string;
    password: string;
  };
}

export async function POST(request: PostRequest) {
  await prisma.user.create({
    data: {
      name: request.body.name,
      email: request.body.email,
      password: request.body.password,
    },
  });
  console.log(request.body);
  return prisma.user.findFirst();
}

And this is the error appearing

Argument `name` is missing.
    at xn (F:\Node\react\with-db\node_modules\@prisma\client\runtime\library.js:116:5852)
    at vn.handleRequestError (F:\Node\react\with-db\node_modules\@prisma\client\runtime\library.js:123:6429)
    at vn.handleAndLogRequestError (F:\Node\react\with-db\node_modules\@prisma\client\runtime\library.js:123:6119)
    at vn.request (F:\Node\react\with-db\node_modules\@prisma\client\runtime\library.js:123:5839)
    at async l (F:\Node\react\with-db\node_modules\@prisma\client\runtime\library.js:128:9763)
    at async POST (webpack-internal:///(rsc)/./src/app/api/user/route.ts:10:5)
    at async eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:254:37) {
  clientVersion: '5.2.0'
}

Furthermore, when I consoled the formData, it logs undefined

I tried replacing formData, with

body: JSON.stringfy({
  name: "myname",
  email: "myemail@gmail.com",
  password: "my password"
});

But, the error occures

  • Hi Osama, did you end up resolving this issue? I've had the same problem, and have had no luck finding an answer – jvs789789 Sep 01 '23 at 12:04
  • @jvs789789 unfortunately no, i just moved to next-auth. it will handle the whole users system. in other cases i moved to put the files in utils folder outside the app. and then use the function in that file. try to use that idea – Osama Mohammed Sep 02 '23 at 05:26

0 Answers0