You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Zod校验时遇“expected string, received undefined”错误求助

问题排查与解决方案

核心原因:Express未配置JSON请求体解析中间件

Express框架默认不会自动解析JSON格式的请求体,这会导致req.body始终为undefined——哪怕你在Insomnia里正确传入了name字段,Zod验证时依然会判定该字段缺失。

修复步骤

1. 给Express添加JSON解析中间件

在你的Express入口文件(比如app.js或server.js)中添加以下代码:

const express = require('express');
const app = express();

// 关键:启用JSON请求体解析
app.use(express.json());

// 后续挂载你的路由
app.use('/your-api-path', router);

2. 优化Zod验证代码(避免重复解析)

当前代码中重复调用了三次createClientBody.parse(req.body),既浪费性能又无意义。只需解析一次并解构所有字段:

export class AuthController {
    async registerClient(req: Request, res: Response) {
        const createClientBody = z.object({
            name: z.string(),
            email: z.string().email(), // 可选:添加邮箱格式校验,提升数据合法性
            password: z.string().min(6), // 可选:添加密码长度校验
        });
        // 仅解析一次,解构出所有需要的字段
        const { name, email, password } = createClientBody.parse(req.body);

        const response = await prisma.client.create({
            data: { name, email, password }
        });

        return res.status(201).send({ response });
    };
}

3. 验证Insomnia请求配置

确保你的请求符合以下要求:

  • 请求方法为POST
  • 请求头中Content-Type设置为application/json
  • 请求体为标准JSON格式(而非form-data或x-www-form-urlencoded,除非你额外配置了对应解析中间件),示例:
{
  "name": "你的用户名",
  "email": "your-email@example.com",
  "password": "你的密码"
}

内容的提问来源于stack exchange,提问作者Pedro Souza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 23:15:21