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
How to Put an Image File in a JSON Object
How to Remove the Decimal Part from JavaScript Number
Automatic Semicolon Insertion & Return Statements
What Is "Callback Hell" and How and Why Does Rx Solve It
How to Use Nodejs to Open Default Browser and Navigate to a Specific Url
New Line in JavaScript Alert Box
Jqgrid: Change Background Color of Row Based on Row Cell Value by Column Name
What Is the 'Constructor' Property Really Used For
How to Communicate Between Popup.Js and Background.Js in Chrome Extension
Var Name Produces Strange Result in JavaScript
Firefox 'Cross-Origin Request Blocked' Despite Headers
Generate HTML Table from 2D JavaScript Array
Select All Contents of Textbox When It Receives Focus (Vanilla Js or Jquery)
How to Define Setter/Getter on Prototype