Search code examples
javascripttypescriptnext.jsprismaplanetscale

Request error PrismaClientValidationError on NextJS 13


I'm making a school project and I'm using NextJS 13, and trying to connect to the MYSQL database using Prisma with PlanetScale, but while trying to register a user I'm getting:

Request error PrismaClientValidationError:
Invalid `prisma.user.create()` invocation:

{
  data: {
+   cpf: String,
+   name: String,
+   email: String,
+   password: String,
+   phone: String,
+   gender: String,
+   birth: DateTime,
+   city: String,
+   state: String,
+   school: String,
+   bio: String,
?   avatar?: String | null
  }
}

Argument cpf for data.cpf is missing.
Argument name for data.name is missing.
Argument email for data.email is missing.
Argument password for data.password is missing.
Argument phone for data.phone is missing.
Argument gender for data.gender is missing.
Argument birth for data.birth is missing.
Argument city for data.city is missing.
Argument state for data.state is missing.
Argument school for data.school is missing.
Argument bio for data.bio is missing.

The Code on src/app/api/user :

import prisma from "../../../lib/prisma";
import { NextResponse } from "next/server"

export async function POST(request) {
    const body = request.body
    try {
        const newUser = await prisma.user.create({
            data: {
                cpf: body.cpf,
                name: body.name,
                email: body.email,
                password: body.password,
                phone: body.phone,
                gender: body.gender,
                birth: body.birth,
                city: body.city,
                state: body.state,
                school: body.school,
                bio: body.bio,
                // avatar: body.avatar || null,
            }
        })
        return NextResponse.json({ data: newUser, success: true });
    } catch (error) {
        console.error('Request error', error)
        return NextResponse.json({ error: 'Error creating user', success: false }, { status: 500 });
    }
    
}

The schema.prisma:

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
  relationMode = "prisma"
}

model User {
  id           Int         @id @default(autoincrement())
  cpf          String      @unique
  name         String
  email        String      @unique
  password     String
  phone        String
  gender       String
  birth        DateTime    @db.Date
  city         String
  state        String
  school       String
  bio          String
  avatar       String?
}

And the code on src/app/login/page.tsx:

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    let body = { cpf, name, email, password, phone, gender, birth, city, state, school, bio};
    try {
      const response = await fetch('/api/user', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      if (response.status !== 200) {
        throw new Error(await response.text())
      } else {
        console.log('Cadastro realizado com sucesso!');
      }
    } catch (error) {
      console.log(body);
      console.log(error);

    }
  }

If i modify the API code to :

const newUser = await prisma.user.create({
  data: {
    cpf: "12345678901",
    name: "John Doe",
    email: "[email protected]",
    password: "password123",
    phone: "1234567890",
    gender: "male",
    birth: new Date(),
    city: "New York",
    state: "NY",
    school: "Johns Hopkins University",
    bio: "I am a software engineer and I love to code.",
  }
});

It will work, already tried to change and format birthdate field, because i thought it was the issue, but same error


Solution

  • this line is causing issue:

     const body = request.body
    

    error message is indicating that you are not passing data

    Argument cpf for data.cpf is missing.

    in route files this is how we get the data in POST requests:

    export async function POST(request) {
        const body = await request.json()