Nowaday, Fetch API is going to be used widely.
The most popular polyfill library is isomorphic-fetch which has default behavior is: first, using native fetch, if don’t have, use the polyfill.
Sometimes when you deal with Network problems, you need to know when having a network error.
Luckily, the API has this:
A
fetch()
promise will reject with aTypeError
when a network error is encountered, although this usually means permission issues or similar
But it isn’t good enough, because sometimes you have a TypeError inside above `doSomething` function, then this will make your app misunderstand the real problem.
But, we still have another solution:
isNetworkError = hasTypeError(error) && isNetworkErrorMessage(error.message)
With Chrome, the error message will be:
Failed to fetch
With Firefox, it’s:
NetworkError when attempting to fetch resource.
With Safari or other browsers that don’t support fetch, it’s from the polyfill:
Network request failed
- Александр
Тема: Ошибка NetworkError when attempting to fetch resource.
Установил систему для ознакомления и тестирования на локальном сервере (с доменной зоной .local).
Два дня было все нормально. Все работало без сбоев.
Сейчас при попытке добавить товар в корзину стала появляется ошибка NetworkError when attempting to fetch resource и сайт подвисает.
При попытке перейти в корзину так же появляется эта ошибка.
После перезагрузки локального сервера и обновления страницы показывает, что в корзине есть товары. Но при попытке добавить еще товар происходит то же самое и та же самая ошибка.
- admin
Re: Ошибка NetworkError when attempting to fetch resource.
Посмотрите, какой статус ответа от запроса на сервер на вкладке Network.
Если 503, то выполните это https://readyscript.ru/faq/#faq-errors и после этого еще раз посмотрите на Response на вкладке Network, там должна быть ошибка в развернутом виде.
Александр
- Александр
Re: Ошибка NetworkError when attempting to fetch resource.
1) Вот с этими пунктами все ОК:
2) Посмотрите, какой статус ответа от запроса на сервер на вкладке Network.
По этому пункту вообще ничего, никаких статусов в ответе нет на вкладке Network. Система (сайт на frontend) пытается добавить товар в корзину и просто зависает. Приходится перезагружать сервер (Openserver).
Два дня было все ок, а потом вот так вот стало. На сервере ничего не перенастраивал.
Только устанавливал модули из магазина приложений. Возможно из-за какого то модуля.
Попробую еще раз выполнить чистую установку системы и потом следить при каждой установке дополнительного модуля, может после установки какого модуля это снова произойдет.
Александр
- Александр
Re: Ошибка NetworkError when attempting to fetch resource.
Выяснил в чем была причина.
Виноват был модуль “Всплывающие уведомления, базовый модуль” от автора ev-lab.ru (к тому же он не выполнял свой функционал и не выводил всплывающее уведомление о добавлении в корзину).
После отключения данного модуля все заработало как положено.
В первом сообщении забыл уточнить, что у меня стоит тема amazing (Изумительная).
Возможно на других темах такого конфликта не будет.
Ярослав Отредактировано Ярослав (29.08.2021 02:39:10)
- Ярослав
Re: Ошибка NetworkError when attempting to fetch resource.
(к тому же он не выполнял свой функционал и не выводил всплывающее уведомление о добавлении в корзину).
Выполняет на теме Flatlines с JQuery. О чем я написал в теме с обсуждением модуля.
Александр Отредактировано Александр (29.08.2021 02:12:12)
- Александр
Re: Ошибка NetworkError when attempting to fetch resource.
Ярослав, так я же и написал, что возможно на других темах он и работает, а на этой нет.
А то я уже было подумал, что это сама readyscript глючит и хотел уже бросить ее изучать. Но как оказалось с readyscript все отлично.
Сообщений [ 6 ]
1.Thunderbird version: thunderbird v68.1.1, operation system: macOSX high sierra 10.13.6
2.Some days ago i can get mail messages, but now can not, like as ” could not connect to server mail.butel.com; the connection was refuesed.”
3.I attempt to remove account and add again, result “component returned failed code: 0x8000fff(NS_ERROR_UNEXPECTED)”, attempt thunderbird v60.9.4, v52.9.1, that can not add mail account.
4.Additional: a) my email server work normal, such as foxmail can add mail account successed. b) windows thunderbird v60.9.4 add the same mail account successed. So I judge that some setting affect the thunderbird.
1.Thunderbird version: thunderbird v68.1.1, operation system: macOSX high sierra 10.13.6
2.Some days ago i can get mail messages, but now can not, like as ” could not connect to server mail.butel.com; the connection was refuesed.”
3.I attempt to remove account and add again, result “component returned failed code: 0x8000fff(NS_ERROR_UNEXPECTED)”, attempt thunderbird v60.9.4, v52.9.1, that can not add mail account.
4.Additional: a) my email server work normal, such as foxmail can add mail account successed. b) windows thunderbird v60.9.4 add the same mail account successed. So I judge that some setting affect the thunderbird.
Выбранное решение
Thanks all, I find the problem reason, It is thunderbird network used proxy setting, and change it no proxy.
That can explain below error message:
1、could not connect to server mail.butel.com; the connection was refuesed.
2、”TypeError: NetworkError when attempting to fetch resource.”
Прочитайте этот ответ в контексте
👍 0
Все ответы (5)
1.Thunderbird version: thunderbird v68.1.1, operation system: macOSX high sierra 10.13.6
2.Some days ago i can get mail messages, but now can not, like as ” could not connect to server mail.butel.com; the connection was refuesed.”
3.I attempt to remove account and add again, result “component returned failed code: 0x8000fff(NS_ERROR_UNEXPECTED)”, attempt thunderbird v60.9.4, v52.9.1, that can not add mail account.
4.Additional: a) my email server work normal, such as foxmail can add mail account successed. b) windows thunderbird v60.9.4 add the same mail account successed. So I judge that some setting affect the thunderbird.
And, Yes, there is an Error in the log that TB couldn’t find your account settings. Try going to the tools menu and clicking on “Account Settings”.
Look at the entry for your butel.com/ mail account and check the server settings under it. Maybe when you click “OK” it will write the settings again into the preferences and that error will go away.
2、I use wireshark tool to catch network ip package, found that no any data transfer to mail server, like maxOSX forbid thunderbird to access network, but I check system firewall setting, no forbid. so no idea and I stop here.
When I add mail account and click re-test button , i open the thunderbird error console. The error message is:
- 2019-10-11 18:14:35 mail.setup INFO manual config to test:
- Incoming: pop3, mail.butel.com:110, no SSL, auth: plain, username: (redacted)@butel.com, password: set
- Outgoing: smtp, mail.butel.com:41000, no SSL, auth: plain, username: (redacted)@butel.com, password: set
- 2019-10-11 18:14:35 mail.setup WARN spinner start looking_up_settings_halfmanual
- 2019-10-11 18:14:35 mail.setup INFO status msg: Looking up configuration: Probing server
- 2019-10-11 18:14:35 mail.setup INFO switching to UI mode manual-edit-testing
- 2019-10-11 18:14:35 mail.setup INFO progress callback host mail.butel.com port 110 type pop3
- 2019-10-11 18:14:35 mail.setup INFO progress callback host mail.butel.com port 41000 type smtp
- TypeError: NetworkError when attempting to fetch resource. 2
- 2019-10-11 18:14:35 mail.setup INFO progress callback host mail.butel.com port 110 type pop3
- 2019-10-11 18:14:35 mail.setup INFO guessConfig failed: Can’t find a server
- 2019-10-11 18:14:35 mail.setup WARN status error failed_to_find_settings
- 2019-10-11 18:14:35 mail.setup INFO status msg: Thunderbird failed to find the settings for your email account.
- 2019-10-11 18:14:35 mail.setup INFO switching to UI mode manual-edit-have-hostname
The key error message:
TypeError: NetworkError when attempting to fetch resource. 2
I see two seriously odd things in this setup.
1. I have never seen SMTP configured on port 41,000. Try configuring your mail server to use a low port, perhaps even one of the “standard ones” but certainly less that 1,000. There be dragons above 1,000 because they are largely unused for anything. although 40,00 to 41000 can be used by some FTP installations. But is usually a UDP port.
2. Errors such as your last image normally shows the server name. That it is returning “self hosted” makes me wonder exactly what is happening there.
But I would guess that it is the port number that is causing the issue. Why it is I am not so sure. It might even be a regression caused by https://bugzilla.mozilla.org/show_bug.cgi?id=1500105
So some questions, that I may understand better your setup..
Is the server mail.butel.com an exchange server? If it were on the “local network” it might explain the “self hosted”, and some other things.
If you use the command prompt and type tracert mail.butel.com and tracert self-hosted do they both resolve to the same IP address. does self-hosted resolve at all?
Выбранное решение
Thanks all, I find the problem reason, It is thunderbird network used proxy setting, and change it no proxy.
That can explain below error message:
1、could not connect to server mail.butel.com; the connection was refuesed.
2、”TypeError: NetworkError when attempting to fetch resource.”
This issue seems to exists in #1779 (and #2301), but both have been closed long ago, even though the problem is not solved, at least not for me. Since I cannot reopen it and get no answer to my comments there, I open a new bug and provide all the information I have. Unfortunately the whole source code is too huge to append, so I provide the snippets where the problem occurs.
Describe the bug
- react 16.7.0
- web3, tested 1.0.0-beta.41 and 0.20.7
- canache-cli 6.2.5
- canache-code 2.3.3
- Firefox Quantum 64.0
- Metamask 5.3.2, also tested backgrade to 5.3.0
Without Metamask the exactly same code works (using the fallback to localhost, connecting to canache-cli). In a nodejs / express environment without react, it works. So I suppose, it is something about Metamask and React in combination.
startup of canache:
ganache-cli -d --db ${HOME}/tmp/ganache/db -i 123456
import Web3 from "web3";
const getWeb3 = new Promise((resolve, reject) => {
// Wait for loading completion to avoid race conditions with web3 injection timing.
window.addEventListener("load", async () => {
// Modern dapp browsers...
if (window.ethereum) {
const web3 = new Web3(window.ethereum);
try {
// Request account access if needed
await window.ethereum.enable();
// Acccounts now exposed
resolve(web3);
} catch (error) {
reject(error);
}
}
// Legacy dapp browsers...
else if (window.web3) {
// Use Mist/MetaMask's provider.
const web3 = window.web3;
console.log("Injected web3 detected.");
resolve(web3);
}
// Fallback to localhost; use dev console port by default...
else {
const provider = new Web3.providers.WebsocketProvider(
"ws://127.0.0.1:8545"
);
const web3 = new Web3(provider);
console.log("No web3 instance injected, using Local web3.");
resolve(web3);
}
});
});
export default getWeb3;
Using Web3 0
On line await window.ethereum.enable();
, I always get an error:
Source-Map-Fehler: TypeError: NetworkError when attempting to fetch resource.
Ressourcen-Adresse: moz-extension://b18341ab-dfc3-4aa4-b3a8-c6b259c38e56/contentscript.js
Source-Map-Adresse: ../sourcemaps/contentscript.js.map[Weitere Informationen]
At the end, creating a contract, web3 fails with silly error messages without a useful context, such as:
Error: invalid address
formatters.js:268
inputAddressFormatter
formatters.js:268
inputTransactionFormatter
formatters.js:104
./node_modules/web3/lib/web3/method.js/Method.prototype.formatInput/<
method.js:94
map self-hosted:286:17 ./node_modules/web3/lib/web3/method.js/Method.prototype.formatInput
method.js:93
./node_modules/web3/lib/web3/method.js/Method.prototype.toPayload
method.js:121
send
method.js:148
ContractFactory/this.new
contract.js:196
deploy
deploy.js:44
deploy self-hosted:975:17 callCallback
react-dom.development.js:147
invokeGuardedCallbackDev
react-dom.development.js:196
invokeGuardedCallback
react-dom.development.js:250
invokeGuardedCallbackAndCatchFirstError
react-dom.development.js:265
executeDispatch
react-dom.development.js:571
executeDispatchesInOrder
react-dom.development.js:596
executeDispatchesAndRelease
react-dom.development.js:695
executeDispatchesAndReleaseTopLevel
react-dom.development.js:704
forEachAccumulated
react-dom.development.js:676
runEventsInBatch
react-dom.development.js:844
runExtractedEventsInBatch
react-dom.development.js:852
handleTopLevel
react-dom.development.js:5027
batchedUpdates$1
react-dom.development.js:20269
batchedUpdates
react-dom.development.js:2246
dispatchEvent
react-dom.development.js:5107
interactiveUpdates$1
react-dom.development.js:20331
interactiveUpdates
react-dom.development.js:2267
dispatchInteractiveEvent
react-dom.development.js:5083
dispatchInteractiveEvent self-hosted:1019:17
Using Web3 1. 0-beta41
Same in web3 1.0.0-beta41:
Source-Map-Fehler: TypeError: NetworkError when attempting to fetch resource.
Ressourcen-Adresse: moz-extension://b18341ab-dfc3-4aa4-b3a8-c6b259c38e56/contentscript.js
Source-Map-Adresse: ../sourcemaps/contentscript.js.map
The message Weitere Informationen links to a Firefox page.
When I try to deploy a contract in Web3 1.0.0-beta41, I get no more information than:
DataCloneError: The object could not be cloned. inpage.js:1
To Reproduce
Steps to reproduce the behavior:
- Setup a react app
- Use the above initialisation code
- Use Metamask in Firefox
- See error in console
- Try to deploy a contract
- See the second error message
Expected behavior
Web3 should be correctly initialized, a contract should be deployed.
- OS: Ubuntu 18.04
- Browser Firefox Quantum 64.0
- MetaMask Version 5.3.2
The code, where the contract is deployed:
web3.eth.Contract(contractjson.abi).deploy({
data: contractjson.bytecode,
arguments: [this.state.arg1, this.state.arg2 this.state.arg3]
}).send({
from: this.state.account,
gas: this.state.gas,
gasPrice: this.state.gasprice
})
.then(newContractInstance => {
this.setState({
result: "success: " + newContractInstance.options.address
});
this.updateAccounts();
})
.catch(err => {
this.setState({ result: "cannot create contract: " + err });
});
Can you have a look in the developer console of your browser which HTTP request actually failed?
I’m also using a reverse proxy (apache). Would you by chance know where I would have to add it?
It’s actually the same for Riot-Web. Can you access your synapse instance from riot.im web client?
Yes, Riot-Web works just fine.
I’m also using a reverse proxy (apache). Would you by chance know where I would have to add it?
Indeed, which I mentioned earlier 😛
Google is your friend: https://github.com/matrix-org/synapse/blob/master/docs/ACME.md
location /.well-known/acme-challenge {
proxy_pass http://localhost:8009;
}
ProxyPass /.well-known/acme-challenge http://localhost:8009/.well-known/acme-challenge
Of course not only for the acme-challenge but everything under .well-kown
But unfortunately the issue remains the same.
Google is your friend: https://github.com/matrix-org/synapse/blob/master/docs/ACME.md
location /.well-known/acme-challenge { proxy_pass http://localhost:8009; }
ProxyPass /.well-known/acme-challenge http://localhost:8009/.well-known/acme-challenge
Of course not only for the acme-challenge but everything under .well-kown
Latest master works without HTTPS.
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:*",
]
}
I don’t need to declare any permission about blob URL at chrome.
All right, it looks like <all_urls> is the only way.