vue下axios攔截器token刷新機制


//建立http.js文件,如下是具體代碼:



//
引入安裝的axios插件 import axios from 'axios' import router from '@/router'; import Vue from 'vue' const qs = require("qs"); let _this = new Vue(); let isLock = false; let refreshSubscribers = []; //判斷token是否過時 function isTokenExpired(token) { let expires_time = JSON.parse(token).expires_time; let curentTime = new Date().getTime(); if (curentTime >= expires_time) { return true; } else { return false; } } //獲取Token對象 function getToken() { return localStorage.getItem("token"); } //push全部請求到數組中 function subscribeTokenRefresh(cb) { refreshSubscribers.push(cb) } //刷新請求(refreshSubscribers數組中的請求獲得新的token以後會自執行,用新的token去請求數據) function onRrefreshed(token) { refreshSubscribers.map(cb => cb(token)) } //刷新token function refreshToken(config, token, resolve, reject) { let data = { refresh_token: JSON.parse(token).refresh_token }; axios({ method: "post", url: "xxxxxx/refreshToken",//刷新token的接口 headers: { "Content-Type": "application/x-www-form-urlencoded", "Authorization": "Basic b3JkZXItc2VydmVyOjEyMzQ1Ng==" }, data: qs.stringify(data) }).then(res => { isLock = false;//釋放鎖 if (res.data.code === 101) { _this.$message.error('登陸狀態已失效,請從新登陸。'); localStorage.removeItem("token"); router.push({ path: "/login" }); return; } let expires_time = new Date().getTime() + parseInt(res.data.data.expires_in * 0.8) * 1000; let token = JSON.parse(localStorage.getItem("token")); token.expires_time = expires_time; token.access_token = res.data.data.access_token; localStorage.setItem("token", JSON.stringify(token)); config.headers.Authorization = 'Bearer ' + res.data.data.access_token; resolve(config); //執行數組裏的函數,從新發起被掛起的請求 onRrefreshed(res.data.data.access_token) //清空數組中保存的請求 refreshSubscribers = [] }).catch(err => { return err; }); } function request(newOptions, resolve, reject) { axios({ method: newOptions.method, url: newOptions.url, data: newOptions.type == "form" ? qs.stringify(newOptions.data) : newOptions.data, headers: newOptions.headers }).then(res => { if (res.status == 200) { //這裏咱們只須要獲取返回的data中的數據便可 resolve(res.data); } else { reject(res.data); } }).catch(err => { reject(err); _this.$message.error('服務異常!'); }) } axios.interceptors.request.use( config => { let token = getToken(); if (token) { //判斷token是否過時,若是過時請求刷新token if (isTokenExpired(token)) { //判斷當前是否正在請求刷新token if (!isLock) { isLock = true;//isLock設置true,鎖住防止死循環。 //使用Promise等待刷新完成返回配置信息 let refresh = new Promise((resolve, reject) => { refreshToken(config, token, resolve, reject); }) return refresh; } else { //判斷當前url是不是刷新token的請求地址,若是是直接下一步。 if (config.url.indexOf('/logined/refreshToken') === -1) { //把請求(token)=>{....}都push到一個數組中 let retry = new Promise((resolve, reject) => { //(token) => {...}這個函數就是回調函數 subscribeTokenRefresh((token) => { config.headers.Authorization = 'Bearer ' + token //將請求掛起 resolve(config) }) }) return retry } else { return config; } } } else { return config; } } else { return config; } }, error => { return Promise.reject(error); }); const http = options => { return new Promise((resolve, reject) => { const defaultOptions = { type: "json" }; const newOptions = { ...defaultOptions, ...options }; //headers默認傳遞json格式數據,這裏也能夠設置token,每次調用都會攜帶
if (localStorage.getItem("token")) { newOptions.headers = { // 'Authorization': 'Basic b3JkZXItc2VydmVyOjEyMzQ1Ng==', 'content-Type': newOptions.type == 'form' ? 'application/x-www-form-urlencoded;charset=UTF-8' : 'application/json;charset=UTF-8', 'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem("token")).access_token, ...newOptions.headers }; } else { newOptions.headers = { 'content-Type': newOptions.type == 'form' ? 'application/x-www-form-urlencoded;charset=UTF-8' : 'application/json;charset=UTF-8', ...newOptions.headers }; } request(newOptions, resolve, reject); }) }; //設置請求超時 axios.defaults.timeout = 30000 export default http
//在main.js下面掛載 http.js文件
import http from '@/utils/http.js';
Vue.prototype.http = http;
//登陸保存token信息接口

this.http({
            method: "post",
            url: "/xxxxx/user",
            type: "form",
            headers: { Authorization:"Basicb3JkZXItc2VydmVyOjEyMzQ1Ng==" },
            data: {}
          }).then(function(res) {
               let expires_time =
                  new Date().getTime() +
                  parseInt(res.data.token.expires_in * 0.8) * 1000;
                  let token = res.data.token;
                  token.expires_time = expires_time;
                localStorage.setItem("token", JSON.stringify(token));
        
            }).catch(function(err) {
              console.log(err);
            });                
//退出清空token
this.http({
        method: "get",
        url: "/xxxxx/logout",
        data: {}
      }).then(function(res) {
 localStorage.removeItem("token");
    }).catch(function(err) {
          console.log(err);
        });

這是本人作自動刷新token遇到的問題,如今分享給你們,若是對你有幫助記得留言,謝謝!!vue

相關文章
相關標籤/搜索