'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)
}
}
})
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
