Getting "Typeerror: Failed to Fetch" When the Request Hasn't Actually Failed

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

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.

TypeError: Failed to fetch & Cannot read properties of undefined

Found a solution for this. What was happening behind the scenes was that the webpage was refreshing when the "submit" button was clicked, due to the default event associated to the submission of forms. That's why my network requests "vanished" in the Network tab of Chrome Dev Tools.

I proceeded to edit the render of the form by returning:

<div>
<form onSubmit={(event) => { event.preventDefault(); } }>
<label htmlFor="gamertag">Xbox Live Gamertag:</label>
<input type="search" id="search-recent-matches" name="Gamertag" placeholder="Enter a Gamertag..."></input>
<button type="submit" onClick={ this.fetchHaloMatches } >Search</button>
</form>
</div>

As you can see, I had to call the .preventDefault() method. Since window.event is now deprecated, I found out that the onSubmit attribute returns the event (class Event) associated to the submission. I could then call the .preventDefault() method on that specific event, preventing the refresh. Remember to declare the submission button as type="submit" or this won't work.

TypeError: Failed to execute 'fetch' on 'Window': 1 argument required, but only 0 present

Your call to fetch is incorrect , you need to set the required argument which is the endpoint link as first argument :

const response = await fetch(urlToFetch) 

Also , it is a good habit to set the second argument which is an object that includes the method ( GET , POST ... ) , headers ( api key ... ) ...



Related Topics



Leave a reply



Submit