Javascript network error occurred

How to catch net::ERR_CONNECTION_REFUSED

or anything else.. the question would be, how to get the kind of error?

You won’t get specific information about the error, by intent (because otherwise it may be abused to gain insight into the user’s internal network, for instance).

4 Answers 4

I even tried to achieve the goal using javascript XMLHttpRequest()

var xhttp= new XMLHttpRequest(); try < xhttp.onreadystatechange = function() < console.log(xhttp); if (xhttp.readyState == 4 && xhttp.status == 0) < alert("Unknown Error Occured. Server response not received."); >>; xhttp.open("POST", "http://localhost:8080/data", true); xhttp.send(); >catch(e)

Above snippet only gives generic error handling, while I am not getting exact reason behind the error. The try. catch statement fails to catch anything, because none of the functions inside try block is throwing any exceptions. It seems XMLHttpRequest is running in background thread, so its runtime error in not being catchable.

As jQuery is a library which is actually a javascript, it will also behave same for $.post() because $.post() is also using XMLHttpRequest behind the curtain.

Below is the jQuery version, which also will handle generic error, as we can not exactly know reason for error.

try < $.post('http://localhost:8080/data', <>, function(res) <>).fail(function() < alert("Unknown Error Occured. Server response not received."); >); > catch (e)

As javascript XMLHttpRequest() is still not efficient enough for handling different error states, we can not know exact reason behind the network error for AJAX requests. We can only capture generic errors and some other known status codes like

Читайте также:  Html кнопка запустить скрипт

Update: It has been a very long time since I last updated this post. I saw few answers which try to achieve similar objectives but still with very little success. As mentioned in some of the answers in this thread we can also use XMLHttpRequest.onerror callback function for catching some generic errors but if you are still working with IE, then maybe it won’t work.

Источник

Saved searches

Use saved searches to filter your results more quickly

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. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Axios returns a generic «Network Error» even when the request got a response code #4420

Axios returns a generic «Network Error» even when the request got a response code #4420

Comments

Describe the bug

When making a request to my API, the catch block has a generic «Network Error» message, but when checking in the network inspector the request got a response code 413. This causes my users to incorrectly report that ‘the website thinks i dont have a solid internet connection’. I suspect this happens for other codes too because this has been going on for a while.

To Reproduce

Make a request with a very large payload to trigger a 413 response

Expected behavior

The catch block should have the response code

Environment

  • Axios Version: 0.25.0 and 0.21.2
  • Adapter: xhr (i think? i dont remember changing this, so i guess whatever is default?)
  • Browser: Chrome
  • Browser Version: 97.0.4692.99
  • Node.js Version: 14.18.1
  • OS: OSX 12.1

Additional context/Screenshots

axiosInstance .post("/results/add",  result: completedEvent, //this is very big >) .then((response) =>  // handle response >) .catch((e) =>  console.log(e); //this console logs Error: Network Error // at createError (monkeytype.js:formatted:35086:25) // at XMLHttpRequest.handleError (monkeytype.js:formatted:34457:28) >);

image
image

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

Same issue happens in my application. I’m waiting for more details

Screenshot 2022-01-25 at 22 50 17

Same issue happens in my application too.
React Native, iOS 15.0, iPhone 12 simulator, axios 0.24.0 (tried 0.25.0 — the same issue)

This comment has been hidden.

Any chance you could have a look into this? I feel like this is quite important, since it makes it impossible to do proper error handling, makes it harder to debug and confuses users.

@manugch @Miodec do you have any DNS ad blockers? I disabled my AdGuard and now it works fine. Can you check any any blockers/vpn?

@manugch @Miodec do you have any DNS ad blockers? I disabled my AdGuard and now it works fine. Can you check any any blockers/vpn?

No Adblockers. I also see the error happening on visitor devices in our sentry logs, over 112 iOS devices by now who crashed with that unhandled «Network Error».
It affects only iOS devices as I said before Mac, iPhone, iPad mostly iOS/Safari 14.1.X

@manugch @Miodec do you have any DNS ad blockers? I disabled my AdGuard and now it works fine. Can you check any any blockers/vpn?

Tested without adblock — same thing.

Somewhat similar situation for my ecommerce store as well. 91% «Network Error» on Safari(iOS). Safari follows a strict «Same Origin Policy» and I have noticed that most MarTech integrations throw errors on Safari. However, for me, these 91% errors are in my app and not in with 3rd party tags/pixels.

I am seeing the exact same issue. A generic error saying Error: Network Error with no other information when getting 403s. According to the docs, the error should still include the response code and headers, but it doesn’t.

  • Axios 0.21.4 & 0.26.0
  • Node.js v16.13.1
  • Firefox 96.0.3 & Chrome 98.0.4758.82
  • Windows 10 Pro (Build 19041)

I had a similar problem. I realized that was a CORS problem. Do you have any OPTIONS call before the actual API call?

@pierroberto I see this error for API calls which are on same domain, relative paths like /api/getsomedata .

Looking at the code, there seems to be a catch all in the XHR adapters https://github.com/axios/axios/blob/master/lib/adapters/xhr.js#L118

It’s not there in the HTTP adapter which will give the correct error so you may want to switch to that

I think it’s because the XHR spec doesn’t give any clue about the error, so I don’t think it can be fixed. As your then dependant on the browser implementation to trigger the .onError only if HTTP code = 0, and it seems some will trigger this with codes in the 400 range

I think it’s because the XHR spec doesn’t give any clue about the error, so I don’t think it can be fixed.

So, why does the console correctly show errors like ERR_FAILED 413 in this case, or CONNECTION_REFUSED or SSL_CERT_DATE_INVALID that I ran into in other cases? All of them give Network Error , but somehow show up correctly in the console.

Pretty sure using HTTP is not the best solution as its not supported in every browser (webpack replaces it with xhr)

EDIT: Right.. Im assuming its related to the // Real errors are hidden from us by the browser comment.

Alright, I figured things out (im still learning so some details could be wrong)

Basically, there is no way around it. Axios is just a wrapper for XMLHttpRequest (just realised that’s where the XHR acronym comes from) to make it a bit easier to use and less complicated to write. Axios gives us a Network Error because xhr itself doesn’t give us any info about the error. You can see for yourself by doing a simple request to an endpoint that doesn’t exist:

const oReq = new XMLHttpRequest(); oReq.addEventListener("error", (e) =>  console.log(e); >); oReq.open("GET", "http://localhost:5005/"); oReq.send();

image

The console.log will give us (drumroll please):

Absolutely nothing 🙂

However, the console error will show GET http://localhost:5005/ net::ERR_CONNECTION_REFUSED (still don’t understand why the error is in the console but not in the event listener parameter)

So either way, this is not the fault of Axios. The only fix here that was mentioned by @Tofandel is to switch to the HTTP adapter at the expense of some compatibility — I don’t know how big this expense is exactly. Axios uses Node’s HTTPS module in its HTTP adapter and I’m not sure yet what things like webpack will replace it with. If I remember ill update this comment with my further findings.

Источник

Network Error AxiosError: Network Error at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:105169:14)

I am building an Amazon clone and have implemented Payment through stripe and now after entering card details, it redirects to the orders page (which I want it to) but then it shows this «Network Error AxiosError: Network Error at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:105169:14)» on the screen and when I open stripe to see it shows
enter image description here These are my code files Payment.js

import React, < useEffect, useState >from "react"; import "./Payment.css"; import < useStateValue >from "./StateProvider"; import CheckoutProduct from "./CheckoutProduct"; import < Link >from "react-router-dom"; import < CardElement, useElements, useStripe >from "@stripe/react-stripe-js"; import CurrencyFormat from "react-currency-format"; import < getBasketTotal >from "./reducer"; import axios from "./axios"; import < useNavigate >from "react-router-dom"; function Payment() < const [< basket, user >, dispatch] = useStateValue(); const navigate = useNavigate(); const stripe = useStripe(); const elements = useElements(); const [succeeded, setSucceeded] = useState(false); const [processing, setProcessing] = useState(""); const [error, setError] = useState(null); const [disabled, setDisabled] = useState(true); const [clientSecret, setClientSecret] = useState(true); useEffect(() => < //Generate the special stripe secret which allows us to charge the customer const getClientSecret = async () =>< const response = await axios(< method: "post", url: `/payments/create?total=$`, >); setClientSecret(response.data.clientSecret); //Stripe Expects total in currency subunits >; getClientSecret(); >, [basket]); const handleSubmit = async (event) => < event.preventDefault(); setProcessing(true); const payload = await stripe .confirmCardPayment(clientSecret, < payment_method: < card: elements.getElement(CardElement), >, >) .then((< payment >) => < //paymentIntent = Payment Confirmation setSucceeded(true); setError(null); setProcessing(false); dispatch(< type: "EMPTY_BASKET", >); navigate("/orders", < replace: true >); //Here instead of push we have used replace because after successful payment we dont want to come back to the payments page >); >; const handleChange = (event) => < //Listen for changes in the Card Element and display any errors the customer makes while entering the card details setDisabled(event.empty); setError(event.error ? event.error.message : ""); >; return ( 

Checkout ( Items)

Delivery Address

76/4A Rajpur Road

Dehradun

Review Items & Delivery

( image= price= rating= /> ))>

Payment Method

> />

Order Total : > decimalScale= value= displayType= thousandSeparator= prefix= />

>
); > export default Payment;
import "./App.css"; import Checkout from "./Checkout"; import Header from "./Header"; import Home from "./Home"; import < BrowserRouter as Router, Routes, Route >from "react-router-dom"; import Login from "./Login"; import React, < useEffect >from "react"; import < auth >from "./firebase"; import < useStateValue >from "./StateProvider"; import Payment from "./Payment"; import < loadStripe >from "@stripe/stripe-js"; import < Elements >from "@stripe/react-stripe-js"; import Orders from "./Orders"; const promise = loadStripe( "pk_test_51NRKdkSGdggXhtrctnXw7BsWnkeXoSwRsRYKxZ7o17Nqx55wvPdMQJwSpm4BCXZoSPiIFW9KOrPAFAwoUylvfEt100BhWELocF" ); function App() < const [<>, dispatch] = useStateValue(); useEffect(() => < //Will only rum once the app component loads auth.onAuthStateChanged((authUser) =>< console.log("The user is : ", authUser); if (authUser) < //The user was Logged In / The user just Logged In dispatch(< type: "SET_USER", user: authUser, >); > else < //The user was logged out dispatch(< type: "SET_USER", user: null, >); > >); >, []); return (  
> /> > /> > > > > > > />
); > export default App;
/** * Import function triggers from their respective submodules: * * const = require("firebase-functions/v2/https"); * const = require("firebase-functions/v2/firestore"); * * See a full list of supported triggers at https://firebase.google.com/docs/functions * */ const < onRequest >= require("firebase-functions/v2/https"); const logger = require("firebase-functions/logger"); // Create and deploy your first functions // https://firebase.google.com/docs/functions/get-started // exports.helloWorld = onRequest((request, response) => < // logger.info("Hello logs!", ); // response.send("Hello from Firebase!"); // >); const functions = require("firebase-functions"); const express = require("express"); const cors = require("cors"); const stripe = require("stripe")( "sk_test_51NRKdkSGdggXhtrcB8ZbigCqipRaMbRZVIJGYGGhAr7tM9fkCqXMaBJL7ubJhfxgDfxaPhYxG3nrtUarNhvhQ76U00zgF0sXPa" ); //API //App Config const app = express(); //Middleware app.use(cors(< origin: true >)); app.use(express.json()); // API Routes app.get("/", (request, response) => response.status(200).send("hello world")); app.post("/payments/create", async (request, response) => < const total = request.query.total; console.log("Payment Request Received BOOM. for this amount ->", total); try < const paymentIntent = await stripe.paymentIntents.create(< amount: total, currency: "usd", >); // Send the client secret as a response response.status(201).send(< clientSecret: paymentIntent.client_secret, >); > catch (error) < console.error(error.response.data); response.status(500).send(< error: "An error occurred while creating the payment intent.", >); > >); // Listen Command exports.api = functions.https.onRequest(app); //http://127.0.0.1:5001/challenge-940e1/us-central1/api 
import axios from "axios"; const instance = axios.create(< baseURL: "http://127.0.0.1:5001/challenge-940e1/us-central1/api", //The API (cloud Function) URL >); export default instance; 

Источник

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