P粉4389183232023-08-24 16:31:57
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粉7014918972023-08-24 14:39:30
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.