I am trying to implement the Sendinblue API in my React JS application. I have a text input that the user is to enter their email into, and then a button that will add their email to a Sendinblue list. I am using the "Create a contact" reference located here in Node.js, as I am using the JavaScript code for my React app. Sometimes, this code works, as the email is successfully added to the SendinBlue list, however most times the email is not added and I receive the following error:
TypeError: Failed to fetch
My full code can be seen below, where the email is input from the text field:
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: '[email protected]'},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
When I test this on the Sendinblue API docs, it successfully adds the email to my contact list every time. I test it with a new email each time to ensure that it does not throw an error because of a duplicate email. I have also tinkered with the value of updateEnabled
between true
and false
however it does not seem to help solve this issue.
I believe that the error may stem from the var request = require("request");
command in the first line, as I am not sure if require
is a React method or a Node.js method.
If anyone has any ideas on how I could fix this, your help would be greatly appreciated. Thank you.
You are right, require
is used for Node.js and the example in the Sendinblue reference mentions it too. Try using axios
instead. You just need to install it like any other npm module in your React project using npm install axios
and try with the following script:
const response = await axios.post(
'https://api.sendinblue.com/v3/contacts',
{ updateEnabled: false, email: '[email protected]'},
{ headers: { 'Content-Type': 'application/json', 'api-key': 'My SendinBlue Application API Key' } }
)
console.log(response.data)
Please let me know if it helps! Thanks