javascriptgetfetch-api

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


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 make 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.


Solution

  • This could be an issue with the response you are receiving from the backend. If it was working fine on the server then the problem could be within the response headers.

    Check the value of Access-Control-Allow-Origin in the response headers. Usually fetch API will throw fail to fetch even after receiving a response when the response headers' Access-Control-Allow-Origin and the origin of request won't match.