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

Next.js集成SendGrid发邮件问题:前端数据正常后端获值为undefined

Next.js联系表单邮件内容字段为undefined的解决方案

你遇到的问题是前端能正确提交数据,但后端API路由中无法读取req.body里的用户字段,导致邮件内容显示undefined。结合代码和现象分析,核心问题出在请求体的处理逻辑或前端请求配置上,以下是具体解决方案:

1. 修复后端API路由的req.body处理

你的代码中使用了const body = JSON.parse(JSON.stringify(req.body));,这是完全冗余的操作——Next.js的API路由默认会自动解析Content-Type: application/json的请求体,req.body已经是解析好的JavaScript对象。这行冗余代码不仅没用,还可能在某些场景下导致数据异常。

修改后的API路由代码:

import cookie from "cookie";
const mail = require("@sendgrid/mail");

mail.setApiKey(process.env.NEXT_PUBLIC_SENDGRID_API_KEY);

export default async (req, res) => {
  // 先打印请求体,方便排查字段是否正常接收
  console.log("Received request body:", req.body);

  res.setHeader(
    "Set-Cookie",
    cookie.serialize("token", req.body.token || "", {
      httpOnly: true,
      secure: process.env.NODE_ENV !== "development",
      expires: new Date(0),
      maxAge: 60 * 60,
      sameSite: "strict",
      path: "/",
    })
  );

  // 直接使用解析后的req.body
  const body = req.body;

  const message = `
  FirstName: ${body.firstName}\r\n
  Email: ${body.email}\r\n
  phone: ${body.phone}\r\n
  Message: ${body.message}\r\n
`;

  const data = {
    to: "info@test.com",
    from: "info@test.com",
    subject: `New message from ${body.firstName} ${body.phone}`,
    text: message,
    html: message.replace(/\r\n/g, "<br />"),
  };
  try {
    await mail.send(data);
    console.log(data);
    res.status(200).json({ status: "OK" });
  } catch (error) {
    console.log("server error", error);
    if (error.response) {
      console.log(error.response.body);
    }
    res.status(400).json({ status: "ERROR", message: error.message });
  }
};

2. 确保前端请求配置正确

前端发送请求时必须满足以下条件,否则后端无法正确解析请求体:

  • 使用POST方法
  • 设置Content-Type: application/json请求头
  • 用JSON.stringify()将表单数据转为JSON字符串

示例前端提交代码:

const handleSubmit = async (formData) => {
  try {
    const response = await fetch("/api/contact", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    });
    const result = await response.json();
    console.log(result);
  } catch (err) {
    console.error(err);
  }
};

3. 额外排查点

如果上述修改后仍未解决问题,可检查以下内容:

  • 查看终端中console.log("Received request body:", req.body)的输出,确认请求体是否为空或字段名与前端不一致
  • 检查前端表单字段的name属性,是否和后端使用的firstName、email等字段名完全匹配
  • 确认next.config.js中没有自定义的bodyParser配置覆盖默认解析逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:18:28