Skip to content

Commit

Permalink
feat: 重构axios工具类
Browse files Browse the repository at this point in the history
  • Loading branch information
cadecode committed Apr 15, 2023
1 parent 31ec9ad commit eaac5a2
Showing 1 changed file with 56 additions and 17 deletions.
73 changes: 56 additions & 17 deletions src/utils/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ const service = axios.create({
timeout: 60 * 1000
})

// 请求拦截器
/**
* 请求拦截器
*/
service.interceptors.request.use(
config => {
if (store.getters.token) {
Expand All @@ -29,30 +31,67 @@ service.interceptors.request.use(
}
)

// 响应拦截器
/**
* 响应拦截器
* uni-boot-admin 响应格式 {status, data, error:{code, message, path, moreInfo}}
*/
service.interceptors.response.use(
response => {
const res = response.data
if (res.status !== 200) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
checkResError(response)
checkResToken(response)
return res
},
(error) => {
console.error(error)
const response = error.response
if (response && response.data) {
checkResError(response)
}
Message({ message: error.message, type: 'error', duration: 5 * 1000 })
throw error
}
)

/**
* 从响应中检查后端error信息
*/
function checkResError(response) {
const res = response.data
let errorMessage
// 判断有没有返回error
if (res && res.error) {
// 未登录跳转到登录页
if (res.status === 401) {
errorMessage = res.error.message + ', 是否重新登录'
MessageBox.confirm(errorMessage, '登录状态失效', {
confirmButtonText: '返回登录页',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => location.reload())
})
return Promise.reject(new Error(JSON.stringify(res.error, null, 2) || 'Error'))
} else {
return res
return
}
},
error => {
console.log('err' + error)
errorMessage = '错误: ' + JSON.stringify(res.error)
// 此处res.error可兼容SpringBoot原生接口异常
Message({
message: error.message,
message: errorMessage || '未知错误',
type: 'error',
duration: 5 * 1000
duration: 5 * 1000,
dangerouslyUseHTMLString: true
})
return Promise.reject(error)
throw new Error(errorMessage || '未知错误')
}
)
}

/**
* 从响应中检查后端token信息,每次写入新token
*/
function checkResToken(response) {
if (response.headers && response.headers[tokenKey]) {
store.dispatch('user/setToken', response.headers[tokenKey])
}
}

export default service

0 comments on commit eaac5a2

Please sign in to comment.