Ошибка networkerror when attempting to fetch resource

My feeling is that it may not be related to CORS. It may have to deal with the «import» mechanism(?)
Here is my case: I got a «Source map error» message when I just updated my local version of OpenLayers to v5.0.0. Here is my html:

<!DOCTYPE html>
<html>
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Lignes SNCF</title>
  <link rel="stylesheet" href="sncf.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/5.0.0/ol.css">
  <link rel="preload" href="Gares.json">
  <link rel="preload" href="communes.geojson">
  <script src="../../../ENSEIGNEMENT/v5.0.0-dist/ol.js"></script>
</head>
<body>
  <h1>Lignes SNCF</h1>
  <div id="canvasMap" class="map"><div id="popup"></div></div>
  <script src="./sncfV5.js"></script>
</body>
</html>

and the error message:

Source map error: TypeError: NetworkError when attempting to fetch resource.
Resource URL: file:///E:/ENSEIGNEMENT/v5.0.0-dist/ol.js
Source Map URL: ol.js.map[Learn More]

Puzzlingly, the JavaScript code works correctly, and the map correctly displays on screen, even before the «Source map error» message on console.

If I turn back to the previous version of OpenLayers, only difference:

<script src="../../../ENSEIGNEMENT/v4.6.5-dist/ol.js"></script>

it works also, but with no error message.

I do not see what to blame … but Openlayers 5 is the first release intended to be used with «import … from ‘ol'». What I didn’t try yet (other issues), I am still using:

const map = new ol.Map(...);

instead of:

import Map from 'ol.Map.js';
const map = new Map(...);

I don’t know what to blame, but the original question from «Suresh» has also something to do with the «import» mechanism. I my case I cannot see the point with CORS.

NetworkError when attempting to fetch resource is a common error that occurs when you’re trying to fetch data from a server using the Fetch API or XMLHttpRequest. This error can be caused by various reasons, such as incorrect URL, server-side issues, or CORS restrictions.

In this guide, we’ll walk you through the step-by-step process of troubleshooting and fixing the NetworkError when attempting to fetch a resource.

Table of Contents

  • Step 1: Verify the URL
  • Step 2: Check the Server Status
  • Step 3: Inspect CORS Configuration
  • Step 4: Analyze Network Conditions
  • Step 5: Debug Fetch Request
  • FAQs

Step 1: Verify the URL

The first step in troubleshooting the NetworkError is to verify that the URL you’re trying to fetch is correct. Ensure that the URL is well-formed and points to the correct resource.

const url = 'https://api.example.com/data';
fetch(url)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('NetworkError:', error));

If the URL is incorrect or points to a non-existent resource, update it to the correct one.

Step 2: Check the Server Status

The NetworkError may also occur due to server-side issues. To check if the server is up and running, you can use tools like Down For Everyone Or Just Me or Is It Down Right Now?.

If the server is down, wait for it to be back online or contact the server administrator to resolve the issue.

Step 3: Inspect CORS Configuration

Cross-Origin Resource Sharing (CORS) is a security feature that restricts web pages from making requests to a different domain than the one that served the web page. If the server hosting the resource doesn’t have the proper CORS configuration, you’ll encounter the NetworkError.

To fix CORS issues, you can either:

Update the server’s CORS configuration to allow requests from the origin making the request. This is the recommended solution for production environments. More information on configuring CORS can be found in the Mozilla Developer Network documentation.

Use a proxy server to bypass CORS restrictions during development. Tools like CORS Anywhere or CORS Proxy can help with this.

Step 4: Analyze Network Conditions

Poor network conditions can also cause the NetworkError. To check if this is the issue, test your internet connection using tools like Speedtest or Fast.com.

If you’re experiencing network issues, try connecting to a different network or wait for the network conditions to improve.

Step 5: Debug Fetch Request

Finally, if none of the above steps resolve the issue, you can debug the fetch request to identify the root cause of the problem. To do this, you can use browser developer tools like Chrome DevTools or Firefox Developer Tools.

Some common debugging techniques include inspecting network requests, checking console logs, and analyzing request headers and response headers.

FAQs

1. Can I use XMLHttpRequest instead of Fetch API to avoid NetworkError?

No. The NetworkError can also occur when using XMLHttpRequest. The error is not specific to the Fetch API. The troubleshooting steps outlined in this guide apply to both Fetch API and XMLHttpRequest.

2. Is there a way to bypass CORS restrictions on the client-side?

Bypassing CORS restrictions on the client-side is not recommended, as it can lead to security vulnerabilities. The proper way to handle CORS issues is to configure the server to allow requests from the required origins.

3. How can I check if the server has the correct CORS configuration?

You can use tools like CORS Tester or CORS Check to test if the server has the correct CORS configuration.

4. What other APIs can I use to fetch data from a server?

You can also use APIs like Axios or jQuery.ajax() to fetch data from a server. However, these APIs may also encounter the NetworkError if the underlying issues are not resolved.

5. How can I handle NetworkError in my code?

You can use the catch block in your fetch request to handle the NetworkError and display a user-friendly error message or take other appropriate actions.

fetch(url)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    console.error('NetworkError:', error);
    // Display error message or take other actions
  });

Back to top

Делаю вот такой запрос:

const fetchArticlesConstitution = async () => {
        try {
            const res = await fetch('/api/main/block', {
                method: 'GET',
                headers: {
                    'X-Requested-With':'XMLHttpRequest'
                },
            });

            const articlesConstitution = await res.json();

            dispatch({
                type: 'FETCH_ARTICLE_CONSTITUTION',
                payload: articlesConstitution
            });
        } catch (e) {
            console.log('Ошибка', e);
            throw error
        }
    };

Почему, обычно при первой загрузке, выдает ошибку TypeError: «NetworkError when attempting to fetch resource.» Иногда все нормально и все загружается иногда нет.
Подскажите плиз что это за ошибка, почему она возникает и как ее решить. Заранее спасибо!

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

1 26.08.2021 15:10:24

  • Александр
  • Новый участник
  • Неактивен
  • Зарегистрирован: 26.08.2021
  • Сообщений: 4

Тема: Ошибка NetworkError when attempting to fetch resource.

Установил систему для ознакомления и тестирования на локальном сервере (с доменной зоной .local).
Два дня было все нормально. Все работало без сбоев.
Сейчас при попытке добавить товар в корзину стала появляется ошибка NetworkError when attempting to fetch resource и сайт подвисает.
При попытке перейти в корзину так же появляется эта ошибка.
После перезагрузки локального сервера и обновления страницы показывает, что в корзине есть товары. Но при попытке добавить еще товар происходит то же самое и та же самая ошибка.

Повысить оценку Понизить оценку

2 Ответ от admin 26.08.2021 20:15:24

  • admin
  • в работе
  • Неактивен
  • Откуда: Краснодар
  • Зарегистрирован: 19.06.2014
  • Сообщений: 1,084
  • Рейтинг: 146

Re: Ошибка NetworkError when attempting to fetch resource.

Посмотрите, какой статус ответа от запроса на сервер на вкладке Network.
Если 503, то выполните это https://readyscript.ru/faq/#faq-errors  и после этого еще раз посмотрите на Response на вкладке Network, там должна быть ошибка в развернутом виде.

На упреждение:
Проверьте значение в phpinfo() — mb_string.func_overload, должно быть = 0
Проверьте, чтобы в mysql был отключен strict mode, т.е. было sql_mode = »[пустые кавычки] в my.cfg

Повысить оценку Понизить оценку

3 Ответ от Александр 26.08.2021 20:57:28

  • Александр
  • Новый участник
  • Неактивен
  • Зарегистрирован: 26.08.2021
  • Сообщений: 4

Re: Ошибка NetworkError when attempting to fetch resource.

1) Вот с этими пунктами все ОК:

Проверьте значение в phpinfo() — mb_string.func_overload, должно быть = 0
Проверьте, чтобы в mysql был отключен strict mode, т.е. было sql_mode = »[пустые кавычки] в my.cfg

2) Посмотрите, какой статус ответа от запроса на сервер на вкладке Network.

По этому пункту вообще ничего, никаких статусов в ответе нет на вкладке Network. Система (сайт на frontend) пытается добавить товар в корзину и просто зависает. Приходится перезагружать сервер (Openserver).

Два дня было все ок, а потом вот так вот стало. На сервере ничего не перенастраивал.
Только устанавливал модули из магазина приложений. Возможно из-за какого то модуля.
Попробую еще раз выполнить чистую установку системы и потом следить при каждой установке дополнительного модуля, может после установки какого модуля это снова произойдет.

Повысить оценку Понизить оценку

4 Ответ от Александр 27.08.2021 04:05:35

  • Александр
  • Новый участник
  • Неактивен
  • Зарегистрирован: 26.08.2021
  • Сообщений: 4

Re: Ошибка NetworkError when attempting to fetch resource.

Выяснил в чем была причина.
Виноват был модуль «Всплывающие уведомления, базовый модуль» от автора ev-lab.ru (к тому же он не выполнял свой функционал и не выводил всплывающее уведомление о добавлении в корзину).
После отключения данного модуля все заработало как положено.

В первом сообщении забыл уточнить, что у меня стоит тема amazing (Изумительная).
Возможно на других темах такого конфликта не будет.

Повысить оценку Понизить оценку

5 Ответ от Ярослав 29.08.2021 02:02:28 Отредактировано Ярослав (29.08.2021 02:39:10)

  • Ярослав
  • Ярослав
  • Участник
  • Неактивен
  • Откуда: Пятигорск
  • Зарегистрирован: 13.11.2014
  • Сообщений: 644
  • Рейтинг: 64

Re: Ошибка NetworkError when attempting to fetch resource.

(к тому же он не выполнял свой функционал и не выводил всплывающее уведомление о добавлении в корзину).

Выполняет на теме Flatlines с JQuery. О чем я написал в теме с обсуждением модуля.

6 Ответ от Александр 29.08.2021 02:09:40 Отредактировано Александр (29.08.2021 02:12:12)

  • Александр
  • Новый участник
  • Неактивен
  • Зарегистрирован: 26.08.2021
  • Сообщений: 4

Re: Ошибка NetworkError when attempting to fetch resource.

Ярослав, так я же и написал, что возможно на других темах он и работает, а на этой нет.
А то я уже было подумал, что это сама readyscript глючит и хотел уже бросить ее изучать. Но как оказалось с readyscript все отлично.

Повысить оценку Понизить оценку

Сообщений [ 6 ]

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

Same issue. But what is particular in my situation is that I need to fetch a blob url, like «blob:https://images.google.com.hk/9143673d-b976-4416-b29c-85ce48a77da6».

However, if I declare manifest.json as

{
   ...
   "permissions": [
       "blob:*",
    ]
} 

Firefox does not recognize it, and throws a warning message, «Reading manifest: Warning processing permissions: Error processing permissions.1: Value «blob:» must either: must either [must either [be one of [«clipboardRead», «clipboardWrite», «geolocation», «idle», «notifications»], be one of [«bookmarks»], be one of [«find»], be one of [«history»], be one of [«menus.overrideContext»], be one of [«search»], be one of [«topSites»], be one of [«activeTab», «tabs», «tabHide»], be one of [«browserSettings»], be one of [«cookies»], be one of [«downloads», «downloads.open»], be one of [«privacy»], be one of [«webNavigation»], or be one of [«webRequest», «webRequestBlocking»]], be one of [«alarms», «mozillaAddons», «storage», «unlimitedStorage»], be one of [«captivePortal»], be one of [«browsingData»], be one of [«devtools»], be one of [«identity»], be one of [«menus», «contextMenus»], be one of [«normandyAddonStudy»], be one of [«pkcs11»], be one of [«geckoProfiler»], be one of [«sessions»], be one of [«urlbar»], be one of [«contextualIdentities»], be one of [«dns»], be one of [«activityLog»], be one of [«management»], be one of [«networkStatus»], be one of [«proxy»], be one of [«nativeMessaging»], be one of [«telemetry»], be one of [«theme»], or match the pattern /^experiments(.w+)+$/], or must either [be one of [«<all_urls>»], must either [match the pattern /^(https?|wss?|file|ftp|*)://(*|*.[^*/]+|[^*/]+)/.$/, or match the pattern /^file:///.$/], or match the pattern /^resource://(*|*.[^*/]+|[^*/]+)/.$|^about:/]»

Maybe the pattern /^(https?|wss?|file|ftp|*)://(*|*.[^*/]+|[^*/]+)/.*$/ can provide some hints, but useless for a blob URL. 😞

I don’t need to declare any permission about blob URL at chrome.

All right, it looks like <all_urls> is the only way.

Понравилась статья? Поделить с друзьями:
  • Ошибка network related or instance specific error
  • Ошибка network is unreachable no further information
  • Ошибка network failure геншин 110
  • Ошибка network failed что делать
  • Ошибка network error что значит