| | |
| | | import axios from 'axios' |
| | | import $qxueyou from '@/config/qxueyou.js' |
| | | import { getUUID } from "@/utils/tool.js"; |
| | | import { ElMessage } from 'element-plus'; |
| | | import router from '@/router/index.js' |
| | | |
| | | let createAxios = axios.create({ |
| | | baseURL: $qxueyou.serverRoot, |
| | |
| | | throw error; |
| | | } |
| | | } |
| | | |
| | | let strTrim = function(data) { |
| | | let newData = {...data} |
| | | Object.keys(newData).forEach((key) => { |
| | | if (typeof newData[key] === 'string') { |
| | | newData[key] = newData[key].trim() |
| | | } |
| | | }) |
| | | return newData |
| | | } |
| | | |
| | | //网络请求监听 |
| | | createAxios.interceptors.request.use( |
| | | function(config) { |
| | |
| | | if (!config.url.includes('/auth/refresh-token')) { |
| | | config.headers = { |
| | | ...config.headers, |
| | | Authorization: localStorage.getItem('accessToken') |
| | | Authorization: localStorage.getItem(ACCESS_TOKEN_KEY) |
| | | } |
| | | } |
| | | config.flag = getUUID().toString().slice(-4) |
| | | if (config.data) { |
| | | console.log(`data-${config.flag} `, config.data) |
| | | // config.data = JSON.stringify(config.data) |
| | | } |
| | | if (config.params) { |
| | | console.log(`params-${config.flag} `, config.params) |
| | | // config.params = strTrim(config.params) |
| | | } |
| | | return config |
| | | }, |
| | |
| | | const resultCode = response.data.code; |
| | | const originalRequest = response.config; |
| | | if (response.data && [500, 400].includes(resultCode)) { |
| | | console.log(response) |
| | | console.log(`url-${response.config.flag}`, response.config.url, response) |
| | | return response |
| | | } |
| | | if (response.data && resultCode == '401') { |
| | |
| | | }); |
| | | refreshQueue = []; |
| | | tokenUtils.clearTokens(); |
| | | // $store.commit("session/loginFlag", false); |
| | | // $store.commit("session/userInfo", {}); |
| | | // 可以在这里触发登录页面跳转 |
| | | } finally { |
| | | isRefreshing = false; |
| | | } |
| | | } else { |
| | | tokenUtils.clearTokens(); |
| | | // $store.commit("session/loginFlag", false); |
| | | // $store.commit("session/userInfo", {}); |
| | | } |
| | | } |
| | | |
| | |
| | | return response |
| | | }, |
| | | error => { |
| | | // store.commit('network/changeNetworkState', false) |
| | | if (!error.response) return Promise.reject(error) |
| | | |
| | | // store.commit('network/status', error.response.status) |
| | | if (401 === error.response.status) { |
| | | // 刷新 token 的请求返回 401 时,直接返回错误,不要抛出新的错误 |
| | | if (error.config && error.config.url && error.config.url.includes('/auth/refresh-token')) { |
| | | return Promise.reject(error) |
| | | } |
| | | // store.commit('session/clearUser') |
| | | // store.commit('endea/clearShareK') |
| | | // store.commit('network/logout') |
| | | throw new Error('登录失效') |
| | | } |
| | | ElMessage.error(error) |
| | | return Promise.reject(error) |
| | | } |
| | | ) |