9

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);
  });
14
  • Is this a CORS request? Commented Jul 21, 2017 at 3:41
  • @hellojeffhall no its a local request
    – Riven
    Commented Jul 21, 2017 at 3:42
  • What is url set to? Commented Jul 21, 2017 at 3:45
  • 1
    What server is being used? There should be more than "type error" logged at a server. What does resp.status log? fetch() should only reach .catch() if a network error occurs. Is your server active and accepting requests? Are you requesting the correct URL? Can you include server type and configuration at text of Question? Commented Jul 21, 2017 at 3:53
  • 2
    @guest271314 thanks btw
    – Riven
    Commented Jul 21, 2017 at 4:12

3 Answers 3

3

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();">
2
  • This was a missing solution for me!
    – paulywill
    Commented Mar 4, 2019 at 18:41
  • and adding function handleClick()
    – paulywill
    Commented Mar 4, 2019 at 18:41
0

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!

0

Before to parse response as JSON, you can check the HTTP status of the response:

fetch("https://example.com/page-not-found")
  .then(resp => resp.status === 200 ? resp.json() : alert(resp.status))
  .then(/*...*/)
  .catch(error => alert(error));

200 is the HTTP status for OK.

Of course, alert() is used here for debug/dev purpose only.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.