Node.js中使用Zod验证时报错TypeError: schema.parseAsync is not a function的问题排查
Node.js中使用Zod验证时报错TypeError: schema.parseAsync is not a function的问题排查
我帮你排查了一下代码,发现问题主要出在导入导出的匹配上,还有几个小的拼写/配置错误,一起来看看怎么修复:
1. 核心问题:Schema导入时未正确解构
你的Zod Schema文件是通过module.exports = { signupSchema };导出的一个对象(包含signupSchema属性),但在auth-router.js里你直接把整个导出对象赋值给了signupSchema变量:
// 错误的导入方式 const signupSchema = require("../validator/auth-validator")
这时候signupSchema其实是个普通JavaScript对象,不是Zod的Schema实例,自然没有parseAsync方法,才会抛出类型错误。
修复方案:改成解构导入,获取真正的Schema实例:
// auth-router.js 修正后的导入 const { signupSchema } = require("../validator/auth-validator")
2. Schema里的两个细节错误
除了核心问题,你的Schema还有两处小问题会影响验证逻辑:
phone字段的错误配置:你用了reportError,但Zod里必填字段的错误提示应该用required_errorpassword拼写错误:你写成了pasword,如果前端传递的字段名是password,这会导致密码验证完全失效
修正后的Schema片段:
const { z } = require('zod') const signupSchema = z.object({ username: z .string({ required_error: "Username is required"}) .trim() .min(3, {message: "Username must be at least 3 characters"}) .max(255, {message: "Username must be less than 255 characters"}), email: z .string({ required_error: "Email is required"}) .trim() .min(3, {message: "Email must be at least 3 characters"}) .max(255, {message: "Email must be less than 255 characters"}), phone: z .string({required_error: "Phone no. is required"}) // 修正为required_error .trim() .min(10, {message: "Phone no. must be at least 10 characters"}) .max(20, {message: "Phone no. must be less than 20 characters"}), password: z // 修正拼写为password .string({ required_error: "Password is required"}) .min(7, {message: "Password must be at least 7 characters"}) // 顺便统一提示文案和校验值 .max(1024, {message: "Password must be less than 1024 characters"}), }) module.exports = { signupSchema };
总结
完成上述两处修改后,传入validate中间件的就会是真正的Zod Schema实例,parseAsync方法就能正常调用,验证逻辑也会按预期工作。
备注:内容来源于stack exchange,提问作者Mayur Patil
相关产品推荐
相关产品推荐

