Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 335
Alfred Balle Avatar asked Aug 30 '18 11:08

Alfred Balle


1 Answers

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)
})
like image 180
Rubén Pozo Avatar answered Sep 28 '22 22:09

Rubén Pozo