This is my first time using axios and I have encountered an error.
axios.get(
`http://someurl.com/page1?param1=1¶m2=${param2_id}`
)
.then(function(response) {
alert();
})
.catch(function(error) {
console.log(error);
});
With the right url and parameters, when I check network requests I indeed get the right answer from my server, but when I open console I see that it didn’t call the callback, but instead it caught an error.
Error: Network Error
Stack trace:
createError@http://localhost:3000/static/js/bundle.js:2188:15
handleError@http://localhost:3000/static/js/bundle.js:1717:14
asked Aug 31, 2017 at 11:16
6
If Creating an API Using NodeJS
Your Express app needs to use CORS (Cross-Origin Resource Sharing). Add the following to your server file:
// This should already be declared in your API file
var app = express();
// ADD THIS
var cors = require('cors');
app.use(cors());
For fuller understanding of CORS, please read the Mozilla Documentation on CORS.
answered Nov 15, 2017 at 21:25
jacobhobsonjacobhobson
9968 silver badges14 bronze badges
5
my problem was about the url I was requesting to. I hadn’t inserted http://
at the beginning of my url. I mean I was requesting to a url like 92.920.920.920/api/Token
instead of http://92.920.920.920/api/Token
. adding http://
solved my problem.
phoenix
7,3885 gold badges37 silver badges44 bronze badges
answered Apr 30, 2019 at 10:57
1
It happens when you work on localhost and forgot to add http://
Wrong Usage
const headers = {
"Content-Type": "application/json",
Authorization: apiKey,
};
const url = "localhost:5000/api/expenses/get-expenses";
axios.get(url, { headers });
// NETWORK ERROR
The correct one is
const headers = {
"Content-Type": "application/json",
Authorization: apiKey,
};
const url = "http://localhost:5000/api/expenses/get-expenses";
axios.get(url, { headers });
// WORKS FINE IF YOU HANDLED CORS CORRECTLY IN THE SERVER SIDE
answered Dec 6, 2020 at 8:07
1
In addition to @jacobhobson answer, I had also used some parameters to made it work.
app.use(cors({origin: true, credentials: true}));
answered Nov 28, 2019 at 13:13
0
I was having same issue on production on digital ocean droplet. I was using axios in ReactJS to call Node.js API.
Although I included cors
const cors = require('cors');
app.use(cors());
But I still had to add
res.header( "Access-Control-Allow-Origin" );
before calling out my controller. And it worked for me. There I realized that cors is not working properly. So I uninstalled and installed them again and It Works!
Complete code is here.
So either you use
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "x-access-token, Origin, X-Requested-With, Content-Type, Accept");
next();
});
or use
app.use(cors());
It’s the same.
answered Jun 29, 2020 at 5:34
5
I received a network error with axios 0.27.2 when I was trying to upload an image to our server. After I set headers like below no error is received.
headers:{"Accept":"application/json, text/plain, /","Content-Type": "multipart/form-data"}
and you need to check with your api request’s body type in your collection like if it’s form-data or x-wwww-form-urlencoded or ..etc.
Skoua
3,1913 gold badges41 silver badges50 bronze badges
answered May 11, 2022 at 17:18
A.A.A.A.
712 bronze badges
In my case I used «https» instead of «http«, check that too.
answered May 16, 2021 at 14:28
1
Make sure you have the same port number in cors({ origin : [ "http://localhost:3001"]})
and the .env
file.
Elletlar
3,1067 gold badges30 silver badges38 bronze badges
answered Nov 3, 2020 at 9:58
This is happening because of restrict-origin-when-cross-origin policy.Browser sends a pre-flight request to know whom the API server wants to share the resources.
So you have to set origin there in API server and send some status.After that the browser allow to send the request to the API server.
Here is the code.I am running front-end on localhost:8000 and api server is running on port 6000.
const cors = require("cors");
app.options("*", cors({ origin: 'http://localhost:8000', optionsSuccessStatus: 200 }));
app.use(cors({ origin: "http://localhost:8000", optionsSuccessStatus: 200 }));
I have set origin as my front-end url, If You set it to true , then it will allow only port 8000 to access rosource, and front-end running on port 8000 can not access this resource. Use this middleware before route in api server.
answered Oct 7, 2021 at 8:45
I have resolved my issue by adding this header.
var data = new FormData();
data.append('request', 'CompaniesData');
var config = {
method: 'post',
url: baseUrl, headers:{"Accept":"application/json, text/plain, /","Content-Type": "multipart/form-data"},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
answered May 17, 2022 at 11:18
i’m using axios in react-native as android and .net as backend, i have same issue but i can’t solve the problem. I think it is security problem when i type the url in chrome it warns me about that in emulator.
axios("http://10.0.2.2:5001/api/Users/getall")
.then((result) => setUsers(result.data.data))
.then((json) => {
return json.data;
})
.catch((error) => {
console.error(error);
})
.then((response) => response.parse());
answered May 21, 2022 at 19:44
In my case, I’m using Hapi.js as the backend, so all I had to do is set the cors value to true as in the code below;
const server = Hapi.server({
port: 4000,
host: 'localhost',
state: {
strictHeader: false
},
routes: {
cors: true
}
});
answered Jun 10, 2022 at 12:42
BenBen
3854 silver badges15 bronze badges
-
change the
port
number of your node server.
It took more than 3 hours to solve this error. Solution ended with changing port numer which was initially set to 6000, later set to 3001. Then it worked. My server localhost base url was:"http://localhost:6000/data"
I changed port number in
app.listen()
on server and from frontend I call thatGET
route inasync
function as
await axios.get('http://localhost:3001/data')
.
It is working fine now. -
If you face the address issue:
address already in use :::#port
Then on command prompt:
killall -9 node
answered Aug 11, 2022 at 16:46
I just want to let you know that after searching for a solution for two days, I was able to solve my error.
Since the proxy was the source of the issue, I must configure a proxy in the package.json file, and I have to follow these instructions in the function that uses Axios:
try { await axios.post("user/login", formData).then((res) => { console.log(res.data); }); } catch (error) { console.log(error.response.data.message); }
and in package.json file need to add a proxy:
"proxy": "http://localhost:6000",
for better understand check this documentation: enter link description here
answered Nov 3, 2022 at 16:10
1
If you are running react native
in development
while using real device
connected via USB(and the API server is being accessed via development machine IP), ensure the development machine and the device are both connected to the same network
answered Feb 4 at 12:12
Содержание
- Соединение с сервером потеряно при побеге из Таркова | БЫСТРАЯ ПОЧИНКА
- Попробуйте эти исправления
- Исправление 1. Перед игрой выберите сервер с лучшим пингом.
- Исправление 2. Перезагрузите роутер.
- Исправление 3. Используйте VPN
- Исправить 4. Отключить IPv6
- Исправление 5. Обновите сетевые драйверы
- Fix 6. Переключитесь на статический IP
- Исправление 7. Переход с DS-Lite на Dual-Stack
- Соединение с сервером потеряно при побеге из Таркова | БЫСТРАЯ ПОЧИНКА
- Попробуйте эти исправления
- Исправление 1. Перед игрой выберите сервер с лучшим пингом.
- Исправление 2. Перезагрузите роутер.
- Исправление 3. Используйте VPN
- Исправить 4. Отключить IPv6
- Исправление 5. Обновите сетевые драйверы
- Fix 6. Переключитесь на статический IP
- Исправление 7. Переход с DS-Lite на Dual-Stack
Соединение с сервером потеряно при побеге из Таркова | БЫСТРАЯ ПОЧИНКА
Server Connection Lost Escape From Tarkov Quick Fix
Сервер в Escape from Tarkov не работает? Многие игроки сообщают, что их выгоняют из-за ошибки «Соединение с сервером потеряно». Вот исправление.
Сервер в Escape from Tarkov не работает? Многие геймеры сообщают, что их выгнали с ‘ Соединение с сервером потеряно ‘ ошибка. Это так типично.
В общем, с вашей стороны мало чем заняться, просто подождите, пока Battlesate решит свои проблемы. Однако есть вероятность, что на самом деле проблем с сервером нет (проверьте статус сервера). Ниже приведены быстрые исправления, которые можно попробовать, если вы хотите поиграть в нее как можно скорее.
Попробуйте эти исправления
- Перед игрой выберите сервер с лучшим пингом
- Перезагрузите ваш роутер
- Используйте VPN
- Отключить IPv6
- Обновите сетевые драйверы
- Переключиться на статический IP
- Переход с DS-Lite на Dual-Stack
Исправление 1. Перед игрой выберите сервер с лучшим пингом.
Многим геймерам помогает выбор лучшего сервера. Вы должны снять флажок с автоматического выбора сервера и выбрать сервер с наименьшим пингом.
Ошибка «Соединение с сервером потеряно» в Таркове сохраняется? Если ручной выбор сервера не помог, вы можете попробовать следующее исправление, указанное ниже.
Исправление 2. Перезагрузите роутер.
Это может быть просто связано с вашим подключением к Интернету, особенно когда у других нет этой проблемы.
1) Отключите модем и маршрутизатор,
2) Оставьте их минимум на 30 секунд.
3) Подключите модем, а затем маршрутизатор обратно к источнику питания.
4) Проверьте проблемы с сервером в Escape of Tarkov.
Исправление 3. Используйте VPN
VPN может помочь установить лучшие соединения в Escape from Tarkov. Многие игроки считают, что это действительно может до некоторой степени уменьшить количество сбоев. В противном случае их все время выгоняют.
Вы можете выбрать надежный бесплатный VPN или платный VPN, например Nord VPN (к Купон на скидку 70% доступен уже сейчас), который включает в себя круглосуточную поддержку клиентов и 30-дневную бесплатную пробную версию.
Разница между бесплатным VPN и платным — это пинг. Серверы Таркова чрезвычайно чувствительны к любым задержкам или колебаниям пинга. Поэтому обязательно выбирайте VPN с наименьшим пингом.
Исправить 4. Отключить IPv6
Многие игроки исправляют эту проблему, отключив IPv6. Это не гарантированное решение, но все же стоит попробовать. Вот как:
1) На клавиатуре нажмите Окно клавиша s + р ключ одновременно.
2) Введите ncpa.cpl в поле ‘Выполнить’.
3) Щелкните правой кнопкой мыши активный сетевой адаптер ( Ethernet или Вай-фай ) и выберите Характеристики .
4) Прокрутите вниз и снимите флажок Интернет-протокол версии 6 (TCP / IPv6) .
5) Нажмите хорошо чтобы сохранить изменения.
Возможно, вам потребуется перезагрузить компьютер, чтобы настройки вступили в силу.
Исправление 5. Обновите сетевые драйверы
Если драйвер сетевого адаптера, который вы используете, неисправен или устарел, вы, возможно, столкнетесь с этой ошибкой «Соединение с сервером потеряно» в Escape from Tarkov. Чтобы устранить потенциальные проблемы и добиться меньших задержек, вам следует установить на свой компьютер последнюю версию сетевого драйвера.
Вручную — Чтобы обновить драйвер сетевого адаптера до последней версии, вам необходимо посетить веб-сайт производителя, загрузить точный драйвер, а затем установить его вручную.
Автоматически — Если у вас нет времени, терпения или навыков работы с компьютером для обновления драйверов вручную, вместо этого вы можете сделать это автоматически с помощью Водитель Easy . Driver Easy автоматически распознает вашу систему и найдет правильные драйверы для вашего сетевого адаптера, а также правильно загрузит и установит их:
1) Скачать и установите Driver Easy.
2) Запустите Driver Easy и нажмите Сканировать сейчас кнопка. Затем Driver Easy просканирует ваш компьютер и обнаружит все проблемные драйверы.
3) Щелкните значок Обновлять рядом с отмеченным драйвером сетевого адаптера, чтобы автоматически загрузить правильную версию этого драйвера, а затем вы можете установить его вручную (это можно сделать в БЕСПЛАТНОЙ версии).
Или нажмите Обновить все для автоматической загрузки и установки правильной версии всех драйверов, которые отсутствуют или устарели в вашей системе. (Для этого требуется Pro версия который поставляется с полной поддержкой и 30-дневной гарантией возврата денег. Вам будет предложено выполнить обновление, когда вы нажмете Обновить все .)
4) После обновления драйвера перезагрузите компьютер, чтобы изменения вступили в силу.
Профессиональная версия Driver Easy поставляется с полной технической поддержкой.
Если вам нужна помощь, пожалуйста, свяжитесь с нами. Служба поддержки Driver Easy в support@letmeknow.ch .
Fix 6. Переключитесь на статический IP
Вместо того, чтобы позволять вашему маршрутизатору назначать любой свободный IP-адрес в любой момент времени, вы можете назначать определенные IP-адреса устройствам, к которым вы часто обращаетесь. И это оказывается временным исправлением для ‘ Соединение с сервером потеряно ‘Для нескольких игроков Escape from Tarkov. Вот как это сделать:
1) На клавиатуре нажмите Win + R в то же время и войти ncpa.cpl .
2) Щелкните правой кнопкой мыши активное соединение и выберите Статус .
3) Щелкните Подробности .
4) Запишите IPv4-адрес и Маска подсети IPv4 . Вы можете записать это или сделать снимок экрана, потому что он вам понадобится позже.
5) Теперь вернитесь к Подключение к сети щелкните правой кнопкой мыши активное соединение и выберите Характеристики .
6) Дважды щелкните значок Интернет-протокол версии 4 (TCP / IPv4) .
7) Выберите Используйте следующий IP-адрес вариант, а затем введите IP-адрес, маску подсети, которую вы приобрели ранее. Затем введите предпочтительный и альтернативный адреса DNS-серверов.
Нажмите хорошо чтобы сохранить изменения.
9) Вы можете проверить свои новые настройки, используя ipconfig команда в командной строке.
Попробуйте запустить игру и проверьте проблему. Но если ошибка потери соединения с сервером Tarkov, к сожалению, сохраняется, вы можете попробовать следующее исправление.
Исправление 7. Переход с DS-Lite на Dual-Stack
Если ни один из вышеперечисленных способов не решит вашу проблему, вы можете попросить своего интернет-провайдера перейти с DS Lite на Dual Stack. Это оказалось полезным для многих игроков, хотя и с переменным успехом.
Dual-Stack позволяет устройству запускать IPv4 и IPv6 параллельно, в то время как DS-Lit (Dual-Stack Lite) — это технология, которая позволяет интернет-провайдерам переходить в сеть IPv6, одновременно обрабатывая истощение IPv4-адресов.
Решили ли приведенные выше исправления вашу проблему? Не стесняйтесь написать нам, если у вас есть какие-либо вопросы или предложения.
Источник
Соединение с сервером потеряно при побеге из Таркова | БЫСТРАЯ ПОЧИНКА
Server Connection Lost Escape From Tarkov Quick Fix
Сервер в Escape from Tarkov не работает? Многие игроки сообщают, что их выгоняют из-за ошибки «Соединение с сервером потеряно». Вот исправление.
Сервер в Escape from Tarkov не работает? Многие геймеры сообщают, что их выгнали с ‘ Соединение с сервером потеряно ‘ ошибка. Это так типично.
В общем, с вашей стороны мало чем заняться, просто подождите, пока Battlesate решит свои проблемы. Однако есть вероятность, что на самом деле проблем с сервером нет (проверьте статус сервера). Ниже приведены быстрые исправления, которые можно попробовать, если вы хотите поиграть в нее как можно скорее.
Попробуйте эти исправления
- Перед игрой выберите сервер с лучшим пингом
- Перезагрузите ваш роутер
- Используйте VPN
- Отключить IPv6
- Обновите сетевые драйверы
- Переключиться на статический IP
- Переход с DS-Lite на Dual-Stack
Исправление 1. Перед игрой выберите сервер с лучшим пингом.
Многим геймерам помогает выбор лучшего сервера. Вы должны снять флажок с автоматического выбора сервера и выбрать сервер с наименьшим пингом.
Ошибка «Соединение с сервером потеряно» в Таркове сохраняется? Если ручной выбор сервера не помог, вы можете попробовать следующее исправление, указанное ниже.
Исправление 2. Перезагрузите роутер.
Это может быть просто связано с вашим подключением к Интернету, особенно когда у других нет этой проблемы.
1) Отключите модем и маршрутизатор,
2) Оставьте их минимум на 30 секунд.
3) Подключите модем, а затем маршрутизатор обратно к источнику питания.
4) Проверьте проблемы с сервером в Escape of Tarkov.
Исправление 3. Используйте VPN
VPN может помочь установить лучшие соединения в Escape from Tarkov. Многие игроки считают, что это действительно может до некоторой степени уменьшить количество сбоев. В противном случае их все время выгоняют.
Вы можете выбрать надежный бесплатный VPN или платный VPN, например Nord VPN (к Купон на скидку 70% доступен уже сейчас), который включает в себя круглосуточную поддержку клиентов и 30-дневную бесплатную пробную версию.
Разница между бесплатным VPN и платным — это пинг. Серверы Таркова чрезвычайно чувствительны к любым задержкам или колебаниям пинга. Поэтому обязательно выбирайте VPN с наименьшим пингом.
Исправить 4. Отключить IPv6
Многие игроки исправляют эту проблему, отключив IPv6. Это не гарантированное решение, но все же стоит попробовать. Вот как:
1) На клавиатуре нажмите Окно клавиша s + р ключ одновременно.
2) Введите ncpa.cpl в поле ‘Выполнить’.
3) Щелкните правой кнопкой мыши активный сетевой адаптер ( Ethernet или Вай-фай ) и выберите Характеристики .
4) Прокрутите вниз и снимите флажок Интернет-протокол версии 6 (TCP / IPv6) .
5) Нажмите хорошо чтобы сохранить изменения.
Возможно, вам потребуется перезагрузить компьютер, чтобы настройки вступили в силу.
Исправление 5. Обновите сетевые драйверы
Если драйвер сетевого адаптера, который вы используете, неисправен или устарел, вы, возможно, столкнетесь с этой ошибкой «Соединение с сервером потеряно» в Escape from Tarkov. Чтобы устранить потенциальные проблемы и добиться меньших задержек, вам следует установить на свой компьютер последнюю версию сетевого драйвера.
Вручную — Чтобы обновить драйвер сетевого адаптера до последней версии, вам необходимо посетить веб-сайт производителя, загрузить точный драйвер, а затем установить его вручную.
Автоматически — Если у вас нет времени, терпения или навыков работы с компьютером для обновления драйверов вручную, вместо этого вы можете сделать это автоматически с помощью Водитель Easy . Driver Easy автоматически распознает вашу систему и найдет правильные драйверы для вашего сетевого адаптера, а также правильно загрузит и установит их:
1) Скачать и установите Driver Easy.
2) Запустите Driver Easy и нажмите Сканировать сейчас кнопка. Затем Driver Easy просканирует ваш компьютер и обнаружит все проблемные драйверы.
3) Щелкните значок Обновлять рядом с отмеченным драйвером сетевого адаптера, чтобы автоматически загрузить правильную версию этого драйвера, а затем вы можете установить его вручную (это можно сделать в БЕСПЛАТНОЙ версии).
Или нажмите Обновить все для автоматической загрузки и установки правильной версии всех драйверов, которые отсутствуют или устарели в вашей системе. (Для этого требуется Pro версия который поставляется с полной поддержкой и 30-дневной гарантией возврата денег. Вам будет предложено выполнить обновление, когда вы нажмете Обновить все .)
4) После обновления драйвера перезагрузите компьютер, чтобы изменения вступили в силу.
Профессиональная версия Driver Easy поставляется с полной технической поддержкой.
Если вам нужна помощь, пожалуйста, свяжитесь с нами. Служба поддержки Driver Easy в support@letmeknow.ch .
Fix 6. Переключитесь на статический IP
Вместо того, чтобы позволять вашему маршрутизатору назначать любой свободный IP-адрес в любой момент времени, вы можете назначать определенные IP-адреса устройствам, к которым вы часто обращаетесь. И это оказывается временным исправлением для ‘ Соединение с сервером потеряно ‘Для нескольких игроков Escape from Tarkov. Вот как это сделать:
1) На клавиатуре нажмите Win + R в то же время и войти ncpa.cpl .
2) Щелкните правой кнопкой мыши активное соединение и выберите Статус .
3) Щелкните Подробности .
4) Запишите IPv4-адрес и Маска подсети IPv4 . Вы можете записать это или сделать снимок экрана, потому что он вам понадобится позже.
5) Теперь вернитесь к Подключение к сети щелкните правой кнопкой мыши активное соединение и выберите Характеристики .
6) Дважды щелкните значок Интернет-протокол версии 4 (TCP / IPv4) .
7) Выберите Используйте следующий IP-адрес вариант, а затем введите IP-адрес, маску подсети, которую вы приобрели ранее. Затем введите предпочтительный и альтернативный адреса DNS-серверов.
Нажмите хорошо чтобы сохранить изменения.
9) Вы можете проверить свои новые настройки, используя ipconfig команда в командной строке.
Попробуйте запустить игру и проверьте проблему. Но если ошибка потери соединения с сервером Tarkov, к сожалению, сохраняется, вы можете попробовать следующее исправление.
Исправление 7. Переход с DS-Lite на Dual-Stack
Если ни один из вышеперечисленных способов не решит вашу проблему, вы можете попросить своего интернет-провайдера перейти с DS Lite на Dual Stack. Это оказалось полезным для многих игроков, хотя и с переменным успехом.
Dual-Stack позволяет устройству запускать IPv4 и IPv6 параллельно, в то время как DS-Lit (Dual-Stack Lite) — это технология, которая позволяет интернет-провайдерам переходить в сеть IPv6, одновременно обрабатывая истощение IPv4-адресов.
Решили ли приведенные выше исправления вашу проблему? Не стесняйтесь написать нам, если у вас есть какие-либо вопросы или предложения.
Источник
Describe the bug
Getting network error when sending form data and server’s response is not received in browser.
This appears and there is no request in the network tab
However, on the server, console logging req.headers and as you can see, the content length is the file size
I don’t have any cors middleware.
To Reproduce
const uploadMenu = (e: any) => {
const file = e.target.files[0];
const formData = new FormData();
formData.set('file', file);
fileInput.current.value = '';
const response = await await axios({
method: 'post',
url: '/api/v2/merchant/auth/menu/upload',
params: { merchant_id: merchantId },
data: formData
})
.then((response) => {
return response;
})
.catch((err) => {
console.log(err);
if (err.response) {
return err.response;
} else if (err.request) {
return err.request;
} else {
return false;
}
});
}
Expected behavior
Axios should be able to receive the response sent from the server, rather than instantly giving a network error.
Environment
- Axios Version 0.21.1
- Adapter HTTP
- Browser Chrome
- Browser Version 90.0.4430.93
- Node.js Version 14.16.0
- OS: Windows 10
- Additional Library Versions React 16.13.7
The strangest thing is, why doesn’t my request show up in the network tab but I get it on the server? Why is axios giving instant network error when the server actually received the request?
Additional context/Screenshots
I am trying to check the headers content-length
and send a file size too big response before it reaches multer, because I think multer uploads the file first before it checks the filesize in the fileFilter
function.
If I let the request go through multer, multer will be able to send the response and axios will receive the response.
This causes the issue
app.post('/api/v2/merchant/auth/menu/upload', (req, resp, next) => {
if (parseInt(req.headers['content-length'] > 10000000) {
return resp.status(400).send('The file is too big')
}
},
(req, resp, next) => {
upload.single('file')(req, resp, (err) => {
return resp.send(200).send('Menu uploaded')
}
});
However, if I send a request that is not form data, it works. If I remove the first middleware or don’t send a response in the first middleware, it works. Any response outside of upload.single('file')
will raise the issue.
Proof that the server is sending the response.
Facing the same issue.
In my case I send API-requests via POST with request params for backend API as json in body. Then i get response on that POST-request, in contains some data from my API.
The problem I (we) have here is tricky one. I figured out if Content-Length on the response is over about 3mil, right after receiving it I get either CONNECTION_RESET or CONNECTION_CLOSE with status-code 200 (HTTP: OK). From here Axios call went into error (‘catch’) so my response.data was already forever lost.
The exact same request works in Firefox. And from Postman. I just get responce with status 200 and my data.
Browser definetly loading response, it can be seen in chrome debugger, and right after all was loaded — network error.
I tested it in Edge — it fails as well, so I started to think it’s not Google Chrome but Chromium-related issue.
Another mistery I can’t resolve — the same request works in Chrome, from localhost in dev-environment (both front and api on localhost). It gives the exact same responce (DB shared).
I tried to send response reply with stream insdead of object — no difference.
The dev environment, where request works in Chrome:
- OS: Windows 10 Pro x64
- Vue in dev-mode, serve on localhost:8080, http
- Fastify instance listening on localhost:3000, http
The prod environment, where request fails in Chrome:
-
OS: Ubuntu 18.04.3 LTS
-
Apache2 on port 80 -> 443, ssl, self-signed
-
Nginx in docker with builded Vue-app, listening on port 80 -> 443, ssl, self-signed
-
Docker-container listen on port 8080, redirects to nginx inside on port 443
-
Node.js in docker with fastify app, port 3000, ssl, self-signed
-
Docker-instance listen on port 3000, redirects to fastify on same port
Apache redirects requests on specific path (where app located) to same domain:8080 (apache:example.com:443/app -> docker:example.com:8080/app -> nginx:example.com:443/app)
Requests to API made directly to example.com:3000 and served by fastify https-server, so I assume neither apache2 nor nginx responsible for this (as expected, those request never appears in accesserror logs of both)
If my issue somehow related to this and I will find the demon behind it — I’ll share it here.
— UPD
Request dont work: Chromium hibiki latest-stable, Chromium dev v80.*, ms EDGE latest, Google Chrome latest
Request works on mobile Chrome from Apple AppStore.
Chrome extension is not the issue.
Chrome generated headers is not the issue (FF sending witn Connection: keep-alive, Chrome on some request (and this one) — doesn’t. Explicitly adding those headers did nothing)
request.onreadystatechange = function handleLoad() {
at node_modules/axios/lib/adapters/xhr.js
added at line 47 console.log(request)
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { console.log(request) return; }
Result in console with failed request
I checked netlog of two requests. One was with error, second — with success. They are both from same environment, same API-call, different params (dates on query). So only result data-set differs.
First one: the good one.
Look at HTTP2_SESSION, how it ends
t=11324 [st=8513] HTTP2_SESSION_RECV_DATA
--> fin = false
--> size = 1636
--> stream_id = 3
t=11324 [st=8513] HTTP2_SESSION_UPDATE_RECV_WINDOW
--> delta = -1636
--> window_size = 15694254
...
t=11324 [st=8513] HTTP2_SESSION_RECV_DATA
--> fin = true <---------------------- HERE
--> size = 0
--> stream_id = 3
t=11324 [st=8513] HTTP2_SESSION_RECV_GOAWAY <------------------------- AND HERE
--> active_streams = 0
--> debug_data = "[0 bytes were stripped]"
--> error_code = "0 (NO_ERROR)"
--> last_accepted_stream_id = 3
--> unclaimed_streams = 0
t=11324 [st=8513] HTTP2_SESSION_CLOSE
--> description = "Finished going away"
--> net_error = 0 (?)
t=11324 [st=8513] HTTP2_SESSION_POOL_REMOVE_SESSION
t=11324 [st=8513] -HTTP2_SESSION
URL_REQUEST finale of this
t=11324 [st=8507] HTTP2_STREAM_UPDATE_RECV_WINDOW
--> delta = -6203
--> stream_id = 3
--> window_size = 6244320
t=11324 [st=8507] -HTTP_TRANSACTION_READ_BODY <- Gracefully finished read-job
t=11324 [st=8507] URL_REQUEST_JOB_FILTERED_BYTES_READ
--> byte_count = 47136
t=11324 [st=8507] HTTP_TRANSACTION_READ_BODY [dt=0]
t=11324 [st=8507] -REQUEST_ALIVE
Now look at the HTTP2_SESSION from failed request. The last ST is 11900
t=11922 [st=11900] HTTP2_SESSION_RECV_DATA
--> fin = false
--> size = 2059
--> stream_id = 3
...
t=11922 [st=11900] HTTP2_SESSION_RECV_DATA <---------------------- LAST RECEIVE DATA
--> fin = false <-------------- HERE
--> size = 2203
--> stream_id = 3
t=11922 [st=11900] HTTP2_SESSION_UPDATE_RECV_WINDOW
--> delta = -2203
--> window_size = 15652754
t=11922 [st=11900] HTTP2_SESSION_CLOSE <--------------- AND IT'S CLOSED
--> description = "Connection closed"
--> net_error = -100 (ERR_CONNECTION_CLOSED)
t=11922 [st=11900] HTTP2_SESSION_UPDATE_RECV_WINDOW
--> delta = 2023
--> window_size = 15654777
URL_REQUEST finale of this
t=11922 [st=11886] HTTP2_STREAM_ERROR
--> description = "Abandoned."
--> net_error = "ERR_CONNECTION_CLOSED"
--> stream_id = 3
t=11922 [st=11886] -HTTP_TRANSACTION_READ_BODY
--> net_error = -100 (ERR_CONNECTION_CLOSED)
t=11922 [st=11886] FAILED
--> net_error = -100 (ERR_CONNECTION_CLOSED)
t=11922 [st=11886] -REQUEST_ALIVE
--> net_error = -100 (ERR_CONNECTION_CLOSED)
So. From here we can assume — not clear why, but:
- while using HTTP/2 in node (Fastify app)
- on responses larger than unknown amount
Client will not get HTTP2_SESSION_RECV_DATA packet with fin = true
flag, so Chrome will not understand this is the end. Also, no GOAWAY packet where it should be one at the end of HTTP2 session (by HTTP2 documentation). Client just gets last portion of body and then API go silent, so Client assume it’s not the end of data, perhaps connection closed or connection reset. It’s abnormal for Client anyway, so he throws an error and dumps recieved portion (by client perspective — it’s a portion) of that data.
In total: now I’m 84.7% sure it’s issue with node https server uses http2 sessions.
Why it works on non-chromium-based browsers? I guess they just keep what they got and still try to parse the data even then session was not closed properly.
I solved this issue with my setup.
const fs = require('fs')
const path = require('path')
const fastify = require('fastify')({
http2: false, // <-------------- HERE
https: {
allowHTTP1: true, // fallback support for HTTP1
key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
}
})
So in my situation — it was totally not an axios issue, it’s node-http2 and/or it’s use in fastify. I doubt fastify maintain sessions and form packets for http2, so probably just http2-webServices in node.
Express probably uses the same params, since it’s all about node-http2 npm. Maybe explicitly disabling it in app will work for Express as well.
After checking with snippets got your issue,
From the first middleware, you are not forwarding your request with next() . That is the place your request got broken. The issue with the backend not with axios and moreover validate the file size before upload using multer by example.
var maxSize = 1 * 1000 * 1000;
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, 'public/upload');
},
filename: function (req, file, callback) {
callback(null, file.originalname);
},
onFileUploadStart: function(file, req, res){
if(req.files.file.length > maxSize) {
return false;
}
}
});
var upload = multer({ storage : storage}).single('bestand');
router.post('/upload',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
console.log(req.file);
res.redirect(req.baseUrl);
});
});
By default multer having this functionality.Have a great day.
Thanks @FuketsuBaka saved me a bunch of time — was getting this on a large 2mb response
This is my first time using axios and I have encountered an error.
axios.get(
`http://someurl.com/page1?param1=1¶m2=${param2_id}`
)
.then(function(response) {
alert();
})
.catch(function(error) {
console.log(error);
});
With the right url and parameters, when I check network requests I indeed get the right answer from my server, but when I open console I see that it didn’t call the callback, but instead it caught an error.
Error: Network Error
Stack trace:
createError@http://localhost:3000/static/js/bundle.js:2188:15
handleError@http://localhost:3000/static/js/bundle.js:1717:14
asked Aug 31, 2017 at 11:16
6
If Creating an API Using NodeJS
Your Express app needs to use CORS (Cross-Origin Resource Sharing). Add the following to your server file:
// This should already be declared in your API file
var app = express();
// ADD THIS
var cors = require('cors');
app.use(cors());
For fuller understanding of CORS, please read the Mozilla Documentation on CORS.
answered Nov 15, 2017 at 21:25
jacobhobsonjacobhobson
9968 silver badges14 bronze badges
5
my problem was about the url I was requesting to. I hadn’t inserted http://
at the beginning of my url. I mean I was requesting to a url like 92.920.920.920/api/Token
instead of http://92.920.920.920/api/Token
. adding http://
solved my problem.
phoenix
7,3885 gold badges37 silver badges44 bronze badges
answered Apr 30, 2019 at 10:57
1
It happens when you work on localhost and forgot to add http://
Wrong Usage
const headers = {
"Content-Type": "application/json",
Authorization: apiKey,
};
const url = "localhost:5000/api/expenses/get-expenses";
axios.get(url, { headers });
// NETWORK ERROR
The correct one is
const headers = {
"Content-Type": "application/json",
Authorization: apiKey,
};
const url = "http://localhost:5000/api/expenses/get-expenses";
axios.get(url, { headers });
// WORKS FINE IF YOU HANDLED CORS CORRECTLY IN THE SERVER SIDE
answered Dec 6, 2020 at 8:07
1
In addition to @jacobhobson answer, I had also used some parameters to made it work.
app.use(cors({origin: true, credentials: true}));
answered Nov 28, 2019 at 13:13
0
I was having same issue on production on digital ocean droplet. I was using axios in ReactJS to call Node.js API.
Although I included cors
const cors = require('cors');
app.use(cors());
But I still had to add
res.header( "Access-Control-Allow-Origin" );
before calling out my controller. And it worked for me. There I realized that cors is not working properly. So I uninstalled and installed them again and It Works!
Complete code is here.
So either you use
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "x-access-token, Origin, X-Requested-With, Content-Type, Accept");
next();
});
or use
app.use(cors());
It’s the same.
answered Jun 29, 2020 at 5:34
5
I received a network error with axios 0.27.2 when I was trying to upload an image to our server. After I set headers like below no error is received.
headers:{"Accept":"application/json, text/plain, /","Content-Type": "multipart/form-data"}
and you need to check with your api request’s body type in your collection like if it’s form-data or x-wwww-form-urlencoded or ..etc.
Skoua
3,1913 gold badges41 silver badges50 bronze badges
answered May 11, 2022 at 17:18
A.A.A.A.
712 bronze badges
In my case I used «https» instead of «http«, check that too.
answered May 16, 2021 at 14:28
1
Make sure you have the same port number in cors({ origin : [ "http://localhost:3001"]})
and the .env
file.
Elletlar
3,1067 gold badges30 silver badges38 bronze badges
answered Nov 3, 2020 at 9:58
This is happening because of restrict-origin-when-cross-origin policy.Browser sends a pre-flight request to know whom the API server wants to share the resources.
So you have to set origin there in API server and send some status.After that the browser allow to send the request to the API server.
Here is the code.I am running front-end on localhost:8000 and api server is running on port 6000.
const cors = require("cors");
app.options("*", cors({ origin: 'http://localhost:8000', optionsSuccessStatus: 200 }));
app.use(cors({ origin: "http://localhost:8000", optionsSuccessStatus: 200 }));
I have set origin as my front-end url, If You set it to true , then it will allow only port 8000 to access rosource, and front-end running on port 8000 can not access this resource. Use this middleware before route in api server.
answered Oct 7, 2021 at 8:45
I have resolved my issue by adding this header.
var data = new FormData();
data.append('request', 'CompaniesData');
var config = {
method: 'post',
url: baseUrl, headers:{"Accept":"application/json, text/plain, /","Content-Type": "multipart/form-data"},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
answered May 17, 2022 at 11:18
i’m using axios in react-native as android and .net as backend, i have same issue but i can’t solve the problem. I think it is security problem when i type the url in chrome it warns me about that in emulator.
axios("http://10.0.2.2:5001/api/Users/getall")
.then((result) => setUsers(result.data.data))
.then((json) => {
return json.data;
})
.catch((error) => {
console.error(error);
})
.then((response) => response.parse());
answered May 21, 2022 at 19:44
In my case, I’m using Hapi.js as the backend, so all I had to do is set the cors value to true as in the code below;
const server = Hapi.server({
port: 4000,
host: 'localhost',
state: {
strictHeader: false
},
routes: {
cors: true
}
});
answered Jun 10, 2022 at 12:42
BenBen
3854 silver badges15 bronze badges
-
change the
port
number of your node server.
It took more than 3 hours to solve this error. Solution ended with changing port numer which was initially set to 6000, later set to 3001. Then it worked. My server localhost base url was:"http://localhost:6000/data"
I changed port number in
app.listen()
on server and from frontend I call thatGET
route inasync
function as
await axios.get('http://localhost:3001/data')
.
It is working fine now. -
If you face the address issue:
address already in use :::#port
Then on command prompt:
killall -9 node
answered Aug 11, 2022 at 16:46
I just want to let you know that after searching for a solution for two days, I was able to solve my error.
Since the proxy was the source of the issue, I must configure a proxy in the package.json file, and I have to follow these instructions in the function that uses Axios:
try { await axios.post("user/login", formData).then((res) => { console.log(res.data); }); } catch (error) { console.log(error.response.data.message); }
and in package.json file need to add a proxy:
"proxy": "http://localhost:6000",
for better understand check this documentation: enter link description here
answered Nov 3, 2022 at 16:10
1
If you are running react native
in development
while using real device
connected via USB(and the API server is being accessed via development machine IP), ensure the development machine and the device are both connected to the same network
answered Feb 4 at 12:12
Troubleshooting the PuTTY Network Error
Software caused connection abort
Read what PuTTY has to say about the error
This is a generic error produced by the Windows network code when it kills an established connection for some reason. For example, it might happen if you pull the network cable out of the back of an Ethernet-connected computer, or if Windows has any other similar reason to believe the entire network has become unreachable.
Windows also generates this error if it has given up on the machine at the other end of the connection responding to it. If the network between your client and server goes down and your client then tries to send some data, Windows will make several attempts to send the data and will then give up and kill the connection. In particular, this can occur even if you didn’t type anything, if you are using SSH-2 and PuTTY attempts a key re-exchange.
(It can also occur if you are using keepalives in your connection. Other people have reported that keepalives fix this error for them. (There are pros and cons of keepalives.))
We are not aware of any reason why this error might occur that would represent a bug in PuTTY. The problem is between you, your Windows system, your network and the remote system.
Try a different SSH client
Most likely the problem exists somewhere between PuTTY and the target SSH server. To provide evidence for this, use a different SSH client like (http://kitty.9bis.net) and see if the problem happens on that as well. It probably will which will isolate the problem away from PuTTY.
Suspect spotty Internet connection
The problem may be the spotty Internet connection. Internet Connectivity Monitoring the uptime of an Internet connection is a good way of determining if your ISP are losing packets and is to blame for PuTTY going down. Get some software that tests the uptime of an Internet connection. For example, http://code.google.com/p/internetconnectivitymonitor/. Frequent and long disconnections from the Internet is a breach of ISP service requirements. If this is the case, it will be difficult to prove it’s the ISP’s fault, as tech support automatically blames these sorts of issues on your computer, OS, router, and wiring to your home. If you are using cable Internet and living out in the boonies, it could be possible that defective hardware in your neighbor’s homes could be sending static on the line for a few seconds/minutes when they first turn it on. Finally, it’s possible that there is defective hardware in the ISP’s network to your home. The cost to ISPs to replace their hardware is so high, that often times they won’t do it unless there are enough subscribers in an area to warrent the cost.
Suspect the wired/wireless router
Are you connecting through a wired/wireless router? How old is it? Your router might be the problem. Old wireless and wired technology can get old and drop connections sporadically and restart them, causing PuTTY to die. Remove these components from the equation and see if that solves the problem. Try a wired connection and/or different router to see if that fixes the problem. I had a Linksys wireless router suffer this slow death and drop connections and restart them.
Suspect the operating system providing the SSH connection
The computer you are connecting to with SSH has a policy for number of seconds to keep SSH connections alive. This number is set low for security reasons, and you could increase it. Where this setting is depends on what operating system you are using that provides SSH.
If you are using PuTTY through a virtual machine
If you are using PuTTY passing through a virtual machine, there may be a policy on the virtual machine which is breaking your SSH connection to the server when it thinks it is inactive. Increasing these values depends on which virtual machine software and operating system you are using.
If the Internet connection is bad, SSH client connection workarounds:
If your ISP provides an unstable connection then you could make the disconnections less painful with «ssh autologin». What you do is generate a public and private key. And you tell your foreign server to automatically let in anyone who provides an accurate private key. It doesn’t solve your problem completely, but when the Internet outage happens, all you do is close the window, double click an icon, and you are immediately taken back to your home folder command line without entering a username/password.
This will help you with that:
Is there a way to «auto login» in PuTTY with a password?