73 lines
1.8 KiB
TypeScript
73 lines
1.8 KiB
TypeScript
|
|
import axios from 'axios'
|
||
|
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||
|
|
import { useTenantStore } from '@/stores/tenant'
|
||
|
|
|
||
|
|
// 创建 axios 实例
|
||
|
|
const service = axios.create({
|
||
|
|
baseURL: import.meta.env.VITE_APP_BASE_API || '/api',
|
||
|
|
timeout: 10000
|
||
|
|
})
|
||
|
|
|
||
|
|
// 请求拦截器
|
||
|
|
service.interceptors.request.use(
|
||
|
|
(config) => {
|
||
|
|
const tenantStore = useTenantStore()
|
||
|
|
if (tenantStore.currentTenantId) {
|
||
|
|
config.headers['X-Tenant-Id'] = tenantStore.currentTenantId
|
||
|
|
}
|
||
|
|
// TODO: 如果有 token 也可以在这里注入 Authorization
|
||
|
|
return config
|
||
|
|
},
|
||
|
|
(error) => {
|
||
|
|
console.log(error)
|
||
|
|
return Promise.reject(error)
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
// 响应拦截器
|
||
|
|
service.interceptors.response.use(
|
||
|
|
(response) => {
|
||
|
|
const res = response.data
|
||
|
|
// 这里可以根据后端的 code 进行统一处理
|
||
|
|
return res
|
||
|
|
},
|
||
|
|
(error) => {
|
||
|
|
console.log('err' + error)
|
||
|
|
let { message, response } = error
|
||
|
|
if (response) {
|
||
|
|
const status = response.status
|
||
|
|
if (status === 401) {
|
||
|
|
ElMessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
|
||
|
|
confirmButtonText: '重新登录',
|
||
|
|
cancelButtonText: '取消',
|
||
|
|
type: 'warning'
|
||
|
|
}).then(() => {
|
||
|
|
// TODO: 跳转到登录页或执行退出逻辑
|
||
|
|
location.href = '/login'
|
||
|
|
})
|
||
|
|
} else if (status === 403) {
|
||
|
|
ElMessage({
|
||
|
|
message: '当前操作无权限',
|
||
|
|
type: 'error',
|
||
|
|
duration: 5 * 1000
|
||
|
|
})
|
||
|
|
} else {
|
||
|
|
ElMessage({
|
||
|
|
message: message || '后端接口未知异常',
|
||
|
|
type: 'error',
|
||
|
|
duration: 5 * 1000
|
||
|
|
})
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
ElMessage({
|
||
|
|
message: '网络连接异常',
|
||
|
|
type: 'error',
|
||
|
|
duration: 5 * 1000
|
||
|
|
})
|
||
|
|
}
|
||
|
|
return Promise.reject(error)
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
export default service
|