[Vuejs]-Vue Axios โ€“ token is undefined

0๐Ÿ‘

โœ…

I suspect that this tutorial may have a mistake โ€“ if you set your headers in axios.create then the Authorization header will get the current value of the sessionStorage, which at this time is undefined.

Actually, you want to set your headers in axios.interceptors.request.use โ€“ so that the header will be populated with the value of the sessionStorage at the moment of performing the AJAX request. Something like this

Vue.prototype.$axios = axios.create(
  {
    headers:
      {
        'Content-Type': 'application/json'
      },
    baseURL: process.env.API_URL
  }
);

Vue.prototype.$axios.interceptors.request.use(
  config =>
  {
    if (store.getters.isUserLoggedin) config.headers['Authorization'] = 'Bearer ' + store.getters.user.token;
    return config;
  }
);

Vue.prototype.$axios.interceptors.response.use(
  response => response,
  error =>
  {
    if (error && error.response && error.response.status && error.response.status === 403)
    {
      store.dispatch('unsetUser');
      router.push('/login');
      return Promise.resolve(); // Avoid showing any errors
    }
    else
    {
      logger.error({
        message: 'Error in HTTP request',
        response: JSON.stringify(extractError(error)),
        status: _get(error, 'response.status', 'unknown'),
        url: _get(error, 'config.url', 'unknown'),
        userId: store.getters.userInfo.id
      });
      throw error;
    }
  }
);

Leave a comment