鍍金池/ 問答/C  HTML/ 當token過期,如何在axios里面用攔截器next()到登陸呢?

當token過期,如何在axios里面用攔截器next()到登陸呢?

例如 ajax返回 code:1 為正常 ,code :-1 為token過期
如何通過

axios.interceptors.response.use(function (response) { next() } 到 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);

// 路由配置
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') { // 判斷當前是否是鎖定狀態(tài)
//     next({
//         replace: true,
//         name: 'locking'
//     });
// } else if (sessionStorage.getItem('locking') === '0' && to.name === 'locking') {
//     next(false);
// } else {
    if (!apiAuth && to.name !== 'login') { // 判斷是否已經(jīng)登錄且前往的頁面不是登錄頁
        next({
            name: 'login'
        });
    } else if (apiAuth && to.name === 'login') { // 判斷是否已經(jīng)登錄且前往的是登錄頁
        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);

});

回答
編輯回答
枕邊人

import你的路由文件, router.push()

2017年10月30日 07:48
編輯回答
她愚我

你要的是跳轉(zhuǎn)到登錄頁面對吧,在 axios 配置的文件中 import vue-router,在其中 使用 router.push(..),或者直接 window.location.href 跳轉(zhuǎn);

另外,next 是 router hook 的方法,外部無法使用;

2018年5月23日 22:38