Getting "TypeError: Failed to fetch" when the request hasn't actually failed
I’m using fetch API within my React app. The application was deployed on a server and was working perfectly. I tested it multiple times. But, suddenly the application stopped working and I’ve no clue why. The issue is when I send a get request, I’m receiving a valid response from the server but also the fetch API is catching an exception and showing TypeError: Failed to fetch . I didn’t even make any changes to the code and it’s the issue with all of the React components.
I’m getting a valid response:

But also getting this error at the same time:

When I remove credentials: "include", it works on localhost, but not on the server.
I tried every solution given on StackOverflow and GitHub, but it’s just not working out for me.
![]()
13 Answers 13
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.
I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.
The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api
Relevant passages as of January 2021 are below. These are excerpts from the text.
4.6 HTTP-network fetch
To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
.
16. Run these steps in parallel:
.
2. If aborted, then:
.
3. Otherwise, if stream is readable, error stream with a TypeError.
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If headers’s guard is "immutable", then throw a TypeError.
Filling Headers object headers with a given object object:
- If object is a sequence, then for each header in object:
- If header does not contain exactly two items, then throw a TypeError.
Method steps sometimes throw TypeError:
- If name is not a name, then throw a TypeError.
- If this’s guard is "immutable", then throw a TypeError.
- If name is not a name, then throw a TypeError.
- Return the result of getting name from this’s header list.
- If name is not a name, then throw a TypeError.
- Normalize value.
- If name is not a name or value is not a value, then throw a TypeError.
- If this’s guard is "immutable", then throw a TypeError.
To extract a body and a Content-Type value from object, with an optional boolean keepalive (default false), run these steps:
.
5. Switch on object:
.
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven’t listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin
In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:
The new Request(input, init) constructor steps are:
.
6. If input is a string, then:
.
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
.
11. If init["window"] exists and is non-null, then throw a TypeError.
.
15. If init["referrer" exists, then:
.
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
.
18. If mode is "navigate", then throw a TypeError.
.
23. If request’s cache mode is "only-if-cached" and request’s mode is not "same-origin" then throw a TypeError.
.
27. If init["method"] exists, then:
.
2. If method is not a method or method is a forbidden method, then throw a TypeError.
.
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
.
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is GET or HEAD , then throw a TypeError.
.
38. If body is non-null and body’s source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
.
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.- If this is disturbed or locked, then throw a TypeError.
In the Response class:
The new Response(body, init) constructor steps are:
.
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
.
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
.The static redirect(url, status) method steps are:
.
2. If parsedURL is failure, then throw a TypeError.- If this is disturbed or locked, then throw a TypeError.
In section "The Fetch method"
The fetch(input, init) method steps are:
.
9. Run the following in parallel:
To process response for response, run these substeps:
.
3. If response is a network error, then reject p with a TypeError and terminate these substeps.In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you’ll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren’t documented in the spec, but you can find information about them by Googling for limitations for each option you’re setting in fetch.
Typeerror failed to fetch – How to Fix TypeError: Failed to fetch and CORS in JavaScript?
Typeerror failed to fetch: The “TypeError: Failed to fetch” error can arise for several reasons:
- Passing an incorrect or incomplete URL to the fetch() method.
- The server to which you are making a request does not return the correct CORS headers.
- The URL has an incorrect protocol.
- Passing a wrong method or headers to the fetch() method.
Let us see the examples to know how this error occurs and try to fix them.
Explanation:
Since the URL we passed to the fetch method was incorrect, we received two errors:
- CORS: No ‘Access-Control-Allow-Origin’ header is present on the requested resource
- TypeError: Failed to fetch
Fixing “TypeError: Failed to fetch” Error
Typeerror: failed to fetch: Check that the URL that you are passing to the fetch() method is complete and valid. Do the following for this:
- Include the protocol, for example, https:// or http:// if you are testing on localhost without an SSL certificate.
- The URL path must be correct, for example, /btechgeeks.
- The HTTP method must be appropriate for the path specified.
- If you misspell any of the configuration, such as a property in the headers object or an HTTP method, you will receive an error.
To resolve the «TypeError: Failed to fetch,» ensure that the correct configuration is sent to the fetch method, including the URL, HTTP method, headers, and that the server to whom you are making a request is setting the necessary CORS headers with the response.
NOTE:
If the configuration that you pass to the fetch method is correct, check to see if your server is sending the correct/valid CORS headers in the response.
Along with the response, the server must set the following CORS headers:
Depending on your use case, you may need to adjust the values, by opening the Network tab in your browser, clicking on the request, and seeing if your server is setting these CORS-related headers.
The headings are as follows:
Access-Control-Allow-Origin: It specifies which origins are permitted/allowed to make requests to the server.
Access-Control-Allow-Methods: It specifies which HTTP methods the origins are permitted to use when making requests to the server.
Access-Control-Allow-Headers: It specifies which HTTP headers origins are permitted to use when making requests to the server.
Способы устранения ошибки 503: сбой бэкэнд-выборки
«Что означает« Ошибка 503 при загрузке серверной части »? Уведомление отображается, когда я пытаюсь посетить веб-страницу в моем браузере ».
Вам знаком этот сценарий? Продолжайте читать, если вам нужно решить эту проблему.
Что такое ошибка 503 Backend Fetch Fetch?
Сообщение «Ошибка 503: сбой выборки из бэкенда» — это сообщение об ошибке ответа протокола передачи гипертекста (HTTP). Вы можете столкнуться с ним независимо от используемого устройства, операционной системы или браузера. Это связано с веб-сайтом, который вы пытаетесь посетить. Это означает, что сервер неисправен и не отвечает должным образом. Ошибка возникает, когда сервер веб-сайта получает больше запросов, чем он может обработать за раз.
Когда вы пытаетесь посетить веб-сайт, но он не отвечает или делает это с очень медленной скоростью, запросы выстраиваются в очередь, что сервер может не справиться. Это может привести к тому, что кеш-память вашего браузера будет занята, что впоследствии приведет к ошибке бэкэнд-выборки.
Причины «Ошибка 503 сбой выборки из бэкэнд»:
- Низкая скорость Интернета: проблемы с подключением к сети или низкая скорость Интернета являются основной причиной, по которой вы можете столкнуться с ошибкой 503 в своем браузере. Веб-сайт загружается слишком долго или не загружается, что приводит к накоплению запросов. Затем данные веб-сайта накапливаются в памяти кеш-сервера, что приводит к ошибке «Ошибка при извлечении из серверной части».
- Сервер веб-сайта находится на обслуживании: если сервер веб-сайта, который вы пытаетесь посетить, находится на плановом / временном обслуживании, ваши запросы будут помещены в очередь, и вы получите ошибку 503 в своем браузере.
- Веб-сайт был признан подозрительным и заблокирован: если в вашем браузере активен блокировщик рекламы, и вы пытаетесь посетить веб-сайт, на котором много рекламного контента, он предотвратит загрузку такого контента. По этой причине запросы накапливаются и приводят к обсуждаемой ошибке. Другие инструменты безопасности в вашем браузере также предотвращают загрузку подозрительных веб-сайтов, что приводит к ошибке, с которой вы столкнулись.
Как устранить ошибку 503: сбой выборки из бэкэнд
Большой! Вы зашли так далеко. Давайте теперь рассмотрим вопрос, который привел вас к этому руководству.
Как исправить ошибку 503: сбой при загрузке бэкэнд? Вот решения:
- Обновите веб-страницу
- Закройте несколько вкладок
- Попробуйте другой браузер
- Перезагрузите WiFi роутер
- Запустите надежный инструмент для обслуживания ПК
- Сбросьте ваш браузер
- Свяжитесь с администратором сайта
Мы возьмем их по одному.
Исправление 1. Обновите веб-страницу
Естественно, первое, что вы сделаете, когда веб-сайт не загружается, — это нажмите кнопку «Обновить». Итак, если вы столкнулись с ошибкой 503 бэкэнд-выборки, имеет смысл обновить веб-страницу. Если вы сделаете это достаточно много раз (по крайней мере, два или три раза), вы сможете обойти ошибку. Однако, если это не сработало для вас, переходите к следующему исправлению.
Исправление 2: Закройте несколько вкладок
Попробуйте закрыть другие активные вкладки в браузере, чтобы снизить нагрузку на кеш-память. Это также может помочь повысить скорость вашего интернета, если она недостаточно высока.
Исправление 3: попробуйте другой браузер
Если в вашем браузере в фоновом режиме выполняется несколько процессов, это может снизить скорость просмотра и вызвать ошибку 503. Или, возможно, в вашем браузере есть настройки, препятствующие загрузке веб-страницы. Попробуйте использовать другой браузер для посещения веб-сайта и посмотрите, загрузится ли он.
Исправление 4: перезагрузите WiFi-роутер
Это хорошее исправление, особенно если вы получаете сообщение «Ошибка бэкэнд-выборки: ошибка 503» на нескольких веб-сайтах. У вас могут быть проблемы с подключением к Интернету, которые можно решить, перезагрузив маршрутизатор.
Закройте браузер и перезагрузите компьютер. Затем выключите маршрутизатор и подождите примерно полминуты, прежде чем снова его включить. Перезапустите браузер и попробуйте снова посетить веб-сайт. Посмотрите, была ли устранена ошибка.
Исправление 5: Запустите средство обслуживания доверенного ПК
Как упоминалось ранее, низкая скорость интернета — одна из основных причин рассматриваемой ошибки. Это может иметь какое-то отношение к настройкам подключения к Интернету на вашем компьютере. Вы можете решить эту проблему автоматически с помощью Auslogics BoostSpeed. Инструмент был разработан разработчиком приложения Microsoft Silver, ему доверяют и рекомендуют эксперты по всему миру. BoostSpeed запускает сканирование, чтобы обнаружить все неоптимальные настройки на вашем компьютере. Затем, используя точные методы, он настраивает их для обеспечения максимальной производительности.
Исправление 6: сбросьте настройки браузера
Сброс настроек браузера — это разумный вариант действий, если большинство посещаемых вами веб-сайтов выдают в вашем браузере сообщение «Ошибка 503: сбой при загрузке серверной части», но загружаются успешно, когда вы загружаете их с помощью другого устройства или другого браузера.
Как мне избавиться от ошибки 503 в Chrome?
Выполните следующие действия, чтобы сбросить настройки браузера Chrome, если веб-сайты продолжают выдавать ошибку 503:
- Запустите браузер Chrome.
- Щелкните значок «Еще», отображаемый в виде трех вертикальных точек в правом верхнем углу окна. Раскроется раскрывающееся меню.
- Щелкните «Настройки».
- Прокрутите страницу вниз и щелкните стрелку вниз рядом с полем «Дополнительно», чтобы развернуть меню.
- Прокрутите вниз до раздела «Сброс и очистка» (если вы используете Chrome в операционной системе Windows). Если вы используете Chrome на Chromebook, Linux или Mac OS, прокрутите вниз до раздела «Сбросить настройки».
- Нажмите на опцию «Восстановить исходные настройки по умолчанию».
- В открывшемся диалоговом окне вы можете установить флажок «Помогите улучшить Chrome, сообщив о текущих настройках». Затем нажмите кнопку «Сбросить настройки».
- Перезапустите браузер и посмотрите, устранена ли ошибка.
Имейте в виду, что сброс означает восстановление настроек вашего браузера по умолчанию. Ваши закладки, история просмотров и сохраненные пароли не будут удалены, но следующие изменения вступят в силу на всех устройствах, на которых вы вошли в систему:
- Если вы выбрали другую поисковую систему в качестве поисковой системы по умолчанию, она будет снова изменена на Google.
- Ваши закрепленные вкладки будут удалены.
- Настройки контента, такие как разрешение веб-сайту использовать ваш микрофон или показывать всплывающие окна, будут сброшены.
- Файлы cookie и данные сайта будут сброшены.
- Расширения браузера отключаются. Если вы хотите снова включить их после сброса, перейдите в меню браузера и нажмите «Дополнительные инструменты»> «Расширения».
- Тема вашего браузера будет сброшена.
Исправление 7. Обратитесь к администратору веб-сайта
Если вы дошли до этого момента, не исправив ошибку, единственный вариант, который у вас остался, — это связаться с администратором проблемного веб-сайта и сообщить им об ошибке. Таким образом, вы также можете узнать, находится ли сервер сайта на техническом обслуживании и когда он снова будет доступен.
Мы надеемся, что наше руководство по исправлению ошибки «Ошибка 503: сбой серверной загрузки» было для вас полезным. Не забудьте заглянуть в наш блог, чтобы получить более содержательные советы по решению проблем с Windows.
What does error message «Failed to fetch» mean? #415
Every single day I get Failed to fetch generic error message when using the upload files v2 api.
What do I benefit from such generic message?
I cannot even debug the issue or know what’s wrong, It happens so randomly from time to time.
The text was updated successfully, but these errors were encountered:
I also rarely get the error message Failed to fetch in our logs as the only response from a call to filesListFolder . (^5.2.1 on web, Chrome) I dont know what status code it returns though. Might also be a console.error() . No idea whats going on or how to handle this. I should probably upgrade though.
@phil294 We haven’t heard back from the original poster here, and we don’t know exactly what the cause of this is. If you can share some way for us to reproduce it though, we’ll look into it. In any case, we do recommend upgrading to the latest version of the SDK.
I actually just now found the reason in my case: When the site is offline, a call like x = await filesListFolder(. ) fails with a simple
object. This is also the case with v 8.2.0 . I’ll now just do a try < . >catch(e) < if(e.message === 'Failed to fetch') < /* show network error to the user */ >> . Thanks for your help and I hope this will help someone else.
@greg-db I’m not sure how can I re-produce the error because I cannot myself, I have pretty much this setup on my App and the error is totally random, I just don’t know what the error is or where it happen.
But as @phil294 mentioned my App is fully PWA (https://app.replayed.co), and I always show network error to the user. In my case the error is happen after couple fetches so it’s not like there’s connection at all or the user access the page immediately from offline. It happens like 50% of the time, It’s getting annoying. I’m not sure what to do!
@ImSolitude Thanks for following up. Unfortunately if we can’t reproduce the issue here, it’s unlikely we’ll be able to offer much help.
To clarify though, since your app is a PWA, it seems the API calls are made client-side on your users’ devices (and you’re just seeing the error report). Is that correct? Given that you can’t reproduce it yourself, and since Philip mentioned this can happen when offline, it may indicate that it happens when the user has even just an unreliable connection, if not completely offline.
Hey @greg-db, An update to this, We checked the sentry issues and it was filled with this error,
TypeError: Failed to execute ‘fetch’ on ‘Window’: Illegal invocation , We’re using dropbox: 8.1.0 , and we’re not passing any custom fetcher to the Dropbox constructor.
Not sure what’s wrong.
@ImSolitude Thanks for the information. From that code, it looks like you’re using this in a React app. This SDK doesn’t officially support React unfortunately, but I’ll pass this along as a feature request. I can’t promise if or when that might be implemented though.
I have same fetch error problem. I have a node.js app which runs on AWS Lambda. The Lambda is connected with a VPC. It goes internet with a static IP. I use v10.23.0 dropbox-sdk-js. It always seems to run on my local but It sometimes runs on lambda, sometimes gets fetch error.
My code like this:
@ridvankartal It looks like you’re not getting the exact same error as originally reported in this thread. The original reports were about a generic «Failed to fetch» error, but you’re getting an «ETIMEDOUT» error. Anyway, I’ll reply on your forum thread. By the way, for future reference, it is not necessary to post the same issue in multiple places.