【问题标题】:Sendinblue create contact 'TypeError: Failed to fetch' error (using React)Sendinblue create contact 'TypeError: Failed to fetch' 错误(使用 React)
【发布时间】:2020-07-24 20:51:06
【问题描述】:

我正在尝试在我的 React JS 应用程序中实现 Sendinblue API。我有一个文本输入,用户要在其中输入他们的电子邮件,然后是一个将他们的电子邮件添加到 Sendinblue 列表的按钮。我正在使用位于 Node.js 中 here 的“创建联系人”参考,因为我正在为我的 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 文档上对此进行测试时,它每次都会成功地将电子邮件添加到我的联系人列表中。我每次都用一封新电子邮件对其进行测试,以确保它不会因为重复的电子邮件而引发错误。我还修改了updateEnabledtruefalse 之间的值,但它似乎无助于解决这个问题。

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

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

【问题讨论】:

    标签: javascript reactjs typeerror sendinblue


    【解决方案1】:

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

    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)
    

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

    【讨论】:

    • 感谢您的回复!当我运行这个新代码时,只是偶尔添加电子邮件,即使在我添加了正确的 api-key 并且每次试用都使用不同的电子邮件之后也是如此。它不会在 console.log 命令中打印任何内容(我什至也为此尝试了 alert 命令),所以我不确定这个 axios 命令是否正在运行。关于为什么会这样的任何想法?
    • 您可以尝试检查response 包含的内容。 POST 请求可能失败,response 对象有关于它的详细信息。
    猜你喜欢
    • 1970-01-01
    • 2023-02-15
    • 2018-01-05
    • 2018-09-21
    • 1970-01-01
    • 2022-10-06
    • 2018-04-03
    • 2020-07-10
    • 2020-09-18
    相关资源
    最近更新 更多