'CORS policy - MERN app on heroku and netlify

I just deployed my first MERN stack app on Heroku and Netlify. Everything seems to be working normally, fetching and showing data like it did on localhost.

Strange thing that happens is that when I try to update my object (using axios.put), nothing happens for 30-ish seconds (status says "pending" in my network requests) and then the error pops up:

"Access to XMLHttpRequest at 'https://mern-stack-tonid.herokuapp.com/own/61e5beb60b4c9d6b17b00518' from origin 'https://goofy-montalcini-bc7ff5.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Maybe even stranger (to me at least, I'm still new to this) is that as soon as I refresh the page, no matter if status is still pending or the error appeared, the change is made and I can see in MongoDB that the change has been made.

In my backend I used app.use(cors({ origin: "https://goofy-montalcini-bc7ff5.netlify.app", }));

as well as app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); next(); });

and I included res.header('Access-Control-Allow-Origin', '*'); inside every call to api.

On the client side, inside package.json, i set "proxy": "https://mern-stack-tonid.herokuapp.com"

Thank you in advance, the answer is probably very simple but as I said it's my first time deploying MERN stack app



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source