When token expires, how do you use the interceptor next () to log in in axios?

for example, ajax returns code:1 as normal, code:-1 as token expiration
how to pass

what about axios.interceptors.response.use (function (response) {next ()} to login.vue?

=

import Vue from "vue";
import iView from" iview";
import Util from". / libs/util";
import VueRouter from "vue-router";
import {routers} from". / router";
import config from".. / build/config";
import axios from "axios";

Vue.use (VueRouter);

/ / routing configuration
const RouterConfig = {

routes: routers

};

export const router = new VueRouter (RouterConfig);

router.beforeEach ((to, from, next) = > {

let apiAuth = sessionStorage.getItem("apiAuth");
iView.LoadingBar.start();
Util.title(to.meta.title);
console.log(to)

// if (sessionStorage.getItem("locking") === "1" && to.name !== "locking") { // 
//     next({
//         replace: true,
//         name: "locking"
//     });
// } else if (sessionStorage.getItem("locking") === "0" && to.name === "locking") {
//     next(false);
// } else {
    if (!apiAuth && to.name !== "login") { // 
        next({
            name: "login"
        });
    } else if (apiAuth && to.name === "login") { // 
        Util.title();
        next({
            name: "home_index"
        });
    } else {
        axios.defaults.baseURL = config.baseUrl;
        axios.interceptors.request.use(function (config) {
            console.log("token")
            config.headers["version"] = "v1.0"
            if(sessionStorage.getItem("apiAuth")){
                config.headers["user-token"] = sessionStorage.getItem("apiAuth")
            }
            if(sessionStorage.getItem("access-token")){
                config.headers["access-token"] = sessionStorage.getItem("access-token")                   
            }
            
            return config;
        });
        axios.interceptors.response.use(function (response) {
            console.log("%c------response-------","color: green;")
            console.log(response.data.code)
            if(response.data.code == 1){   // token
               router.push({ name: "login"})
                
            }
            console.log("%c------response-------","color: green;")
            return response;
          }, function (error) {
            console.error(error)
          });
        Util.toDefaultPage([...routers], to.name, router, next);
    }
// }

});

router.afterEach ((to) = > {

Util.openNewPage(router.app, to.name, to.params, to.query);
iView.LoadingBar.finish();
window.scrollTo(0, 0);

});

Mar.24,2021

import your routing file, router.push ()


you want to jump to the login page , right? in the axios configuration file, import vue-router, uses router.push (..), or directly window.location.href jump;

in addition, next is a method of router hook and cannot be used externally;

Menu