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

safeParse始终执行失败,req.body为undefined的问题求助

问题排查:POST请求无法解析请求体导致输入验证失败

当前POST /task 路由始终触发输入验证失败分支,返回"输入错误"响应,即使已传入符合createTaskInput要求的参数。错误提示显示请求体为undefined,期望接收对象类型。

相关路由代码

router.post("/task", authMiddleware, async (req, res) => {
    //@ts-ignore
    const userId = req.userId
    // validate the inputs from the user;
    const body = req.body;

    
    const parseData = createTaskInput.safeParse(body);

    console.log("Request Body:", body);
    console.log("Parse Data Result:", parseData);
    console.log("Content-type:", req.headers['content-type']);

    if (!parseData.success) {
        return res.status(411).json({
            message: "You've sent the wrong inputs",
            error: parseData.error.errors
        })
    }

    // parse the signature to ensure the user has paid

    let response = await prismaClient.$transaction(async tx => {

        const response = await tx.task.create({
            data: {
                title: parseData.data.title ?? DEFAULT_TITLE,
                amount: "1",
                //TODO: Signature should be unique in the table else people can reuse a signature
                signature: parseData.data.signature,
                user_id: userId
            }
        });

        await tx.option.createMany({
            data: parseData.data.options.map(x => ({
                image_url: x.imageUrl,
                task_id: response.id
            }))
        })

        return response;

    })

    res.json({
        id: response.id
    })
})

错误响应

{
    "message": "You've sent the wrong inputs",
    "error": [
        {
            "code": "invalid_type",
            "expected": "object",
            "received": "undefined",
            "path": [],
            "message": "Required"
        }
    ]
}

排查解决步骤

  • 检查请求Content-Type头:查看代码日志中的Content-type值,确保Postman请求设置的是application/json。若使用表单格式(如multipart/form-data),express不会自动解析为JSON对象,导致req.body为undefined。
  • 确认express JSON解析中间件:确保项目中已配置express.json()中间件,该中间件负责解析JSON格式请求体,缺失会导致req.body无法被正确解析。
  • 验证Postman请求体格式:在Postman的Body标签选择raw -> JSON,输入标准JSON格式的参数,避免使用form-data或x-www-form-urlencoded(除非后端配置了对应解析中间件)。
  • 排查authMiddleware影响:暂时注释authMiddleware测试请求,确认该中间件是否意外修改或清空了req.body。
  • 核对日志输出:根据代码中的console.log("Request Body:", body)输出,若为undefined则重点排查前两点;若有值,再检查参数是否完全符合createTaskInput的校验规则。

内容的提问来源于stack exchange,提问作者Hrishabh Ayush

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:40:56