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: ``,
  headers: {
    Authorization: auth.getToken()

API.interceptors.response.use(null, function (error) {
  if (error.response.status === 401) {
    console.log('Failed to 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) {
  if (error.response.status === 401) {
  return Promise.reject(error)

You can do something like follow:"quote", params)
  .catch(function(error) {
    if (error.response && error.response.status === 401) {
      window.location.href = "";
    } else {
      // Handle error however you want


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

import axios from 'axios';
import {
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');
    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');

    case 401: // authentication error, logout the user
      //notify.warn('Please login again', 'Session Expired');
      console.error(error.response.status, error.message);

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

  return Promise.reject(error);
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