1
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
import axios from 'axios'
|
||||
import { getToken, clearAuth } from '@/utils/auth'
|
||||
import { toast } from '@/utils/feedback'
|
||||
|
||||
const BASE_URL = '/api'
|
||||
|
||||
@@ -21,21 +20,21 @@ instance.interceptors.request.use(
|
||||
(err) => Promise.reject(err)
|
||||
)
|
||||
|
||||
function handleUnauthorized() {
|
||||
function handleUnauthorized(url) {
|
||||
console.warn('[auth] 登录已过期,自动退出登录', url || '')
|
||||
clearAuth()
|
||||
toast('登录已过期,请重新登录', 'error')
|
||||
setTimeout(() => {
|
||||
if (location.hash !== '#/login') {
|
||||
location.hash = '#/login'
|
||||
}
|
||||
}, 400)
|
||||
}, 200)
|
||||
}
|
||||
|
||||
instance.interceptors.response.use(
|
||||
(response) => response,
|
||||
(err) => {
|
||||
if (err && err.response && err.response.status === 401) {
|
||||
handleUnauthorized()
|
||||
handleUnauthorized(err.config && err.config.url)
|
||||
}
|
||||
return Promise.reject(err)
|
||||
}
|
||||
@@ -43,14 +42,7 @@ instance.interceptors.response.use(
|
||||
|
||||
export function request({ url, method = 'GET', data, params, headers, responseType } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
instance({
|
||||
url,
|
||||
method,
|
||||
data,
|
||||
params,
|
||||
headers,
|
||||
responseType
|
||||
})
|
||||
instance({ url, method, data, params, headers, responseType })
|
||||
.then((res) => {
|
||||
if (responseType === 'blob' || responseType === 'arraybuffer') {
|
||||
resolve(res)
|
||||
@@ -64,18 +56,16 @@ export function request({ url, method = 'GET', data, params, headers, responseTy
|
||||
}
|
||||
|
||||
const message = body.message || '请求失败'
|
||||
toast(message, 'error')
|
||||
console.error('[request]', method, url, '业务失败:', message, body)
|
||||
reject(new Error(message))
|
||||
})
|
||||
.catch((err) => {
|
||||
if (err && err.response && err.response.status === 401) {
|
||||
reject(err)
|
||||
reject(new Error('Unauthorized'))
|
||||
return
|
||||
}
|
||||
const msg = (err && err.message) || '网络异常'
|
||||
if (!/Unauthorized/.test(msg)) {
|
||||
toast(msg, 'error')
|
||||
}
|
||||
console.error('[request]', method, url, '请求异常:', msg, err)
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
@@ -98,12 +88,16 @@ export function uploadFile(file) {
|
||||
return
|
||||
}
|
||||
const message = body.message || '上传失败'
|
||||
toast(message, 'error')
|
||||
console.error('[upload] 业务失败:', message, body)
|
||||
reject(new Error(message))
|
||||
})
|
||||
.catch((err) => {
|
||||
if (err && err.response && err.response.status === 401) {
|
||||
reject(new Error('Unauthorized'))
|
||||
return
|
||||
}
|
||||
const msg = (err && err.message) || '上传失败'
|
||||
toast(msg, 'error')
|
||||
console.error('[upload] 请求异常:', msg, err)
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user