I know this issue had been discussed a lot on Stackoverflow but unfortunately I just couldn't find a way to make it work. Long story short, I am building an API using Node JS to that makes a request to MailChimp, and I am calling this API on the client side Vue JS app with Vite. The API works fine with Postman, but it returns Access to XMLHttpRequest at from origin has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
error.
Here is the index js file on the server:
const cors = require('cors')
app.use(cors({ origin: '*' }))
app.use('/v1/crm/leads', require('./src/routes/LeadRoutes'))
Here is my controller method
await addSubscriberToAudience('xxx', req.body.email).then(async (mailchimpID) => {
if (mailchimpID) {
let data = {
references: {
mailchimpID: mailchimpID
}
}
let updatedLead = await Lead.findByIdAndUpdate(lead.id, data, { new: true })
res.status(200).json({ data: updatedLead, message: 'New Lead Created Successfully' })
} else {
console.log('Null Mailchimp ID')
}
})
Here is how I call it from the frontend:
axios.post(APIURL + '/v1/crm/leads/create', data, {
headers: { 'X-ORIGIN': 'https://example.com' }
}).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error.message)
})
I can see Access Allow Origin is set in the response header in the preflight response:
Backend is hosted on AWS Elastic Beanstalk and frontend is hosted on AWS S3 Bucket Any help is needed please, and thank you!
Edit 1: I am making other POST API calls from the website to my backend server, they all work fine. Only this one is not working, and the difference is that, after I make the call from client side to the server, server calls Mailchimp API, and then waiting on response from Mailchimp API before return a success response to my frontend, hope this context helps