2
votes

The api give 401 Unauthorized error because of expired token.

Even though, error status code(401) is not available in axios interceptor.

Vue.axios.interceptors.response.use(function(response) {    
  return response;
}, function(error) {

    // I want to catch the 401 error here but, error.response is undefined
    return Promise.reject(error);
});

Is there any way i can get it, the below github issue says error.response.status can be used, but error.response is undefined for me.

Http Error: Failed to load http://localhost:5000/api/user: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:2323' is therefore not allowed access. The response had HTTP status code 401.

Console.log(error) from intercepter response.use Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87)

1
can you log the error first?samayo
@samayo Error logs updated.Vaisakh Rajagopal
you are making requests between two different ports. this is a CORS issue. You need allow your backend to accept or add Access-Control-Allow-Origin optionsamayo
A pre-flight request is fired before the actual request I am guessing that is why you are never able to intercept the error response.Stephan-v
@VaisakhRajagopal did you find a way. I need to intercept also 401 so I can redirect to login screen.VAAA

1 Answers

0
votes

This is my Axios error handler code. It runs. If you want, you can delete the toast codes.

    import axios from 'axios'
    import toast from './toast'
    import store from '../../store'
    
    // apply interceptor on response
    axios.interceptors.response.use(function (response) {
      if (response.status === 200 && response.data.message) {
        toast.success(response.data.message)
      }
      if (response.status === 201 && response.data.message) {
        toast.success(response.data.message)
      }
      return response
    }, function (error) {
      // Do something with response error
      // check for errorHandle config
    
      // if has response show the error
      if (error.response) {
        if (error.response.status === 404 || error.response.status === 400) {
          toast.error(error.response.data.message)
        }
        if (error.response.status === 401) {
          // if you ever get an unauthorized, logout the user
          store.dispatch('logout')
        // you can also redirect to /login if needed !
        }
      }
      return Promise.reject(error)
    })