-2

I need to redirect to login page if backend throws 401-Unauthorised error. But when I try to use router.push('/login) it throws router is not defined error in axios interceptor. Here is my axios.js file.

import Vue from 'vue'
import axios from "axios"
import router from '../router'

_axios.interceptors.response.use(
 function(response) {
  return response
 },
 function(error) {
  if(error.response.status == 401){
   router.push('/login')
  }
  return Promise.reject(error)
 }
)

This is router.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

const routes = [
{
 path: '/login',
 name: 'Login',
 meta: {
  layout: 'login',
  requireAuth: false,
  icon: null
 },
 component: () => import(/* webpackChunkName: "login" */ 
 '../components/common/auth/login-form'),
}]

const router = new VueRouter({
 mode: 'history',
 base: process.env.BASE_URL,
 routes
})
export default router

And defining {router} in axios gives this error in terminal npm run serve: enter image description here

If I try with import router from '../router' in axios file I got this error: enter image description here enter image description here

3
  • Did you import the router in the file that you have the interceptor in ?
    – bassxzero
    Commented Feb 8, 2023 at 9:32
  • Yes I have. updated the axios code here. Commented Feb 8, 2023 at 9:52
  • The error in your console screenshot shows that the problem is axios.post(), nothing to do with router. Seems you haven't imported axios correctly in your store file
    – Phil
    Commented Feb 9, 2023 at 5:12

1 Answer 1

0

use default export import router from '../router' instead of named import like you have in answer, `cause you have default export only in file where you define router

3
  • I tried it but that's not working as well. Giving the error in console regarding some state method in the index.js file. Updated the question and put a screenshot of the error there @Guzaro Commented Feb 9, 2023 at 5:02
  • @DarshanSoni your question still shows import { router }
    – Phil
    Commented Feb 9, 2023 at 5:07
  • @Phil I meant I have added the screenshot of the errors. But now updated the import statement as welll Commented Feb 9, 2023 at 5:10

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.