I am currently trying to incorporate mailChimp API into my project, but the resFile code that is responsible for sending the success code isn't working.
The code:
async function run(){
try {
const res = await mailchimp.lists.addListMember(listId, {
email_address: subscribingUser.emailAddress,
status: "subscribed",
merge_fields: {
NAME: subscribingUser.userName
}
});
console.log(`Successfully added contact as an audience member. The contact's id is ${res.id}.`);
console.log(res);
//this res.sendFile does not send the file
res.sendFile(__dirname + "/success.html");
} catch(error) {
//Code went straight to this and answered "error undefined"
console.log(`Error ${error.status}.`);
//This file was successfully sent following the "error undefined"
res.sendFile(__dirname + "/failure.html");
}
}
run();
});
I tried:
1)Renaming the success file (doesn't work)
2)Swapping the success and failure file (doesn't work)
All gave the same outcome Expected outcome: Sending the success file to the client upon successful completion. subscribingUser is successfully created Actual outcome: Sending the failure file to client despite the successful completion, terminal says "error undefined". subscribingUser is successfully created.
Edit 1(8 hours after this post was made): I solved the problem by changing the
const res = await mailchimp.....
to
const response = await mailchimp...
The whole working code snippet is pasted below. However, I don't yet know why it worked. I have some theories in the code snippet below. If someone is able to shed light on why, I would be thankful if you could do so. Thank you for all those that helped!
///This is the res I am trying to call.
app.post("/", function(req,res){
//The client's name and email
const clientName = req.body.userName;
const clientEmail = req.body.userEmail;
//my unique list ID is here, so I censored it.
const listId = "XXXXXXX";
const subscribingUser = {
emailAddress: clientEmail,
userName: clientName
}
//Showing us the values of the variables in the object subscribingUser
//Tells us what the user had inputted into the website.
console.log(subscribingUser);
async function run(){
try {
///This was probably why it registered the res.SendFIle in the try
///function as a function, as it overrode the res mentioned above at
///app.post.
const response = await mailchimp.lists.addListMember(listId, {
email_address: subscribingUser.emailAddress,
status: "subscribed",
merge_fields: {
NAME: subscribingUser.userName
}
});
console.log(`Successfully added contact as an audience member. The contact's id is ${response.id}.`);
res.sendFile(__dirname + "/success.html");
} catch(error) {
console.log(`Error ${error}.`);
res.sendFile(__dirname + "/failure.html");
}
}
run();
});