Search code examples
node.jsreactjsexpressheroku

No 'Access-Control-Allow-Origin' header is present on the requested resource when deployed to Heroku


So I have a simple Heroku app that just signs people up to my Mailchimp contacts list. I have it working locally, but when deploying the app I get CORS errors.

I've tried adding withCredentials: true to my axios request and adding cors origin in my Express app, but it still doesn't work.

I have been going through all kinds of articles on cors issues trying to get this to work and understand why this is happening.

I've replaced some of the sensitive information with dummy text, but this is essentially how the request is being made and what the server is doing with the information.

React Code:

const submitForm = async (values) => {
    const { email } = values;

    try {
        const payload = {
            email_address: email
        };

        await axios.post("https://some-url.herokuapp.com", payload, { withCredentials: true });
            handleMessage("Thank you for signing up.");
    } catch (error) {
        console.log(error.message);
        handleMessage(error.message);
    }
}

Express Code:

const cors = require('cors');

app.use(cors({
    origin: `https://www.mycustomdomain.com/`,
    credentials: true
}));

app.post('/', jsonParser, (req, res, next) => {
    const { email_address } = req.body

    if (!email_address) {
        return res.status(400).json({
            error: `Missing email in request body`
        })
    }

    const data = {
        members: [
            {
                email_address,
                status: 'subscribed'
            }
        ]
    }

    const payload = JSON.stringify(data);

    const options = {
        url: `https://mailchim-api.com`,
        method: 'POST',
        headers: {
            Authorization: `auth authCode`
        },
        body: payload
    }

    request(options, (err, response, body) => {
        if (err) {
            res.status(500).json(err)
        } else {
            if (response.statusCode === 200) {
                res.status(200).json(body)
            }
        }
    })
})

Solution

  • My initial problem was that I didn't manually enter the env variables used in the Express app into Heroku.

    I had to run heroku config:set APIKEY=SOME-PASSWORD in order to get all of my env variables to be used on Heroku. https://devcenter.heroku.com/articles/config-vars

    Because I didn't do this originally, I made the mistake of replacing all of my env variables with the actual strings which brought about the CORS issue. Mailchimp also deactivated my API key since the key was being published online. So it was actually a layered issue, not exactly a CORS issue, to begin with.