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

表单提交数据至服务器返回undefined的问题排查求助

表单提交后端接收数据为undefined的解决方案

你的问题核心是前后端数据结构不匹配:后端尝试从req.body.data中获取数据,但前端发送的JSON并没有data这个顶层字段,直接把表单字段作为顶层属性发送了,所以data变量自然是undefined。

解决方法(二选一即可)

方法1:修改后端代码(推荐,贴合当前前端发送结构)

直接从req.body中获取数据,不需要解构data字段:

// "/api/serverfile.js"
export default async function handler(req, res) {
  // 直接解构需要的表单字段,或获取完整请求体
  const { email, firstName, lastName, brand_url, logo, email_body } = req.body;
  
  if (req.method === "POST") {
    try {
      console.log("收到的表单数据:", { email, firstName, lastName }); // 验证数据
      res.status(200).json({ message: "success" });
    } catch (error) {
      console.error(error);
      res.status(500).json({ message: error.message });
    }
  } else {
    res.status(405).json({ message: "仅支持POST请求" });
  }
}

方法2:修改前端代码(调整发送的数据结构)

如果坚持要后端用req.body.data接收,就在前端把数据包裹在data字段里:

// frontendfile.js的handleSubmit中修改body部分
body: JSON.stringify({
  data: {
    email,
    firstName,
    lastName,
    brand_url,
    logo,
    email_body,
  }
}),

额外调试建议

  1. 前端发送前打印数据,确认结构是否正确:
    // handleSubmit中fetch前添加
    const sendData = { email, firstName, lastName, brand_url, logo, email_body };
    console.log("准备发送的数据:", sendData);
    
  2. 后端先打印完整req.body,排查实际接收内容:
    console.log("完整请求体:", req.body);
    
  3. 确认后端框架已启用JSON解析(Next.js API路由默认支持;如果是Express等框架,需添加app.use(express.json())中间件)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:18:11