Меню

Что значит ошибка failed to fetch

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.

To append a name/value name/value pair to a Headers object (headers), run these steps:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If headers’s guard is «immutable», then throw a TypeError.

Filling Headers object headers with a given object object:

To fill a Headers object headers with a given object object, run these steps:

  1. If object is a sequence, then for each header in object:
    1. If header does not contain exactly two items, then throw a TypeError.

Method steps sometimes throw TypeError:

The delete(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. If this’s guard is «immutable», then throw a TypeError.

The get(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. Return the result of getting name from this’s header list.

The has(name) method steps are:

  1. If name is not a name, then throw a TypeError.

The set(name, value) method steps are:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. 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.

The clone() method steps are:

  1. 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.

The clone() method steps are:

  1. 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.

Ошибка error 503 backend fetch failed знакома людям, которые постоянно используют свою технику для выхода в Интернет. При этом, важно отметить, что подобная неприятность может проявиться абсолютно на любой операционной системе и на любом устройстве, позволяющим осуществлять подобные операции. То есть, это может быть ноутбук на Линукс, стационарный компьютер с Виндовс, мобильный телефон или планшет с иной системой.

Что делать с error 503 backend fetch failed и как исправить

Естественно, для того, чтобы понять, как исправить error 503 backend fetch failed, необходимо изначально понять первопричины, способствующие проявлению подобной ситуации.

Что за ошибка и почему проявляется

К сожалению, но перевод error 503 backend fetch failed совершенно не упрощает поиск оптимального разрешения проблемы, так как даже онлайн-переводчик не способен полностью обработать данную фразу.

Тем не менее, специалисты и обычные пользователи уже выявили основные причины возникновения такой ситуации и почему она проявляется. Ошибка с этим кодом связана с обращением к удаленному серверу, который, вроде бы, обрабатывает запрос, но, по каким-либо причинам, не способен на него ответить.

Чаще всего это связано со следующими нюансами:

  • При попытке запуска онлайн-приложения происходят кратковременные сбои.
  • Серверу недостаточно собственной памяти для обработки поступающей информации.
  • Количество одновременно сделанных запросов слишком высоко и их банально не вытягивают мощности удаленного сервера.
  • Владелец сайта решил заняться техобслуживанием своего интернет-ресурса.
  • Срок действия сертификата SSL подошел к концу.

То есть, фактически всегда эта ситуация проявляется из-за каких-либо факторов, непосредственно связанных с функциональным состоянием удаленного ресурса, на который хочет зайти юзер.

Методика лечения

Итак, что делать – error 503 backend fetch failed?

К сожалению, но от обычного человека в таком случае мало чего зависит.

Тем не менее, кое-что можно опробовать:

  1. Обновить проблемную страничку с помощью кнопки «F5» или заново ввести урл-адрес. Может быть произошел кратковременный сбой.
  2. Вернуться к попытке осуществить доступ через какой-то промежуток времени. Вполне возможно, что через несколько минут или часов на другом конце соединения неприятность будет устранена.
  3. Стараться заходить на такие веб-сайты в то время, когда осуществляется минимальное число переходов иных пользователей.
  4. Выполнить перезапуск оборудование и устройства, отвечающего за доступ к Сети.
  5. Найти контактные данные проблемного сервера или интернет-ресурса и написать им сообщение о возникающей ситуации, чтобы служба технического ремонта была в курсе таких проблем.
  6. Временно перейти на использование бесплатных DNS-серверов, информацию о которых можно легко найти в интернет-поиске.

Естественно, такая методика не гарантирует стопроцентного положительного результата. Тем не менее, иногда, она способна оказаться эффективным решением возникшего вопроса. В качестве альтернативного метода можно попробовать поискать требуемую человеку информацию на иных сетевых ресурсах, если проблема на нужном сайте, в течении длительного периода времени, не исчезает.

@bymoe

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!!!

error

@greg-db

We’ll be happy to help with any issues you’re having with the Dropbox API/SDK, but we’ll need some more information. Can you please share:

  • the name and version number of the platform where you’re running this
  • the version number of the Dropbox JavaScript SDK you’re using
  • the steps to reproduce the issue, including relevant code snippet(s)

@phil294

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.

@greg-db

@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.

@phil294

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

message: "Failed to fetch",
stack: "TypeError: Failed to fetch"

object. This is also the case with v8.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.

@bymoe

@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!

@greg-db

@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.

@bymoe

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.

const dbx = new Dropbox({
  clientId: `${process.env.REACT_APP_DROPBOX_CLIENT_ID}`,
  accessToken: `${process.env.REACT_APP_DROPBOX_ACCESS_TOKEN}`,
  pathRoot: '{".tag": "namespace_id", "namespace_id": "####"}',
  selectUser: `${process.env.REACT_APP_DROPBOX_SELECT_USER}`, 
});

Not sure what’s wrong.
error

@greg-db

@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.

@ridvankartal

Hi,

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:

async function main() {
    const Dropbox = require('dropbox').Dropbox;
    const dropbox = {
        dbx: new Dropbox({
            accessToken: process.env.ACCESS_TOKEN,
            pathRoot: JSON.stringify({ '.tag': 'namespace_id', 'namespace_id': process.env.NAMESPACE_ID })
        })
    };
    const payload = {
        path: '',
        recursive: true,
        include_media_info: false,
        include_deleted: false,
        include_has_explicit_shared_members: true,
        include_mounted_folders: true,
        include_non_downloadable_files: true
    };

    let hasMore = true;
    let entries = [];
    let response;
    let cursor;

    while (hasMore) {
        try {
            if (cursor) {
                response = await dropbox.dbx.filesListFolderContinue({ cursor: cursor });
            }
            else {
                response = await dropbox.dbx.filesListFolderGetLatestCursor(payload);

                response = await dropbox.dbx.filesListFolderContinue({ cursor: response.result.cursor });

            }

            console.info('Entries: ', JSON.stringify(response.result.entries));

            cursor = response.result.cursor;
            entries = entries.concat(response.result.entries);
            hasMore = response.result.has_more;
        }
        catch (error) {
            console.info(error);
            return error;
        }
    }
}

main();

Error log:

2022-01-20T08:22:18.579Z	67caa239-e75c-46ce-be4c-0fcf6c154694	INFO	FetchError: request to https://api.dropboxapi.com/2/files/list_folder/continue failed, reason: connect ETIMEDOUT 162.125.4.19:443
    at ClientRequest.<anonymous> (/var/task/node_modules/dropbox/node_modules/node-fetch/lib/index.js:1483:11)
    at ClientRequest.emit (events.js:400:28)
    at TLSSocket.socketErrorListener (_http_client.js:475:9)
    at TLSSocket.emit (events.js:400:28)
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  type: 'system',
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT'
}

@greg-db

@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.

Многие пользователи iPhone, iPad и iPod Touch, получившие джейлбрейк iOS 7 столкнулись с со следующей проблемой — некоторые репозитории, ранее доступные в Cydia, стали недоступны, а в процессе обновления пакетов, появлялись сообщения об ошибках доступа.

Cydia на iPhone 5s джейлбрейк

Одна из них – «Failed to fetch […] HTTP/1.1 404 Not Found».  Исправляется эта ошибка довольно просто.

«404 Not Found» — один из стандартных кодов ответа HTTP сервера. Он сигнализирует, что клиентская программа пользователя, к примеру, веб-браузер, не может подсоединиться к серверу. В большинстве случаев, эта ошибка никак не влияет на работу сервиса, однако магазин выдаёт это предупреждение и у некоторых может сложиться впечатление, что Cydia работает нестабильно.

На самом же деле, в данном случае, этот код ошибки говорит лишь о том, что есть проблемы с доступом к репозиторию UltraSn0w. Для того что бы избавиться от назойливого собщения, достаточно в настройках выключить репозиторий Dev Team, в котором находится популярный в прошлом твик для разлочки iPhone — UltraSn0w. Для iPhone 4 и выше этот источник не имеет какой-либо практической ценности. Его можно, без риска для работы всего приложения, удалить. Твик Ultrasn0w, при необходимости, можно найти и в других репозиториях.

Для того, что бы отключить источник приложений, в данном случае Dev Team (repo666.ultrasn0w.com), в приложении Cydia, вам потребуется выполнить несколько простых операций.

Откройте Cydia -> Manage -> Sources -> Edit, и отключите (удалите) источник Dev Team, имеющий адрес repo666.ultrasn0w.com.

удалить репозиторий в CydiaСмотрите также:

  • Как изменить надпись Разблокируйте на iPhone и iPad с iOS 7 (джейлбрейк).
  • Твики из Cydia, работающие на iOS 7.
  • Скачать Evasi0n 7 1.0.1 — обновленное приложение для джейлбрейка iOS 7 от Evad3rs.
  • Как открыть скрытые настройки iOS 7 после джейлбрейка.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ятрогенная патология врачебные ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Что значит ошибка е16 на принтере canon