英文:
Typescript: Zod expected string, received undefined
问题
zod 在我尝试将 req.body 数据提交到 prisma orm 时出现以下错误 3 次(我正在使用 Insomnia):
ZodError: [
{
"code": "invalid_type",
"expected": "string",
"received": "undefined",
"path": [
"name"
],
"message": "Required"
},
这是 prisma 客户端模型:
model Client {
id String @id @default(uuid())
email String @unique
name String
password String
created_at DateTime @default(now())
updated_at DateTime @updatedAt
reviews ProductReview[] @relation("client")
adm Boolean @default(false)
@@map("clients")
}
这是路由:
const authController = new AuthController();
router.route('/register').post(authController.registerClient)
这是控制器,其中包含 registerClient 函数,这是导致 zod 错误的函数:
export class AuthController {
async registerClient(req: Request, res: Response) {
const createClientBody = z.object({
name: z.string(),
email: z.string(),
password: z.string(),
});
const { name } = createClientBody.parse(req.body); // 这行
const { email } = createClientBody.parse(req.body); // 这行
const { password } = createClientBody.parse(req.body); // 这行
const response = await prisma.client.create({
data: {
name,
email,
password
},
});
return res.status(201).send({ response });
};
}
英文:
zod is throwing the following error 3 times when i try to submit my req.body data to prisma orm (im using Insomnia):
ZodError: [
{
"code": "invalid_type",
"expected": "string",
"received": "undefined",
"path": [
"name"
],
"message": "Required"
},
this is the prisma client model:
model Client {
id String @id @default(uuid())
email String @unique
name String
password String
created_at DateTime @default(now())
updated_at DateTime @updatedAt
reviews ProductReview[] @relation("client")
adm Boolean @default(false)
@@map("clients")
}
this is the route:
const authController = new AuthController();
router.route('/register').post(authController.registerClient)
this is the controller with the registerClient function, that is the one that is throwing the zod error:
export class AuthController {
async registerClient(req: Request, res: Response) {
const createClientBody = z.object({
name: z.string(),
email: z.string(),
password: z.string(),
});
const { name } = createClientBody.parse(req.body); // this lines
const { email } = createClientBody.parse(req.body); // this lines
const { password } = createClientBody.parse(req.body); // this lines
const response = await prisma.client.create({
data: {
name,
email,
password
},
});
return res.status(201).send({ response });
};
}
答案1
得分: 1
"Allows: string (any length) or null or undefined." 可接受:字符串(任意长度)或 null 或 undefined。
英文:
name: z.string().nullish(),
Allows: string (any length) or null or undefined.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论