Network error when attempting to fetch resource что значит

TypeError: «NetworkError when attempting to fetch resource.»

I’ve found a lot of question similar to my problem but I don’t get solution that’s why I’ve asked here.

I’ve just started learning front end development using React. I’ve made separate app for front end and backend running at different ports.

Backend : Laravel framework app running at incomeexpense.stacklearning.com/

Frontend : React app running at localhost:3000/

I’ve a form like this:

I’ve following routes,

Читайте также:  Аланинаминотрансфераза алт понижена что это значит у женщин

Here is CORS middleware,

Finally here is user creating function

When I send the post request from react app following error is shown at console

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://incomeexpense.stacklearning.com/api/users. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

TypeError: «NetworkError when attempting to fetch resource.» Register.js:39 Cross-Origin Request Blocked:

The Same Origin Policy disallows reading the remote resource at http://incomeexpense.stacklearning.com/api/users. (Reason: CORS request did not succeed).

I know this error is due to different domain and browser prevent resource access to different domain.

I just want to know what I need need to do at front and at back end to make things right

PS: back end code works perfectly while sending request from postman.

Источник

How to resolve «TypeError: NetworkError when attempting to fetch resource.»

When I use aurelia-fetch-client to post json data to server and I got this error «TypeError: NetworkError when attempting to fetch resource.» I think your answer is very useful to me.

3 Answers 3

This is probably related to Cross-Origin Resource Sharing (CORS).

The Cross-Origin Resource Sharing (CORS) mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers. Modern browsers use CORS in an API container — such as XMLHttpRequest or Fetch — to mitigate risks of cross-origin HTTP requests. (Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

If you have Chrome you could try using Run in Windows with the command: chrome.exe —user-data-dir=»C:/Chrome dev session» —disable-web-security and see if you can run your code in that environment. This will allow access to no ‘access-control-allow-origin’ header requests.

I tried running parts of your code normally in Chrome, Firefox and Edge and got the same CORS errors. It did however run when I used the above command. You didn’t give too much information to go on, but you might have to do some changes server side as well as in your code.

The command above and more good information about CORS can be found here on SO: «No ‘Access-Control-Allow-Origin’ header is present on the requested resource»

Hopefully this can at least point you in the right direction.

Источник

Почему периодически возникает ошибка NetworkError when attempting to fetch resource?

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

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

  • Вопрос задан более года назад
  • 3408 просмотров

Простой 18 комментариев

Хотел помочь но прочитав комменты передумал.

Подскажите плиз что это за ошибка, почему она возникает и как ее решить

Виктор Поляков, «Вот как ты думаешь, зачем создали тостер?» — тостер это q&a, то есть сервис вопросов и ответов, что-то типа базы знаний к которой можно обратиться при случае. Не сервис IT помощи для ленивых, а именно база знаний, как stackoverflow

«Мне лично это не помогло» — и как раз суть q&a не в том, чтобы ответы помогали кому-то лично в их конкретных рабочих задачах, а в обмене опытом и знаниями.

В вашем случае мне кажется достаточно очевидно, что если ошибка сетевая, то виновник тут не реакт или js, а кто-то другой — может быть человек который криво написал вам сервис, а может быть кот который играет с проводом питания роутера. Проблема не на вашей стороне короче

Robur, Да я уже получил ответ на свой вопрос. Помогли НОРМАЛЬНЫЕ люди которые умеют нормально объяснять, а главное без закидонов. Что-то там это у Вас, а у меня обычная аллергия на свинское отношение.

Хорошо, приведем пример, Вы задаете вопрос, из обычной жизни. К примеры обращаетесь ко мне и спрашиваете как пройти к такому-то магазину.
Я вместо ответа: ну к магазину можешь пройти по асфальту, который находится на дороге, что тут сложного.
Вы отвечаете, да я понял что по асфальту и по дороге, зачем так отвечать, неужели сложно нормально подсказать.
Я: Ну раз ты не можешь включить свой мозг и посмотреть по навигатору, то это очень печально.
Вы: Да я смотрел, но к сожалению не нашел. Если не хотите помогать то не надо выделываться.

Подходит прохожий: Ну вам же сказали по дороге зачем вы грубите. Что тут не понятного. Теперь я Вам тоже дорогу не покажу.

Я вроде как ответил на вопросы, но само содержание ответа, разве может считаться нормальным??

Если уж проводить аналогию, то правильнее будет так:

Вы обращаетесь к прохожему и спрашиваете как пройти к таком-то магазину.
Прохожий: «Разве вы не видите, вон вывеска, вам через дорогу напротив».
Вы отвечаете: «да ладно?))) Вот ты Америку открыл))) А то я по сторонам не посмотрел сначала? Я что, по твоему слепой, что мне эта вывеска?».
Прохожий: Ну раз вы не можете включить свой мозг и пойти туда где вывеска, то это очень печально.
Вы: «Ну ты и мудила. Пойду поспрашиваю у тех кто нормально ответит!»

и дальше топчитесь на месте, громко возмущаясь, рассказывая всем людям как вам тут нахамили с криками «я не потерплю!» «я недавно здесь» «А вот за границей мне бы вежливо ответили» «да я таких посылать буду сразу же» «ответ — посмотри по сторонам — это не для нашего города!!» и так далее.

Хотя можно было сказать «а, точно, вывеска, вон же он, спасибо» и за 2 минуты попасть куда вам надо.

Виктор Поляков, да какие взгляды — я просто заменил в вашем примере вежливые фразы которых там в оригинале не было на слова которые действительно были в диалоге и комментариях после. Практически скопипастил.

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

Прочитал, и еще раз убедился, что рашен-комьюнити недопрограммистов полный отстой, мнят себя божничкой, а сами работают в Залупинске где-нибудь типа IT в отделе. зарплата маленькая, тёлка страшная да и та не дает, квартира в ипотеку, приходится хоть как-то самооценку свою поднимать, только она тут Н@хуй ни кому не интересна.

Если бы такой педик, к которому чел обратился бы за советом, работал в гугле или фейсбуке, а тот бы его послал гуглить, то на хyй бы вылетел с работы на следующий день, потому что, там ценят дух взаимоподдержки и роста для начинающих, и когда к ним обращаются за обычным советом челики уровня 1-2, то более умные стараются максимально помочь, потому что те своим ростом поднимают более умных вверх по карьере.

Но Вам, обезьянкам, (как в Штатах вас называют, «программистов» из России) это не грозит, потому что, таких бакланов как Вы, в комьюнити нормальных пацанов нет и быть не может.

Так что сидеть тут , и писать какие вы охyенные это ваш реальный предел.
Мечтайте в своем забвении, что может кто-то из комьюнити Хабра и подберет вас, на вшивую работенку.

Источник

TypeError: NetworkError when attempting to fetch resource — firefox issue #310

Comments

jcimoch commented Apr 11, 2016

Hi, I have simple function for logout that looks like this

It is workin in chrome but in firefox I get «TypeError: NetworkError when attempting to fetch resource.1 (unknown)». Client side app is on the same server as backend, I’m using https connection with self-signed cert, could it be the issue?

The text was updated successfully, but these errors were encountered:

dgraham commented Apr 11, 2016

Firefox contains a native fetch implementation and does not use this polyfill code. You can use the Network tab in Firefox’s web console to debug the request and response.

ariden83 commented Jun 21, 2017

On chrome, I’ve got «TypeError: Failed to fetch»
On firefox, the same «TypeError: NetworkError when attempting to fetch resource»
..

jstoja commented Jun 26, 2017

Have you check errors like CORS?

billytianlan commented Jul 12, 2017

@ariden83 did you figure out what was causing the errors? I’m seeing the same issues in isolated cases

fabdarice commented Jul 17, 2017

Can we reopen this ticket?
I’m seeing the same error, but only on Firefox.
Also, nothing shows up in the Network tab.

ncaq commented Sep 6, 2017

There maybe relational link.

ganeshangler commented Sep 26, 2017

I’m seeing the same error,except chrome

iamsoorena commented Dec 12, 2017

I have the same exact issue. everything is fine in chrome but firefox caches wrong fetch response. and the worst of all is that it caches this error as response of that particular endpoint of my api for a LONG time.

jomo commented Dec 22, 2017

Having the same issue when I have network.http.referer.XOriginPolicy set to 1 («send a referrer only when the base domains are the same»). Is that supposed to happen? I’m quite sure the base domain of localhost matches the base domain of itself 🙂

manoharreddyporeddy commented Jan 9, 2018

I was accessing Function app, via Logic app, when I got the above error.

Following worked for me:

  1. Function app > Platform features tab > API > CORS > Allowed Origins > (remove all, Save)
  2. Function app > Platform features tab > API > CORS > Allowed Origins > * > Save (that is add * and save)
  3. Function app > Overview tab > Restart

Hope that helps.

aguayUmbt commented Jun 18, 2018

@manoharreddyporeddy function app > platform features tab etc
what are those?

manoharreddyporeddy commented Jun 19, 2018

@aguayUmbt they are menu/sequence of operations to be done in the Azure portal

niranjanreddy891 commented Sep 27, 2018

@jcimoch, I am having the same issue. Please tell me how to debug it. 🙂

sangxxh commented Jan 16, 2019 •

For those who are writing Firefox addon, the solution here helped me, I have to add «*://localhost/*»
to permissions key in manifest.json :

Chrome just works without the need to add this permission.

Barracuda6 commented Feb 19, 2019

If anyone comes across this, I had the same error in Firefox (but with a different application) and it turns out it was because the (self-signed) SSL certificate I was using on the server was not trusted in Firefox. I added the self-signed root CA to Firefox and all was well.

thehme commented Feb 19, 2019 •

In our case, the solution was not using the wild card for Access-Control-Allow-Origin on the server side, instead of the wild card, our settings look like this:

Hervera commented Mar 17, 2019 •

Check if you are using http or https on your server. For me, the error was coming online with heroku server because they use https while in local machine I was using http and it was working.
After choosing https on Heroku for my endpoints, it also worked

x011 commented Aug 15, 2019 •

I managed to solve the problem by monitoring the headers returned by github used on the demo page.
Since I’m using a python webserver, they look something like this:

rohanaceres commented Nov 2, 2019

For me, Swagger UI for some reason crashes when I use examples that consume multilanguage resource files. So I removed the examples from Swagger config and Swager UI started working properly again — of course, without examples.

sebastian-palma commented Feb 2, 2020

Tried in a Rails 6 only-api app with CORS enabled, using NGROK and no luck.

and got it working.

Leslie-Wong-H commented May 19, 2020

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

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 [«»], 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 is the only way.

MihailYotov commented Jul 15, 2020

I had this problem and turned out that someone had put redirection (window.location = ‘/’) not in the promise’s resolve function, but immediately after the fetch call, so the application was aborting the call and redirecting to the index.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Оцените статью