axios: Returning "Network Error" on unauthorized error (401)
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]
About this issue
- Original URL
- State: open
- Created 2 years ago
- Reactions: 5
- Comments: 26
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.
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.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?