I recently set up a REST API on Heroku using Express, NodeJS, and MongoDB (mogoose as orm and MongoDB Atlas as well). I am diving into the world of MERN stack development as a beginner 😅
If you want to check out the API, here's the link:
<a href="https://mern-deploy-test-adib.herokuapp.com/api/todos">/api/todos</a>
Everything seemed to be working smoothly with Postman and VS code's API plugin, as well as when accessing the API from localhost.
However, I encountered an issue when trying to GET/POST using axios, which resulted in the following error:
Error: "Network Error"
It's interesting to note that fetch()
works without any problems, just like Postman.
Additionally, I noticed a CORS warning in the console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://localhost:3000/’)
Even though I set the CORS like this:
app.use(cors({ origin: 'http://localhost:3000/', credentials: true }))
Strangely enough, the API worked perfectly on localhost but started facing issues with axios after deployment.
I made sure to set
cors origin: 'http://localhost:3000/'
And I compared the headers of both the fetch and axios GET requests. Surprisingly, they are identical.
The request header includes
Access-Control-Allow-Origin http://localhost:3000/
By the way, my frontend is hosted on localhost:3000
So, why is axios failing while fetch is successful?
Edit: Here is the code for both the axios and fetch request.
//fetch
fetch(`https://heroku-api-link/api/todos`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err))
//axios
axios.get(`https://heroku-api-link/api/todos`)
.then(data => console.log(data))
.catch(err => console.log(err))
EDIT #2: I tried sending an axios request using an editor on my phone (SPCK editor), and the request was successful. I can't figure out why it's not working when I try from my PC.