I have a REST API hosted on Heroku. It consists of Express, NodeJS and MongoDB(mongoose as orm and MongoDB Atlas as well). I am using MERN stack. Beginner here
The API Link:
<a href="https://mern-deploy-test-adib.herokuapp.com/api/todos">/api/todos</a>
The API works just fine with Postman and VS code's API plugin. It also works perfectly fine on the localhost.
But when I try to GET/POST using axios, it gives:
Error: "Network Error"
But fetch()
works just fine. So does Postman.
Also the I see cors warning in the console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://mern-deploy-test-adib.herokuapp.com/api/todos. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://localhost:3000/’)
but I set the cors like so:
app.use(cors({ origin: 'http://localhost:3000/', credentials: true }))
Interestingly the API worked in localhost but after deploying it doesn't work with axios.
I have set cors origin: 'http://localhost:3000/'
And I checked the headers of both the fetch and axios GET request. They are literally the same.
The request header has Access-Control-Allow-Origin http://localhost:3000/
BTW my frontend is hosted on localhost:3000
So why is this happening? Why is axios not working but fetch is.
Edit: here's the code for both 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 an axios request using an editor on my phone (SPCK editor). The request was successful. I just don't get why it's not working from my pc.