I've built a newsletter API with Mailchimp, and new users can successfully sign up to my newsletter by filling in the form and submitting. However, if there's an error in signing the user up (for example, if they've already signed up), then my current code does not detect this, and still re-directs the user to a 'sign up success' page.
The error however is logged in my terminal - for example, if the contact exists, this error is logged:
error_code: 'ERROR_CONTACT_EXISTS'
I'm currently using a really simple else-if statement that re-directs the user to the success page if the status code === 200.
const request = https.request(url, options, function(response) {
if (response.statusCode === 200) {
res.sendFile(__dirname + "/newsletter-success.html");
} else {
res.sendFile(__dirname + "/newsletter-failure.html");
}
response.on("data", function(data) {
console.log(JSON.parse(data));
});
});
I've tried adapting the callback to pass in errors but not sure if that's right.
Is there a better way of re-structuring my code so that it redirects if successful, and if there's an error then it'll take the user to the failure page?
Thanks.