Vue.js and Axios – redirect on 401

I’m running Vue.js and axios and are trying to make a generic API object like the following:

import router from './router'
import auth from './auth'
const axios = require('axios')

export const API = axios.create({
  baseURL: `https://my-api.com/`,
  headers: {
    Authorization: auth.getToken()
  }
})

API.interceptors.response.use(null, function (error) {
  if (error.response.status === 401) {
    console.log('Failed to login')
    router.push('/Login')
  }
  return Promise.reject(error)
})

I’m trying to have the users redirected to the Login screen in my single page app, whenever a 401 error code is received.
But I’m not getting redirected, and no error occurs in my Developer Tools in Chrome. I do get the console.log with Failed to login.

I have detected a similar situation. I haved fixed with this code:

import router from 'router'
import store from 'store'
...
...
axios.interceptors.response.use(function (response) {
  return response
}, function (error) {
  console.log(error.response.data)
  if (error.response.status === 401) {
    store.dispatch('logout')
    router.push('/login')
  }
  return Promise.reject(error)
})

You can do something like follow:

axios.post("quote", params)
  .catch(function(error) {
    if (error.response && error.response.status === 401) {
      window.location.href = "https://stackoverflow.com/questions/52096412/logon";
    } else {
      // Handle error however you want
    }
  });

Source: https://github.com/axios/axios/issues/396#issuecomment-395592900

you Can use below code and add httpClient.js file to your project:

import axios from 'axios';
import {
  authHeader
}
from '../helper'

const baseUrl="http://localhost:8811/api/";//local-test
const Api_Path = `${baseUrl}/`;

const httpClient = axios.create({
  baseURL: Api_Path,
  headers: {
    //Authorization: 'Bearer {token}',
    //timeout: 1000, // indicates, 1000ms ie. 1 second
    "Content-Type": "application/json",

  }
})
const authInterceptor = (config) => {
  config.headers['Authorization'] = authHeader();
  return config;
}
const errorInterceptor = error => {


// check if it's a server error
  if (!error.response) {
    //notify.warn('Network/Server error');
    console.error('**Network/Server error');
    console.log(error.response);
    return Promise.reject(error);
  }

  // all the other error responses
  switch (error.response.status) {
    case 400:
      console.error(error.response.status, error.message);
      //notify.warn('Nothing to display', 'Data Not Found');
      break;

    case 401: // authentication error, logout the user
      //notify.warn('Please login again', 'Session Expired');
      console.error(error.response.status, error.message);
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      //router.push('/auth');
      break;

default:
  console.error(error.response.status, error.message);
  //notify.error('Server Error');



 }
  return Promise.reject(error);
}
httpClient.interceptors.request.use(authInterceptor);
httpClient.interceptors.response.use(responseInterceptor, errorInterceptor);

export default httpClient;


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Force browser to refresh CSS, JavaScript, etc

Similar Posts