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

Next.js应用调用SendGrid API报错:personalizations需为数组

解决SendGrid API报错:Error: Array expected forpersonalizations

错误原因

  1. 错误类型转换:sendAlerts.js里用模板字符串${req.body.personalizations}把前端传递的数组转成了字符串,而SendGrid要求personalizations必须是数组格式,这是触发报错的直接原因。
  2. 未解析请求体:Next.js Pages Router的API路由不会自动解析JSON请求体,直接使用req.body无法正确获取前端传递的数组数据。
  3. 环境变量拼写错误:代码里写的process.env.SENGRID_APIKEY少了字母D,正确的变量名应为SENDGRID_APIKEY,这个错误会导致后续API密钥无效,触发认证问题。

解决方法

修改api/sendAlerts.js代码,修复上述问题:

const mail = require('@sendgrid/mail');

// 修正环境变量拼写
mail.setApiKey(process.env.SENDGRID_APIKEY);

export default async (req, res) => {
  // 限制仅POST请求访问
  if (req.method !== 'POST') {
    return res.status(405).json({ error: '只支持POST请求' });
  }

  try {
    // 解析JSON格式的请求体
    const requestBody = await req.json();
    
    await mail.send({
      // 直接使用原始数组,取消不必要的字符串转换
      personalizations: requestBody.personalizations,
      from: 'david.gregory.medero@gmail.com',
      subject: requestBody.subject,
      text: requestBody.message
    });

    res.status(200).json({ status: 'Ok' });
  } catch (error) {
    // 返回错误信息方便调试
    res.status(500).json({ error: error.message });
  }
};

前端代码说明

你前后两次编写的前端提交函数逻辑都是正确的,只要后端能正确解析并传递personalizations数组,SendGrid就能正常处理请求,无需修改前端代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:10:17