Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS fetch TypeError: Failed To Fetch

Tags:

javascript

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);
  });
like image 579
Riven Avatar asked Jul 21 '17 03:07

Riven


People also ask

What is the meaning of Failed to fetch?

When you see an error saying "Failed to fetch" or get an ICE error this means that there is a connectivity issue between you and Lookback. Typically this is related to a firewall blocking your connection in some way.

How define fetch in JavaScript?

The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.

Is fetch available in JavaScript?

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

What is no-CORS mode?

no-cors. Prevents the method from being anything other than HEAD , GET or POST , and the headers from being anything other than simple headers. If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers.


1 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();">
like image 113
cwingrav Avatar answered Oct 15 '22 11:10

cwingrav