React.js中使用Netlify Functions向SendGrid API传数据失败问题
我正在开发一个集成SendGrid的React邮件自动化应用,用Netlify Functions和SendGrid API交互。现在遇到的问题是:虽然Netlify函数和React应用的API请求配置好了,数据却传不到SendGrid API里。没有任何错误提示,函数执行也正常,只有本地部署时能给订阅者发邮件,但联系人就是加不到SendGrid的列表里。
已经做过的排查:
- 查看Netlify函数日志,没有错误或异常
- 浏览器开发者工具网络面板显示,向Netlify Function的请求成功
- 确认SendGrid API密钥已在Netlify中正确设置为环境变量,SendGrid账户也完成了验证
预期效果:订阅者提交表单时触发Netlify Function,把订阅者邮箱添加到SendGrid联系人列表。
以下是我的Netlify函数代码:
import type { Handler } from "@netlify/functions"; import fetch from "node-fetch"; const handler: Handler = async function(event) { if (event.body === null) { return { statusCode: 400, body: JSON.stringify("Payload required"), }; } const requestBody = JSON.parse(event.body) as { subscriberName: string; subscriberEmail: string; inviteeEmail: string; }; await fetch(`https://api.sendgrid.com/v3/marketing/contacts`, { headers: { Authorization: `Bearer apiKey123`, 'Content-Type': 'application/json' }, method: "PUT", body: JSON.stringify({ "contacts":[ { "email": requestBody.subscriberEmail,} ] }), }) return { statusCode: 200, body: JSON.stringify("Subscribe email sent!"), }; }; export { handler };
1. 替换硬编码的API密钥
代码里直接写死了apiKey123,必须改用Netlify环境变量获取:
Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
本地测试时可在项目根目录创建.env文件添加SENDGRID_API_KEY=你的密钥,部署到Netlify后要在站点环境变量里配置对应项。
2. 增加API请求错误捕获
当前代码没有处理SendGrid API的错误响应,哪怕请求失败也会返回200状态,导致无法定位问题。修改代码添加错误处理:
const response = await fetch(`https://api.sendgrid.com/v3/marketing/contacts`, { // 保留原有配置 }); if (!response.ok) { const errorDetails = await response.json(); console.error("SendGrid请求失败:", errorDetails); return { statusCode: response.status, body: JSON.stringify(`添加联系人失败: ${errorDetails.errors?.map(e => e.message).join('; ')}`), }; }
3. 修正请求体格式问题
代码中请求体的email字段后多了一个逗号("email": requestBody.subscriberEmail,),虽然部分解析器会忽略,但严格JSON格式不允许,建议删除多余逗号:
"contacts":[ { "email": requestBody.subscriberEmail } ]
4. 验证环境变量是否生效
在函数开头添加日志,确认Netlify环境变量已加载(注意不要直接输出密钥):
console.log("SENDGRID_API_KEY已配置:", !!process.env.SENDGRID_API_KEY);
之后查看Netlify函数日志,确认变量存在。
5. 检查SendGrid API密钥权限
确保你的SendGrid API密钥拥有Marketing Contacts的写入权限,可在SendGrid后台的「API Keys」页面配置权限范围。
内容的提问来源于stack exchange,提问作者Laima

