1

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

I finally figured it out!! Actually it's the origin link I set in cors. I set the origin to http://localhost:3000/. But interestingly the client origin (also http://localhost:3000/) didn't match the origin in the server. But when I changed the server cors origin to http://localhost:3000, removing the '/' from the origin fixed the issue. I don't know why it didn't worked but I am glad it did. Now I need explanation why it worked. Is it something to do with specific route? Like adding the '/' makes it so that only the 'Home' route would work?