The code below is the API call to add a contact to a list/audience programmatically using Node JS and the Mailchimp library. Documentation is found on: https://mailchimp.com/developer/marketing/guides/create-your-first-audience/#add-a-contact-to-an-audience
const listId = "YOUR_LIST_ID";
const subscribingUser = {
firstName: "Prudence",
lastName: "McVankab",
email: "prudence.mcvankab@example.com"
};
async function run() {
const response = await mailchimp.lists.addListMember(listId, {
email_address: subscribingUser.email,
status: "subscribed",
merge_fields: {
FNAME: subscribingUser.firstName,
LNAME: subscribingUser.lastName
}
});
console.log(
`Successfully added contact as an audience member. The contact's id is ${
response.id
}.`
);
}
run();
Here's how I implemented the code in my app.js
app.post("/", function(req, res) {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const apiAudienceName = "Sample Tech Newsletter Subscription";
const listId = apiAudienceName;
const subscribingUser = {
firstName: firstName,
lastName: lastName,
email: email
};
async function run() {
const response = await mailchimp.lists.addListMember(listId, {
email_address: subscribingUser.email,
status: "subscribed",
merge_fields: {
FNAME: subscribingUser.firstName,
LNAME: subscribingUser.lastName
}
});
console.log(`Successfully added contact as an audience member. The contact's id is ${response.id}.`);
}
run();
});
To me, I did the exact requirement of the Mailchimp server to add to my created list but this code is throwing an error saying "Unhandled promise rejection". I've tried to do my research of course but as a beginner in this language, I don't really quite grasp what is needed for me to make this happen. If someone could correct me or show me the error in my code, I would appreciate it. Thank you very much!
NOTE: I was able to make this work by using HTTP request module. But for this time, I wanted to learn how to follow a documentation and use their given code and library. To me, it seems that I did that but it doesn't seem to work.