2025-08-01 17:58:00 +08:00
|
|
|
|
import axios from 'axios'
|
2025-08-02 14:59:08 +08:00
|
|
|
|
import { ElMessage } from 'element-plus'
|
2025-08-01 18:23:53 +08:00
|
|
|
|
import auth from '@/utils/auth'
|
2025-08-01 17:58:00 +08:00
|
|
|
|
|
2025-08-01 18:23:53 +08:00
|
|
|
|
// 创建axios实例
|
2025-08-01 17:58:00 +08:00
|
|
|
|
const api = axios.create({
|
2025-08-01 18:23:53 +08:00
|
|
|
|
baseURL: import.meta.env.VITE_API_BASE_URL || '/api/v1',
|
2025-08-01 17:58:00 +08:00
|
|
|
|
timeout: 10000,
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
// 请求拦截器
|
|
|
|
|
api.interceptors.request.use(
|
|
|
|
|
(config) => {
|
2025-08-01 18:23:53 +08:00
|
|
|
|
// 添加token到请求头
|
|
|
|
|
const token = auth.getToken()
|
2025-08-01 17:58:00 +08:00
|
|
|
|
if (token) {
|
|
|
|
|
config.headers.Authorization = `Bearer ${token}`
|
|
|
|
|
}
|
|
|
|
|
return config
|
|
|
|
|
},
|
|
|
|
|
(error) => {
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// 响应拦截器
|
|
|
|
|
api.interceptors.response.use(
|
|
|
|
|
(response) => {
|
2025-08-01 18:23:53 +08:00
|
|
|
|
return response
|
2025-08-01 17:58:00 +08:00
|
|
|
|
},
|
|
|
|
|
(error) => {
|
2025-08-01 18:23:53 +08:00
|
|
|
|
const { response } = error
|
|
|
|
|
|
|
|
|
|
if (response) {
|
|
|
|
|
const { status, data } = response
|
2025-08-01 17:58:00 +08:00
|
|
|
|
|
|
|
|
|
switch (status) {
|
|
|
|
|
case 401:
|
2025-08-01 18:23:53 +08:00
|
|
|
|
// 未授权,清除token并跳转到登录页
|
|
|
|
|
auth.logout()
|
2025-08-02 14:59:08 +08:00
|
|
|
|
ElMessage.error('登录已过期,请重新登录')
|
2025-08-01 17:58:00 +08:00
|
|
|
|
window.location.href = '/login'
|
|
|
|
|
break
|
|
|
|
|
case 403:
|
2025-08-02 14:59:08 +08:00
|
|
|
|
ElMessage.error('没有权限访问该资源')
|
2025-08-01 17:58:00 +08:00
|
|
|
|
break
|
|
|
|
|
case 404:
|
2025-08-02 14:59:08 +08:00
|
|
|
|
ElMessage.error('请求的资源不存在')
|
2025-08-01 17:58:00 +08:00
|
|
|
|
break
|
|
|
|
|
case 500:
|
2025-08-02 14:59:08 +08:00
|
|
|
|
ElMessage.error('服务器内部错误')
|
2025-08-01 17:58:00 +08:00
|
|
|
|
break
|
|
|
|
|
default:
|
2025-08-02 14:59:08 +08:00
|
|
|
|
ElMessage.error(data?.message || '请求失败')
|
2025-08-01 17:58:00 +08:00
|
|
|
|
}
|
|
|
|
|
} else {
|
2025-08-02 14:59:08 +08:00
|
|
|
|
ElMessage.error('网络连接失败,请检查网络设置')
|
2025-08-01 17:58:00 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
2025-08-01 18:53:45 +08:00
|
|
|
|
export default api
|