Axios: Set a code/status for "Network Error"

Created on 20 Jul 2016  ·  69Comments  ·  Source: axios/axios

I'm trying to detect when my server is down so that I can display an appropriate error message to the user.

In this case, axios network requests throw an error which is different from all other axios errors, as discussed here: https://github.com/mzabriskie/axios/issues/204

In my code, it seems the only way to detect this error is to check err.message:
if (err.message === "Network Error"){/*tell user the server is down*/}

This bothers me because string comparisons are a little risky; perhaps some day this message will be translated, and my code will fail.

It would be great if err.status or err.code (or err.???) were set to some documented value that we can check for in our code.

Is there any other way to detect this scenario that I'm missing?
Thanks all!

Most helpful comment

I'm having this issue. Can anyone help me please?

The server response is 401 but axios gives me this:

error --> "Network Error"
error.response --> undefined
error.status --> undefined

All 69 comments

I think you're right. A status code would make sense.

As someone said in #204, there are some cases where it is impossible to catch network errors in the browser, so Axios responds with a generic error (new Error('Network error')). If you want to distinguish them from bad responses (status code !== 2xx or custom check) I think the best way is just checking the status property instead of the error message. E.g.:

axios.request(options).catch(function(error) {
  if (!error.status) {
    // network error
  }
});

I think setting a custom status code would be a bad idea (it could cause more confusion) and setting a specific property would not help at all because we only have a single error case.

Of course in Node.js is easier because you have access to the actual error and can check according to the Node.js documentation.

Ah, so any error thrown by an Axios call is guaranteed to either 1) have a status, or 2) be a generic network error? I suppose that's good enough.

So far, I cant able to get the error code like 404,500.., Still I am getting Network Error. How to solve this?
instance.post('/foo', {request_id : 12345})
.then(function(response) {})
.catch(function(error){
console.log(error); // Network Error
console.log(error.status); // undefined
console.log(error.code); // undefined
});

Network Error means Axios couldn't connect to your server at all, so it can't get any error code from the server. Maybe try it with another tool (curl, postman, or a browser) to ensure you can connect to it?

I can able to connect with my server, it actually returns 404 Error code and with some other API calls server returns 500 Internal server error, but still i can't able to get the network error code through scripting(i.e.,console.log(error.status); // undefined ).

It's in error.response.status.

I'm having this issue. Can anyone help me please?

The server response is 401 but axios gives me this:

error --> "Network Error"
error.response --> undefined
error.status --> undefined

When error is "network error" that means Axios coudn't connect to your server, or for some reason does not get the response from your server. So that 401 error is never making it into Axios. Maybe post a question with some sample code on StackOverflow?

Ran into this when using AWS API-Gateway. For anyone seeing the same issues it's a problem with 4xx errors (in my case a 401) not responding with the CORS headers. Spent hours troubleshooting this damn issue! Thanks @jonathan-stone for pointing my troubleshooting in the right direct.

@codygreen I'm still having this issues and I ran into this https://forums.aws.amazon.com/message.jspa?messageID=763752

Have you found a workaround?

Does anyone have any solutions to this problem?

My problem was with Jest+ Axios. I solved it by adding this to my package.json:

"jest": {
    "testEnvironment": "node"
}

This works, although I can't seem to find documentation to support it. I am assuming that error.response should be empty on a network error otherwise it is an api error.

axios.request(options).catch(function(error) {
  if (!error.response) {
    // network error
  } else {
    // http status code
    const code = error.response.status
    // response data
    const response = error.response.data
  }
});

Did anyone find a best solution about this? Axios people make some noise :(

I also got this error today, I don't know what the problem is, this is my script:

js var url = "http://localhost:8000/"; Axios.get(url).then(function(response){ alert(response) }).catch(function(error){ alert(error) });

http://localhost:8000/ returns a JSON response, this does not work on other hosts

It might be a Cors Error.

Line 87, it has been set to 'Network Error' in the xhr adapter ? how to change this so that the error can be caught ?
https://github.com/axios/axios/blob/d7f021b8d4cc50bfa0653011bc02452d234d1255/lib/adapters/xhr.js#L84-L91

My bad, its not an issue but expected behavior due to browser security. XHR error responses now receives an ProgressEvent on error status codes.

I'm having the same issue. I believe it's an issue with CORS. Has anyone found a good solution for this?

@codygreen did you manage to fix your issue with API Gateway? Can't even figure out the response status code to help me debug further.

Same general problem here. For me it was definitely CORS. Browser was making OPTIONS requests to the server and I didn't have a handler setup for them (in node). Axios would complete the (failed) request successfully but with an undefined response

      return axios.httpClients.server.post('/someUrl, {
        someData:some_data
      }).then(response => {
        console.log(response);
        //the following errors out because response is undefined
        if (response.data && response.data.success === true) {
        }
      }).catch(err => {
           //catch never triggered
            console.log(err)
      });

What is your response code of the response? if it's a network error, when using the Fetch API browsers will log it to the console but not pass it to JavaScript for security reasons hence the body is empty. See FETCH STANDERS, if you want to access the network errors of the response, change the HTTP response code to 200 and include the error message in the body of the response.

My problem was a dns issue. It worked in postman but failed in axios. Tried a curl to find out that it was also failing there. So my DNS was not configured correctly. Check that if you run into this issue.

Not sure if this is applicable to other cases, but here is how I solved this same issue (considering that we are talking CORS).

On the Frontend side, make sure you are passing the headers as parameter in your PUT or POST requests:

const axiosParams = {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json',
  },
};

axios.put(`${api.url}/like`, axiosParams)
  .then((response) => {
    // ...
  });

And on the Backend side, make sure that you are using CORS with Express:

// server.js
const express = require('express');
const app = express();

var cors = require('cors'); // Yep, you need to install this
app.use(cors()); // Works 🎉

Refs: here and here.

Guys, I also struggling on this issue for quit while. But I figured out the issue of my axios post network createError on Android device now. The reason to axios Network Error is because the form data I passed to axios contains wrong type of data object I guess. I have include an image object(ImagePicker object from Expo) as a one of param of form data which not accept by axios I think. Axios might only receive string, float, int or image as param. image cannot pass as param, it is not an type of image, it is an react native object, I have removed it and include an image field as param by assign image.uri to value of param then it works. Hope this will help some of people who may encounter same problem as I was facing before.
Deleting some of your form data one by one when you are testing axios Network error, you will find out which one is the cause of issue.

~@codygreen @hammadzz did you find a solution to this with Amazon API Gateway?~

Update: if anyone stumbles on this with API Gateway and CORS, you'll need to add a access-control-allow-origin response header to your responses.

As someone said in #204, there are some cases where it is impossible to catch network errors in the browser, so Axios responds with a generic error (new Error('Network error')). If you want to distinguish them from bad responses (status code !== 2xx or custom check) I think the best way is just checking the status property instead of the error message. E.g.:

axios.request(options).catch(function(error) {
  if (!error.status) {
    // network error
  }
});

I think setting a custom status code would be a bad idea (it could cause more confusion) and setting a specific property would not help at all because we only have a single error case.

Of course in Node.js is easier because you have access to the actual error and can check according to the Node.js documentation.

If you're here from Google, note that this API is deprecated. This is from 2016, v <0.13.

You want to check for error.response when the server responds, error.response === undefined for offline status and the special case of error.code === 'ECONNABORTED' for timeouts.

Update: if anyone stumbles on this with API Gateway and CORS, you'll need to add a response header to your responses:

access-control-allow-origin: *

Definitely don't do this. Set the origins accordingly instead of *.

For me it was cors problem , if you are using laravel, and you define a

 ->middleware(['auth:api'])

you have to add all other middleware that you need to this route explicitly its not inherited

->middleware(['auth:api','cors']);

I also faced this issue, use your local IP address instead of localhost (eg 10.0.0.12:8083 ). it's worked for me.

So if I have the correct, the 0 status from an axios request seems to appear in some cases. but it cannot be programmatically determined exactly which case it's encountered.

These cases include when a CORS preflight request has failed, and hence the actual request is never even attempted. Because of this the 404 status would not be appropriate.

Someone needs to buy @joelnet a beer. This saved my day:

https://github.com/axios/axios/issues/383#issuecomment-308606088

Other people might have different problems, but that worked for me.

I am getting this error intermittently. I am guessing its not a CORS issue.
My api/server is a .net server.
Anyone else facing this intermittently ?

I was having this error because I wasn't specifying HTTP or https. Mainly code itself throw an error on protocol undefined. This should be handled or in error meta, it should be included.

As @jonathan-stone said, I don't think this can be rectified, because Axios simply doesn't know what happened. It's like sending your friend out for Funyuns and he says the store was closed. It says "always open" - why was the store closed. Did they close for good (404)? Is someone sick (500)? Did they run out of inventory (503)? He doesn't know, they're just closed (network error)!

I was getting this error when firing Axios in rapid succession against a local Express server trying to retrieve different kinds of data from my API. It's not that Axios didn't report a correct error - it can't - my Express server didn't respond with anything because it was too busy.

If I retry the request (using retry-axios from #164 ) I can get the data or maybe a real error if there's something wrong with the AVAILABLE server.

To solve the problem you need to specify always
Nginx

add_header 'Access-Control-Allow-Origin' * always;

To solve the problem you need to specify always
Nginx

add_header 'Access-Control-Allow-Origin' * always;

Don't do this. Never do this. You wouldn't deactivate your firewall just to let one connection through.

Hi guys, we have set up entity size protection on our proxy, it returns generic error but I'm unable to get the 413 status code... is it somehow possible?

Screenshot 2019-05-07 at 14 19 26

Have you tried the response object?
axios.get(url).then(stuff => console.log(Object.keys(stuff.response));

@ComputerCarl you think it has success response? Don't think so as it ends in catch but I can try it ...

Sorry! My head was elsewhere! Check the catch object ...catch(err => console.log(Object.keys(err.response));

Axios doc

I have in one of my programs;
err.response.data.message;

which I sent from Express;

app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  // this is err.response.data on Axios client
  res.send({ message: 'my custom error' });
});

@ComputerCarl but error.response is undefined, same as error.status :) You can see it on the screenshot, I have it in console.log already. Only error.request is XMLHttpRequest object, as you can see

Ok.. I don't know why you are getting two errors (the 413 in addition to the CORS) . However, if you are using Express, you should enable CORS;

const cors = require('cors');
// ...
app.use(cors());

Also, as I stated above, if the server flat-out rejects your request, then Axios doesn't know what caused the error. At this point, I'm stumped and you'll have to wait for someone smarter to answer. :-)

@ComputerCarl thanks for trying :-D CORS is fine, I have a lot of different calls to same API in app and these works fine. Even errors returned from API I can easily handle. The problem is with this only one canceled on the proxy level.

I don't know if this helps you, but I had created an application which was proxying requests. The framework I was using was gobbling up the Express error. Finally, after explicitly forwarding the error res.send({ message: messageFromProxy });, I was able to see an error and deal with it on the client.

Good luck.

@jonathan-stone said, Network Error means Axios couldn't connect to your server at all, so it can't get any error code from the server.

may be this will help someone.

error.data ;

@balwant-sd as you can see on the screenshot I've sent here, the browser correctly recognises the 413 status code, but axios doesn't

Even in network tab I can see 413 status code...
Screenshot 2019-06-03 at 15 42 12

As mentioned above a Login POST that returns a 401 error returns just 'Network Error' with code as undefined instead of 401.

So this error seems to be a misconfigured CORS error which reflects just on your network tab. I have the same issue as @ketysek, and it seems that my ngnix is not applying CORS for this. As before mentioned, a generic network error will never make it into axios error.response. Here i like to blame the Backend.. oh wait, i did that...

Hello i am also having same issue, even request getting proper response axios always return "Network Error" and goes to .catch(function(error) {}); par. is any one having solution for this problem ?

I had the same problem today. This issue is mostly about the backend not allowing origins cross site HTTP requests. In my case, I am using django so I just placed the corsheaders class as high as possible to the MIDDLEWARE :
MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', //..etc ]
And I created a CORS_ORIGIN_WHITELIST to only allow certain origins :
CORS_ORIGIN_WHITELIST = [ "http://localhost:8081" , //..etc ]
This is for django-cors-headers. If you are not a django user, you should check the documentation of your favorite cors headers module.

As someone said in #204, there are some cases where it is impossible to catch network errors in the browser, so Axios responds with a generic error (new Error('Network error')). If you want to distinguish them from bad responses (status code !== 2xx or custom check) I think the best way is just checking the status property instead of the error message. E.g.:

axios.request(options).catch(function(error) {
  if (!error.status) {
    // network error
  }
});

I think setting a custom status code would be a bad idea (it could cause more confusion) and setting a specific property would not help at all because we only have a single error case.

Of course in Node.js is easier because you have access to the actual error and can check according to the Node.js documentation.

the problem with this approach is let's say we run some code in axios.then and the code has some error, for example "assignment to constant" (which was my case), with the approach you mentioned, we will get network error for "assignment to constant"

code example :

axios(options).then(() => {
  const foo = '';
  foo = 'bar'; // will throw error "assignment to constant"
}).catch(error => {
  if (!error.status) {
    // "assignment to constant" will be considered as network error
  }
})

I use this utility function to catch network errors from lower in the call stack (prevents identifying non-axios errors as network errors):

function isNetworkError(err) {
  return !!err.isAxiosError && !err.response;
}

See https://github.com/axios/axios/pull/1419

I use this utility function to catch network errors from lower in the call stack (prevents identifying non-axios errors as network errors):

function isNetworkError(err) {
  return !!err.isAxiosError && !err.response;
}

See #1419

Solved the problem
Thanks

@mifi can you show a more detailed example of how you're using isNetworkError to prevent identifying non-axios errors as network errors?

Just like this:

try {
  ...
  some code that calls axios
  ...
} catch (err) {
  if (isNetworkError(err)) return alert(‘check your connection);
  throw err;
}

If it's a CORS error and you use Serverless, this can fix it:

resources:
  Resources:
    # CORS for 4xx errors
    GatewayResponseDefault4XX:
      Type: 'AWS::ApiGateway::GatewayResponse'
      Properties:
        ResponseParameters:
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
          gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
        ResponseType: DEFAULT_4XX
        RestApiId:
          Ref: 'ApiGatewayRestApi'

When error is "network error" that means Axios coudn't connect to your server, or for some reason does not get the response from your server. So that 401 error is never making it into Axios. Maybe post a question with some sample code on StackOverflow?

I'm also getting the same error, For me, It reaching the server and I'm responding with 403 and a JSON, which results in the Network Error in the Axios

I'm able to see the response in the browser network tab, but in the catch block err.response is undefined

image

image

@narenderv7 me too

@WarisR I have fixed this by allowing cors on the server-side. I thought Axios issue but actually it isn't. I can help you if you let me know the issue that you're really facing.

Add in the server 'Access-Control-Allow-Origin': '*'

@ketysek I'm having the same error

Screenshot from 2019-12-26 16-48-22

did you find a way to catch this error?

Hi guys, i have problem CORS error where was getting response with status 403 (4* & 5)
Nginx sending header "Access-Control-Allow-Origin" only for response status 2
& 3
*.

i resolve this problem edit nginx config from:
add_header 'Access-Control-Allow-Origin' '*';
to:
add_header 'Access-Control-Allow-Origin' '*' always;

I have the same issue i'm test it using axios 0.18.0 and 0.19.0

Steps:
i made i request with expired token sometimes the error.response came correctly, but sometimes the error response came undefined and the message is 'Network error'. Why is this happens thats a backend error or a bug in axios?

Sometimes it may be caused by the AD blockers in your browser ...
Try incognito or private mode, or download a new browser to test ...

@narenderv7 Yes, it's server side mistake. But I think Axios should be able to handle an error of this case, right?

I need to distingue those two cases:

As I checked. error return by the catch block is the same in both cases above.

There still an issue:
https://github.com/axios/axios/issues/1296

The Error still Exist , if any anybody has a solution for this issue Share with us please.

I use this utility function to catch network errors from lower in the call stack (prevents identifying non-axios errors as network errors):

function isNetworkError(err) {
  return !!err.isAxiosError && !err.response;
}

See #1419

the timeout error can also match those conditions.
image

Was this page helpful?
0 / 5 - 0 ratings