JS fetch TypeError: Failed To Fetch

Viewed 7983

Whenever i tried to fetch it returned an error TypeError:failed to fetch others solution doesnt to work for me. Here's my code

fetch(url)
  .then((resp) => resp.json())
  .then((data) => {
     this.JSONData = data;
  })
  .then(() => {
     this.search()
  }) 
  .catch(error => {
     alert(error);
  });
2 Answers

Is the page reloading before this completes due to async? This can happen in some callbacks that don't return false.

In your code, since resp.json() is async, the function the fetch is in will return before the fetch completes, but it will have enough time to start the fetch. If this is in an 'onSubmit' for example, if the function returns a non-false value, the page reloads, interrupting your fetch. When the first then is encountered (which is async as well), it errors.

To fix,

<form onsubmit="myFunctionWithFetch(); return false;">
... or return false in your function and do ...
<form onsubmit="return myFunctionWithFetch();">

If you're using Swagger and you have an ad blocker, make sure to disable the ad blocker. I ran into this testing my ASP.NET Core site with Swashbuckle. Kept getting an instant failure. Disabled the ad-blocker for my dev site and it started working. Hope that helps!

Related