92 lines
2.2 KiB
TypeScript
92 lines
2.2 KiB
TypeScript
|
|
import axios from 'axios'
|
|||
|
|
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
|
|||
|
|
import { ElMessage } from 'element-plus'
|
|||
|
|
import router from '@/router'
|
|||
|
|
import { useAuthStore } from '@/stores/auth'
|
|||
|
|
|
|||
|
|
// 创建 axios 实例
|
|||
|
|
const request: AxiosInstance = axios.create({
|
|||
|
|
baseURL: import.meta.env.VITE_API_URL, // 从环境变量读取
|
|||
|
|
timeout: 10000, // 10秒超时
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
// Token 管理器(使用 Pinia)
|
|||
|
|
const TokenManager = {
|
|||
|
|
setToken(token: string) {
|
|||
|
|
const authStore = useAuthStore()
|
|||
|
|
authStore.setToken(token)
|
|||
|
|
// 同时设置默认请求头
|
|||
|
|
request.defaults.headers.common['Authorization'] = `Bearer ${token}`
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
getToken(): string {
|
|||
|
|
const authStore = useAuthStore()
|
|||
|
|
return authStore.getToken()
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
removeToken() {
|
|||
|
|
const authStore = useAuthStore()
|
|||
|
|
authStore.removeToken()
|
|||
|
|
// 删除默认请求头
|
|||
|
|
delete request.defaults.headers.common['Authorization']
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 请求拦截器
|
|||
|
|
request.interceptors.request.use(
|
|||
|
|
(config: InternalAxiosRequestConfig) => {
|
|||
|
|
const token = TokenManager.getToken()
|
|||
|
|
if (token) {
|
|||
|
|
// .NET Core API使用标准的Bearer认证
|
|||
|
|
config.headers['Authorization'] = `Bearer ${token}`
|
|||
|
|
}
|
|||
|
|
return config
|
|||
|
|
},
|
|||
|
|
(error) => {
|
|||
|
|
return Promise.reject(error)
|
|||
|
|
}
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// 响应拦截器
|
|||
|
|
request.interceptors.response.use(
|
|||
|
|
(response: AxiosResponse) => {
|
|||
|
|
const { data } = response
|
|||
|
|
|
|||
|
|
// 如果返回 code 为 0 且有新 token,更新 token
|
|||
|
|
if (data.code === 0 && data.token) {
|
|||
|
|
TokenManager.setToken(data.token)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
console.log('data*--', data)
|
|||
|
|
|
|||
|
|
// 处理业务错误码
|
|||
|
|
if (data.code === 302) {
|
|||
|
|
// 清除token
|
|||
|
|
TokenManager.removeToken()
|
|||
|
|
// 跳转到登录页
|
|||
|
|
router.replace('/login')
|
|||
|
|
return Promise.reject(data)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 其他错误码
|
|||
|
|
if (data.code !== 0 && data.code !== undefined) {
|
|||
|
|
ElMessage.error(data.message || data.msg || '请求失败')
|
|||
|
|
return Promise.reject(data)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return data
|
|||
|
|
},
|
|||
|
|
(error) => {
|
|||
|
|
// 网络错误或其他错误
|
|||
|
|
ElMessage.error(
|
|||
|
|
error.response?.data?.message ||
|
|||
|
|
error.response?.data?.msg ||
|
|||
|
|
'请求失败'
|
|||
|
|
)
|
|||
|
|
return Promise.reject(error)
|
|||
|
|
}
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
export default request
|
|||
|
|
|