Receiving "TypeError: Unable to get" when the request didn't actually fail
P粉083785014
P粉083785014 2023-08-23 17:57:40
0
2
618
<p>I use the fetch API in my React application. The application is deployed on the server and runs fine. I tested it multiple times. However, the app suddenly stopped working and I don't know why. The problem is that when I send the <code>get</code> request, I receive a valid response from the server, but the fetch API also catches the exception and shows <code>TypeError: Failed to fetch</code> . I didn't even make any changes to the code and this is an issue with all React components. </p> <p>I received a valid reply: </p> <p>But I also get this error: </p> <pre class="brush:php;toolbar:false;">fetch(url) .then(res => res.json()) .then(data => { // do something with data }) .catch(rejected => { console.log(rejected); });</pre> <p>When I remove the credentials: "include" it works on localhost but not on the server. </p> <p>I tried all the solutions given on StackOverflow and GitHub but it didn't work for me. </p>
P粉083785014
P粉083785014

reply all(2)
P粉438918323

I know there may be React-specific reasons for this problem, but it came up first in the search results for "Typeerror: Failed to fetch" and I wanted to list all the possible reasons here.

The Fetch spec lists when a TypeError is raised from the Fetch API: https:// fetch.spec.whatwg.org/#fetch-api

The relevant paragraphs as of January 2021 follow. These are excerpts from the text.

4.6 HTTP network acquisition

Populate headers object headers with the given object object:

Method steps sometimes throw type errors:

In the "Body mixin" section, there are multiple ways to raise a TypeError if you use FormData. I'm not listing them here because it would make this answer very long. Relevant paragraphs: https://fetch.spec.whatwg.org/#body-mixin

In the "Request Class" section, the new Request(input, init) constructor is a minefield of potential type errors:

In the Response class:

In the "Getting Methods" section

In addition to these potential issues, there are some browser-specific behaviors that may raise TypeError. For example, if you set keepalive to true and the payload is > 64 KB, you will get a TypeError on Chrome, but the same request will work in Firefox. These behaviors are not documented in the spec, but you can find information about them with a Google search to understand the limits of each option you set in fetch.

P粉701491897

This may be an issue with the response you receive from the backend. If it works fine on the server, then the problem may be in the response headers.

Check the value of Access-Control-Allow-Origin in the response header. Typically, when the Access-Control-Allow-Origin of the response header does not match the request's origin, the fetch API will throw an unfetchable error even if the response is received.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template