全局拦截器 和 全局接口管理
作者:chrispy
// 全局的 axios 默认值
axios.defaults.withCredentials = true
axios.defaults.timeout = 10000
// 请求拦截器
axios.interceptors.request.use((config) => {
responseStep = responseStep + 1
if (!config.LOAD_ING) {
loadingInstance = Loading.service(options)
}
return config
}, (error) => {
responseStep = 0
loadingInstance.close()
return Promise.reject(error)
})
// 响应拦截器
axios.interceptors.response.use((res) => {
// 响应成功 - 错误处理
if (res.data.status === 400) {
if (res.data.message.code === 3061) {
const messageObject = JSON.parse(res.data.message.describeCn)
let message = ''
for (let key in messageObject) {
message += '<p style="margin: 5px 0;">' + messageObject[key] + '</p>'
}
Message({
message: message,
dangerouslyUseHTMLString: true,
type: 'error'
})
} else {
Message({
message: res.data.message.describeCn ? res.data.message.describeCn : res.data.message,
type: 'error'
})
}
responseStep = 0
loadingInstance.close()
} else if (res.data.status === 401) {
router.push('/')
window.location.reload()
Message({
message: '登录失效,请重新登录!',
type: 'info'
})
} else if (res.data.status === 500) {
responseStep = 0
loadingInstance.close()
MessageBox.alert('请点击重试', '服务器繁忙', {
confirmButtonText: '重试',
callback: action => {
if (action === 'confirm') {
window.location.reload()
}
}
})
} else {
// 响应成功 - 返回成功
responseStep = responseStep - 1
if (!responseStep) {
responseStep = 0
loadingInstance.close()
}
return res
}
return Promise.reject(res)
}, (error) => {
// 响应失败 - 错误处理
if (error && error.response) {
switch (error.response.status) {
case 408:
error.message = '网络超时'
break
case 504:
error.message = '网络超时'
break
default:
error.message = '网络异常'
}
} else {
error.message = '网络异常'
}
responseStep = 0
loadingInstance.close()
MessageBox.alert('请点击重试', error.message, {
confirmButtonText: '重试',
callback: action => {
if (action === 'confirm') {
window.location.reload()
}
}
})
return Promise.reject(error.message)
})