I'm working on a next.js project, and when running my project locally, I'm able to insert an email into a form and successfully POST it to MailChimp via their API. In production, the same code doesn't work, but I've confirmed that production has:
- Access to and correct MailChimp API key Next API route
- Api route
{URL}/subscribereturns 200
The issue seems to be after the API route is called and the subsequent API call happens. I'm lost and would love your insights.
pages/api/subscribe.js
const axios = require('axios');
const LIST_ID = 'b29d6f1e61'; // MailChimp Audience
const key = `Basic ${Buffer.from(`apikey:${process.env.MAILCHIMP_API_KEY}`).toString('base64')}`;
const subscribe = ( email ) => {
axios({
method: 'POST',
url: `https://us18.api.mailchimp.com/3.0/lists/${LIST_ID}/members/`,
headers: {Authorization: key},
data: { email_address: `${email}`, status: "subscribed" } })
.then(response => {
console.log(response);
return response
}).then(data => {
console.log('Data Rec\'d:', data);
}).catch(error => {
console.log('Subscribe error:', error);
// reject('Something went wrong')
});
};
module.exports = async (req, res) => {
if (req.method === 'POST') {
res.setHeader('Content-Type', 'application/json');
res.statusCode = 200;
res.send(req);
await subscribe(req.body);
res.end()
} else {
res.setHeader('Content-Type', 'application/json');
res.statusCode = 200;
res.end(JSON.stringify({name: 'GET received'}))
}
};
axiosmethod in thesubscribefunction and moving your await before theres.send()?