How to use Vue Router inside Axios Interceptor
-
I’m trying to use Vue router to redirect back to the login page when a request has a status of 401, but it’s not working.
My boot/axios.js:
import Vue from "vue"; import axios from "axios"; import router from '../router/index'; // .... axios.interceptors.response.use( response => { return response; }, function(error) { if (error.response?.status === 401) { // store.dispatch("auth/logout"); router.push('/login'); } return Promise.reject(error); } ); // ...
I get the following error:
TypeError: _router_index__WEBPACK_IMPORTED_MODULE_4__.default.push is not a function
-
Hey
The way you import the router, it is not yet initialized.
Use the Quasarboot
function to access app context (including router).import { boot } from 'quasar/wrappers' export default boot(async ctx => { // here configure your axios instance await ctx.router.push('/path') Vue.prototype.$axios = axios })
-
@andreoakley you have access to router by passing it as a parameter of your boot file’s default export axios interceptor (assuming you made it there) https://quasar.dev/quasar-cli/boot-files#Anatomy-of-a-boot-file, if not then you can do parameter passing to where your axios interceptor resides or if you are not using ssr then you can just make an export of your router instance from
src/router/index.js
, and then import it to wherever your axios interceptor is.
example:// src/router/index.js let router = null export default function (/* { store, ssrContext } */) { router = new VueRouter({ ... }) return router } export { router } // axios interceptor file import { router } from 'src/router' axios.interceptors.response.use( response => { return response; }, function(error) { if (error.response?.status === 401) { // store.dispatch("auth/logout"); router.push('/login'); } return Promise.reject(error); } )
-
Not sure if the solution is ideal, but what I ended up doing was just setting a new variable and exporting like so:
let router = null; export default function({ store }) { const Router = new VueRouter({ scrollBehavior: () => ({ x: 0, y: 0 }), routes, mode: process.env.VUE_ROUTER_MODE, base: process.env.VUE_ROUTER_BASE }); // ...... router = Router; return Router; } export { router };