Getting "TypeError: failed to fetch" when the request hasn't actually failed

Amanshu Kataria picture Amanshu Kataria · Mar 18, 2018 · Viewed 115.9k times · Source

I'm using fetch API within my React app. The application was deployed on a server and was working perfectly. I tested it multiple times. But, suddenly the application stopped working and I've no clue why. The issue is when I send a get request, I'm receiving a valid response from the server but also the fetch API is catching an exception and showing TypeError: failed to fetch. I didn't even made any changes to the code and it's the issue with all of the React components.

I'm getting a valid response.

enter image description here

But also getting this error at the same time.

enter image description here

fetch(url)
.then(res => res.json())
.then(data => {
  // do something with data
})
.catch(rejected => {
    console.log(rejected);
});

When I remove credentials: "include", it works on localhost, but not on the server.

I tried every solution given on StackOverflow and GitHub, but it's just not working out for me.

Answer

yugantar picture yugantar · Apr 18, 2018

The issue could be with the response you are receiving from back-end. If it was working fine on the server then the problem could be with the response headers. Check the Access-Control-Allow-Origin (ACAO) in the response headers. Usually react's fetch API will throw fail to fetch even after receiving response when the response headers' ACAO and the origin of request won't match.