Commit b06035a8 authored by xhx's avatar xhx

fix:全局请求等待

parent 29a9151e
......@@ -6,6 +6,32 @@ import router from '@/router'
let loading: ElLoadingComponent
function startLoading() {
loading = Loading.service({
target: '.content-r'
})
}
function endLoading() {
loading.close()
}
let requestCount = 0
export function showFullScreenLoading() {
if (requestCount === 0) {
startLoading()
}
requestCount++
}
export function tryHideFullScreenLoading() {
if (requestCount <= 0) return
requestCount--
if (requestCount === 0) {
endLoading()
}
}
const service = axios.create({
baseURL: '/api',
......@@ -13,33 +39,30 @@ const service = axios.create({
})
service.interceptors.request.use(function (config) {
// do something before request is sent
if (getStorage('authToken') && config.url?.indexOf('/login') === -1) {
const str = getStorage('authToken')
config.headers['Auth-Token'] = str
}
// showFullScreenLoading()
showFullScreenLoading()
return config;
}, function (error) {
// tryHideFullScreenLoading()
return Promise.reject(error);
});
// Add a response interceptor
service.interceptors.response.use(
response => {
tryHideFullScreenLoading()
const authToken = response.headers['auth-token']
if (authToken) {
saveStorage('authToken', authToken)
}
const res = response.data
// if the custom code is not 200, it is judged as an error.
// tryHideFullScreenLoading()
return res
}, error => {
// Do something with response error
console.log(error.response)
const REASON = error.response.data?.reason
tryHideFullScreenLoading()
const REASON = error?.response?.data?.reason
if (REASON === 'TOKEN') {
router.push('/login')
Message({
......@@ -49,12 +72,11 @@ service.interceptors.response.use(
})
} else {
Message({
message: error.response.data.reason || '网络异常',
message: error?.response?.data?.reason || '网络异常',
type: 'error',
duration: 3 * 1000
})
}
// tryHideFullScreenLoading()
return Promise.reject(error);
})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment