3

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}/subscribe returns 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'}))
    }
};
3
  • 1
    Can you try adding a return before you axios method in the subscribe function and moving your await before the res.send()? Commented Dec 11, 2019 at 2:39
  • did you ever resolve? I'm experiencing the same issue Commented Sep 18, 2020 at 17:34
  • did u solve it ? Commented Jan 28, 2021 at 16:29

1 Answer 1

0

I had a similar problem and all I had to do was try the url in production, say {URL}/subscribe, then ensure you get this

{ "error": "Method GET not allowed" }

if you do not get that, check your commit on git properly to see if that route is being pushed to git and it is not being ignored. If the file is being ignored, just add it properly and redeploy.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.