0

我正在尝试在我的 React JS 应用程序中实现 Sendinblue API。我有一个文本输入,用户要在其中输入他们的电子邮件,然后是一个将他们的电子邮件添加到 Sendinblue 列表的按钮。我正在使用 Node.js 中的“创建联系人”参考因为我正在为我的 React 应用程序使用 JavaScript 代码。有时,此代码有效,因为电子邮件已成功添加到 SendinBlue 列表,但大多数时候电子邮件未添加,我收到以下错误:

TypeError: Failed to fetch

我的完整代码如下所示,其中电子邮件是从文本字段输入的:

var request = require("request");

var options = {
  method: 'POST',
  url: 'https://api.sendinblue.com/v3/contacts',
  headers: {
    accept: 'application/json',
    'content-type': 'application/json',
    'api-key': 'My SendinBlue Application API Key'
  },
  body: {updateEnabled: false, email: 'newEmail@exampleWebsite.com'},
  json: true
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

当我在 Sendinblue API 文档上对此进行测试时,它每次都会成功地将电子邮件添加到我的联系人列表中。我每次都用一封新电子邮件对其进行测试,以确保它不会因为重复的电子邮件而引发错误。我也修改了updateEnabledbetween的值truefalse但它似乎无助于解决这个问题。

我相信错误可能源于var request = require("request");第一行中的命令,因为我不确定require是 React 方法还是 Node.js 方法。

如果有人对我如何解决这个问题有任何想法,我们将不胜感激。谢谢你。

4

1 回答 1

2

你是对的,require它用于 Node.js,Sendinblue 参考中的示例也提到了它。尝试axios改用。你只需要像 React 项目中的任何其他 npm 模块一样安装它,npm install axios并尝试使用以下脚本:

const response = await axios.post(
  'https://api.sendinblue.com/v3/contacts',
  { updateEnabled: false, email: 'newEmail@exampleWebsite.com'},
  { headers: { 'Content-Type': 'application/json', 'api-key': 'My SendinBlue Application API Key' } }
)
console.log(response.data)

如果有帮助,请告诉我!谢谢

于 2020-08-12T09:26:44.623 回答