Sendinblue 创建联系人'TypeError: Failed to fetch'错误(使用 React)



我正在尝试在我的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文档上测试这一点时,它每次都成功地将电子邮件添加到我的联系人列表中。我每次都用一封新的电子邮件来测试它,以确保它不会因为重复的电子邮件而引发错误。我还修改了truefalse之间的updateEnabled的值,但这似乎无助于解决这个问题。

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

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

没错,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)

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

最新更新