Request error PrismaClientValidationError on NextJS 13

huangapple go评论67阅读模式
英文:

Request error PrismaClientValidationError on NextJS 13

问题

我正在制作一个学校项目,我正在使用 NextJS 13,并尝试使用 Prisma 与 PlanetScale 连接到 MYSQL 数据库,但在尝试注册用户时遇到了以下错误:

```plaintext
请求错误 PrismaClientValidationError:
无效的 `prisma.user.create()` 调用:

{
  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
  }
}

data.cpf 的参数缺失。
data.name 的参数缺失。
data.email 的参数缺失。
data.password 的参数缺失。
data.phone 的参数缺失。
data.gender 的参数缺失。
data.birth 的参数缺失。
data.city 的参数缺失。
data.state 的参数缺失。
data.school 的参数缺失。
data.bio 的参数缺失。

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('请求错误', error)
        return NextResponse.json({ error: '创建用户时出错', success: false }, { status: 500 });
    }
    
}

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?
}

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);

    }
  }

如果我将 API 代码修改为:

const newUser = await prisma.user.create({
  data: {
    cpf: "12345678901",
    name: "John Doe",
    email: "johndoe@example.com",
    password: "password123",
    phone: "1234567890",
    gender: "male",
    birth: new Date(),
    city: "New York",
    state: "NY",
    school: "Johns Hopkins University",
    bio: "我是一名软件工程师,我热爱编程。"
  }
});

它会正常工作,我已经尝试过更改和格式化出生日期字段,因为我认为这可能是问题所在,但是仍然出现相同的错误。


<details>
<summary>英文:</summary>

I&#39;m making a school project and I&#39;m using NextJS 13, and trying to connect to the MYSQL database using Prisma with PlanetScale, but while trying to register a user I&#39;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 :

```js
import prisma from &quot;../../../lib/prisma&quot;;
import { NextResponse } from &quot;next/server&quot;

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(&#39;Request error&#39;, error)
        return NextResponse.json({ error: &#39;Error creating user&#39;, success: false }, { status: 500 });
    }
    
}

The schema.prisma:

generator client {
  provider = &quot;prisma-client-js&quot;
}

datasource db {
  provider = &quot;mysql&quot;
  url      = env(&quot;DATABASE_URL&quot;)
  relationMode = &quot;prisma&quot;
}

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&lt;HTMLFormElement&gt;) {
    e.preventDefault();
    let body = { cpf, name, email, password, phone, gender, birth, city, state, school, bio};
    try {
      const response = await fetch(&#39;/api/user&#39;, {
        method: &#39;POST&#39;,
        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },
        body: JSON.stringify(body),
      })
      if (response.status !== 200) {
        throw new Error(await response.text())
      } else {
        console.log(&#39;Cadastro realizado com sucesso!&#39;);
      }
    } catch (error) {
      console.log(body);
      console.log(error);

    }
  }

If i modify the API code to :

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

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

答案1

得分: 1

以下是翻译好的内容:

这一行代码引发了问题:

const body = request.body

错误消息表明您未传递数据

> data.cpf 参数缺失。

route 文件中,这是我们在 POST 请求中获取数据的方式:

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

英文:

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()

huangapple
  • 本文由 发表于 2023年5月15日 07:19:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定