Skip to content
New issue

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

Returning "Network Error" on unauthorized error (401) #4921

Closed
sigespweb22 opened this issue Aug 19, 2022 · 27 comments
Closed

Returning "Network Error" on unauthorized error (401) #4921

sigespweb22 opened this issue Aug 19, 2022 · 27 comments

Comments

@sigespweb22
Copy link

Describe the issue

Axios request below is returning "Network Error", on API's unauthorized return.

The API is in Asp Net Core with Identity. Therefore, it is recognized that my API actually returns a 401, but my request callback is not allowing me to get this return code, so that I can handle this exception directly.

I understand that, of course, my axios request tried to connect to the server, however, the identity by default doesn't even establish this connection in cases of unauthorized, it just returns the code 401, so I imagine that then axios returns this condition that there really was a "Network Error", since that's exactly what happened.

I would like an idea of ​​how we can solve this.

This is the code for the request in question

axios.delete(userApi.deleteAsync, id, config).then((resp) => {
      dispatch(fetchData(getState().user.params))
      toast.success(resp.data.message)
      return resp.data.data
    }).catch((resp) => {

Environment

  • Axios Version [0.27.2]
  • Adapter [e.g. XHR/HTTP]
  • Browser [e.g. Chrome, Safari]
  • Browser Version [e.g. 22]
  • Node.js Version [16.16.0]
  • OS: [Win 10]
  • Additional Library Versions [React 18.1.0, Next 12.1.6]
@lavahasif
Copy link

Describe the issue

Axios request below is returning "Network Error", on API's unauthorized return.

The API is in Asp Net Core with Identity. Therefore, it is recognized that my API actually returns a 401, but my request callback is not allowing me to get this return code, so that I can handle this exception directly.

I understand that, of course, my axios request tried to connect to the server, however, the identity by default doesn't even establish this connection in cases of unauthorized, it just returns the code 401, so I imagine that then axios returns this condition that there really was a "Network Error", since that's exactly what happened.

I would like an idea of ​​how we can solve this.

This is the code for the request in question

axios.delete(userApi.deleteAsync, id, config).then((resp) => {
      dispatch(fetchData(getState().user.params))
      toast.success(resp.data.message)
      return resp.data.data
    }).catch((resp) => {

Environment

  • Axios Version [0.27.2]
  • Adapter [e.g. XHR/HTTP]
  • Browser [e.g. Chrome, Safari]
  • Browser Version [e.g. 22]
  • Node.js Version [16.16.0]
  • OS: [Win 10]
  • Additional Library Versions [React 18.1.0, Next 12.1.6]

find any solution?

@meza360
Copy link

meza360 commented Aug 25, 2022

What I understand, is that you are trying to get the status code(as integer) to then, handle or react with some event.

axios.delete(userApi.deleteAsync, id, config).then((resp) => {
      dispatch(fetchData(getState().user.params))
      toast.success(resp.data.message)
      return resp.data.data
    }).catch((resp) => {
		const { status } = resp.response;
		//console.log(status) to check the status of response

Let us know if this solves your issue.

@sigespweb22
Copy link
Author

I still don't have a definitive solution. Occasionally I created a hack, assuming for now that all connection errors are 401, so I return an exception in this pattern.

hack:

if (resp.message == 'Network Error') return toast.error("You do not have permission for this action.")

Descreva o problema

A solicitação do Axios abaixo está retornando "Erro de rede", no retorno não autorizado da API.
A API está em Asp Net Core com Identity. Portanto, é reconhecido que minha API realmente retorna um 401, mas meu callback de solicitação não está me permitindo obter esse código de retorno, para que eu possa lidar com essa exceção diretamente.
Entendo que, claro, minha requisição axios tentou se conectar ao servidor, porém, a identidade por padrão nem estabelece essa conexão em casos de não autorizados, apenas retorna o código 401, então imagino que então axios retorne isso condição de que realmente houve um "Erro de Rede", pois foi exatamente isso que aconteceu.
Gostaria de uma ideia de como podemos resolver isso.

Este é o código para o pedido em questão

axios.delete(userApi.deleteAsync, id, config).then((resp) => {
      dispatch(fetchData(getState().user.params))
      toast.success(resp.data.message)
      return resp.data.data
    }).catch((resp) => {

Meio Ambiente

  • Versão Axios [0.27.2]
  • Adaptador [por exemplo, XHR/HTTP]
  • Navegador [por exemplo, Chrome, Safari]
  • Versão do navegador [por exemplo, 22]
  • Versão do Node.js [16.16.0]
  • SO: [Win 10]
  • Versões Adicionais da Biblioteca [React 18.1.0, Next 12.1.6]

encontrar alguma solução?

I still don't have a definitive solution. Occasionally I created a hack, assuming for now that all connection errors are 401, so I return an exception in this pattern.

if (resp.message == 'Network Error') return toast.error("You do not have permission for this action.")

@sigespweb22
Copy link
Author

O que eu entendo, é que você está tentando obter o código de status (como inteiro) para então, manipular ou reagir com algum evento.

axios.delete(userApi.deleteAsync, id, config).then((resp) => {
      dispatch(fetchData(getState().user.params))
      toast.success(resp.data.message)
      return resp.data.data
    }).catch((resp) => {
		const { status } = resp.response;
		//console.log(status) to check the status of response

Deixe-nos saber se isso resolve seu problema.

Your suggestion unfortunately did not resolve the issue. Keeps returning status code 0.

My api is really blocking the connection of the axios call, so I agree that it really has to return that it is having difficulties connecting to the api, since that is exactly what is happening. However, the api when blocking the connection due to permissioning problems, it returns either a 401 or a 403, which are related to permissioning. So, I can't understand how axios can't handle this api return pattern. Anyway...

Thanks and I'm still waiting for an elegant solution.

@meza360
Copy link

meza360 commented Sep 3, 2022

Try to keep it simple, and avoid being redundant.

  • Check your axios header request, is it equal to your API header responses? eg. application/json, application/xml
  • Are you developing locally or in different domains?
  • How do you know your API is blocking the connection? have you tried with other client and getting a different result? eg postman, swagger.
  • Are you logging your API responses before its way back to see the real status code?

This doesnt seem like axios fault, looks like we are trying to find the status code on the wrong place of the request.
Do you have any other media, logging, or API chunk of code to take a deeper look?

@sigespweb22
Copy link
Author

sigespweb22 commented Sep 6, 2022

I've already checked most of the points raised by you.

Simply put, when I suspected the possible error reason, I simulated a rogue environment, and checked the api call callback through the google chrome console, that's exactly where I confirmed that the api was returning a 401 (Unauthorized), however, the api callback was not able to retrieve this status code, and as I reported above, the status code comes "0", understand?

Thanks for your help so far, hope we can find the solution soon.

@hypnotic-frog
Copy link

Did you find a solution for this. I'm having the same problem :-(

@sigespweb22
Copy link
Author

Did you find a solution for this. I'm having the same problem

Not yet my friend, but we are all in the fight. A solution will soon emerge.

@An0nymous0
Copy link

It may be a back-end problem, which seems to be related to cross domain. I encountered this problem when I started CORS with spring security.

@sigespweb22
Copy link
Author

It doesn't make sense since, cors doesn't return 401.

@An0nymous0
Copy link

这是没有意义的,因为 cors 不返回 401。

Cross domain setting error will lead to 5xx 4xx request, Axios returns 0

@jeremy303
Copy link

I think I'm seeing the same issue as well w/ the Salesforce API...

@sigespweb22
Copy link
Author

Right. The browser usually informs you when domain issues occur, which in my case did not. So, wouldn't it be ideal for axios to identify this cross-domain return and return a code better than 0? Of course, being certain that this is the same issue.

@sebas0811buitrago
Copy link

I'm having the exact same error, when having a 401 error axios returns this error
I checked the 401 error with the network inspector, any way to get these status from the error?

{
    "message": "Network Error",
    "name": "AxiosError",
    "stack": "AxiosError: Network Error\n    at XMLHttpRequest.handleError (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:168:14)",
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "env": {},
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "authorization": "some token",
            "Content-Type": "application/json",

        },
        "method": "get",
        "data": "null",
        "url": "/somePath",
        "baseURL": "someBaseUrl",
        "params": {
            "size": 500
        }
    },
    "code": "ERR_NETWORK",
    "status": null
}

@sigespweb22
Copy link
Author

sigespweb22 commented Dec 3, 2022

jasonsaayman, Can you please give us strength to close this matter?
Thanks!

@sigespweb22
Copy link
Author

Duplicated on issue #5173

@liujian1368928
Copy link

Hello friend, have you solved this problem? This problem has been bothering me for several hours. Changing the back end does not work and always returns 0

@DigitalBrainJS
Copy link
Collaborator

DigitalBrainJS commented Apr 24, 2023

Axios (XMLHttpRequest) cannot get the status code if:

  • a network error has occurred (on TCP/IP layer)
  • browser prevented JS from reading the request due to cross-domain request policy (CORS) or Mixed Content policy for HTTPs resources
  • the request was canceled/aborted/closed outside Axios (by browser, ad blocker, server-side)

@burt-tcc
Copy link

I had this issue when making a request to a dotnet API. Noticed that UseCors() was at the bottom, moving to the top before all other middleware fixed the issue for me.

@GitHubington
Copy link

I use local-ssl-proxy to test my Next.js frontend against my .NET Core backend.

In my case, the two issues I was having with axios and catch were...

  • Issue no.1 was development SSL Certificate, fixed by the option, NODE_TLS_REJECT_UNAUTHORIZED:

run-dev.bat

set NODE_TLS_REJECT_UNAUTHORIZED=0
start yarn dev
start npx local-ssl-proxy --source 3500 --target 3000
  • Issue no.2 was TypeScript, fixed by the type, AxiosError:

index.tsx

axios.post("Controller/Endpoint", values, {
    baseURL: Constants.API_URL,
    withCredentials: true,
    headers: {
        "Content-Type": "multipart/form-data"
    },
}).then((res) => {
    // consume response
}).catch((error: AxiosError) => {
    // consume error
    console.log("error - Endpoint: " + JSON.stringify(error.response, null, 4));
});

@rodrigo-web-developer
Copy link

If you're using .NET API, you need to ensure that .UseAuthentication() is after .UseCors(), because it is a cors issue that breaks the pipeline before the authorization (where the step returns 401) .

If you want to make certain that the problems is the axios library, try to test a fetch() request direct from DevTools console. If the problems persists, is not axios problem, but a pipeline configuration problem on server side.

@drillprop
Copy link

If you're using .NET API, you need to ensure that .UseAuthentication() is after .UseCors(), because it is a cors issue that breaks the pipeline before the authorization (where the step returns 401) .

If you want to make certain that the problems is the axios library, try to test a fetch() request direct from DevTools console. If the problems persists, is not axios problem, but a pipeline configuration problem on server side.

this fixed the issue for me. Thanks ❤️

@perutilli
Copy link

As @rodrigo-web-developer mentioned for .NET, for me using a spring backend, the problem was that by sending the response in the first filter, the cors header did not apply. I fixed this by adding the headers by hand like described here before sending the 401 https://stackoverflow.com/questions/16351849/origin-is-not-allowed-by-access-control-allow-origin-how-to-enable-cors-using

@Theodore-Kelechukwu-Onyejiaku

For DELETE requests, ensure to add the data and headers config. See example below:

await axios.delete(`${serverURL}/locations/delete`, {
  data: {
    foo: "bar,
  },
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${authToken}`,
  },
});

@syedzubair74
Copy link

I had this issue when making a request to a dotnet API. Noticed that UseCors() was at the bottom, moving to the top before all other middleware fixed the issue for me.

Thanks man. Really helped a lot. Love you!

@HamedSiaban
Copy link

I recently had this issue and did a lot debugging about it.
In the end it turned out that the problem lies in the back end side.

Your server should set Access-Control-Allow-Origin: * or any other valid value in it's response headers when it's returning an unauthorized 401 response.

Usually they set this CORS values for successful responses, but omit them in error responses, Thus this issue happens.

*Hint for people with less knowledge about CORS issues:
In order to make sure that this is the issue, send your api without authentication headers in terminal with cUrl for example.
If you get 401 error (and not some arbitrary error from server), then probably everything is ok in front side and your server should set correct CORS headers in it's error responses.

@mhmarco
Copy link

mhmarco commented Jul 30, 2024

I had this issue when making a request to a dotnet API. Noticed that UseCors() was at the bottom, moving to the top before all other middleware fixed the issue for me.

THISSS was the fix for me thankss!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests