vue配置請求攔截器和響應攔截器


首先確保我們已經設置的store.js進行值的存取,這時候我們需要配置請求和響應的攔截器設置

main.js

 

import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
// 引入store 
import store from './store'

// 如何localStorage的token不存在或是空跳轉到路由
router.beforeEach((to, from, next) => {
  if (to.path === '/') {
    next();
  } else {
    let token = window.localStorage.token;
    if (token === 'null' || token === '' || token === undefined) {
      next('/');
    } else {
      next();
    }
  }

})




//與后端定義狀態是100簽名錯誤 跳轉到登錄界面
axios.interceptors.response.use(
  response => {
    //當返回信息為未登錄或者登錄失效的時候重定向為登錄頁面
    if (response.data.status == 100 || response.data.message == '用戶未登錄或登錄超時,請登錄!') {
      router.push({
        path: "/",
        querry: { redirect: router.currentRoute.fullPath }//從哪個頁面跳轉
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM