使用 React.js 中的 Netlify 函数将数据发送到 SendGrid API 时遇到问题(已解决)

问题描述 投票:0回答:1

我正在开发一个集成 SendGrid 以实现电子邮件自动化的 React 应用程序。为了实现这一目标,我使用 Netlify Functions 与 SendGrid API 进行交互 (https://docs.netlify.com/integrations/email-integration/)。问题是,尽管已配置 Netlify 函数和 React 应用程序来发出 API 请求,但数据并未成功发送到 SendGrid 的 API。我没有收到任何错误消息,并且该函数执行没有问题。在本地部署时,电子邮件将发送到订阅者的电子邮件地址,但据我所知。

我已查看 Netlify 功能日志,没有任何错误消息或任何问题的迹象。我检查了浏览器开发者工具中的网络选项卡,对Netlify功能的请求是成功的。我已经验证我的 SendGrid API 密钥是否已正确设置为 Netlify 中的环境变量。我的 SendGrid 帐户也经过验证,因此不会造成任何问题。目前,我期望当订阅者提交订阅表单时,将触发 Netlify 功能,并且订阅者的电子邮件应添加到 SendGrid 联系人列表中。 这是功能代码:

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 };

reactjs email sendgrid netlify sendgrid-api-v3
1个回答
0
投票

好吧,所以我自己找到了问题所在。我将其发布在这里,希望遇到类似问题的其他人不需要花几天时间试图找出问题所在:) 所以,基本上我需要添加“cookies”属性

  const cookie = event.headers["Cookie"] || event.headers["cookie"];

并定义带有和不带有cookie的标头

const headersWithoutCookie = {
Authorization: `Bearer apiKey123`,
'Content-Type': 'application/json',};
const headers = {
...headersWithoutCookie,
cookie: cookie || '',};

然后只需在函数中添加标题

const response = await fetch(`https://api.sendgrid.com/v3/marketing/contacts`, {
headers,
method: "PUT",
© www.soinside.com 2019 - 2024. All rights reserved.