如何在json中获得ZodError



当我在失眠中测试它时,我试图在json中获得zod验证错误,但我只在终端和失眠中得到它,它告诉我错误:无法连接到服务器我看到了一些例子,它到处都是有效的……我不明白为什么它不工作…

my register method

export const register = async (req: Request, res: Response) => {
const payloadSchema = z
.object({
firstname: z.string({
required_error: "Firstname is required",
invalid_type_error: "Title must be a string",
}),
lastname: z.string({
required_error: "Lastname is required",
invalid_type_error: "Title must be a string",
}),
email: z
.string({ required_error: "Email is required" })
.email({ message: "Invalid email address" }),
password: z.string(),
confirm: z.string(),
})
.refine((data) => data.password === data.confirm, {
message: "Passwords don't match",
path: ["confirm"], 
});
const parsedData = await payloadSchema.parseAsync(req.body);
try {
const result = await User.findOne({ where: { email: parsedData.email } });
if (result) {
return res.status(400).json({
success: false,
error: "User already exists",
});
}
const user = new User();
user.firstname = parsedData.firstname;
user.lastname = parsedData.lastname;
user.email = parsedData.email;
user.password = parsedData.password;
await user.save();
const accessToken = jwt.sign(
{ userId: user.id },
process!.env!.TOKEN_SECRET!
);
return res.status(200).json({
success: true,
createdUser: user,
accessToken: accessToken,
});
} catch (e) {
if (e instanceof ZodError) {
return res.status(400).json({
success: false,
error: e.flatten(),
});
} else if (e instanceof Error) {
return res.status(400).json({
message: e.message,
});
}
}
};

那么我做错了什么,我该如何修复它?谢谢你的关注。

const parsedData = await payloadSchema.parseAsync(req.body);

如果验证失败,来自Zod的parseAsync调用将抛出错误,但在您的代码中,它在try/catch块之外,请尝试将其移动到内部:

try {
const parsedData = await payloadSchema.parseAsync(req.body);

const result = await User.findOne({ where: { email: parsedData.email } });
...

相关内容

  • 没有找到相关文章

最新更新