import axios from 'axios'
import type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { useLoadingStore } from '@/stores/loading'
// 创建 axios 实例
const service: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_URL || '/api', // 从环境变量获取 baseURL
timeout: 15000, // 请求超时时间
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})
// 请求拦截器
service.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
// 显示loading
const loadingStore = useLoadingStore()
loadingStore.show()
// 在这里可以添加token等认证信息
const token = localStorage.getItem('token')
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error: any) => {
const loadingStore = useLoadingStore()
loadingStore.hide()
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
(response: AxiosResponse) => {
// 隐藏loading
const loadingStore = useLoadingStore()
loadingStore.hide()
const res = response.data
// 如果有 code 字段
if (typeof res.code !== 'undefined') {
if (res.code === 200) {
return res.data
} else {
handleError(res)
return Promise.reject(new Error(res.message || 'Error'))
}
}
// 没有 code 字段,直接返回原始数据
return res
},
(error: any) => {
const loadingStore = useLoadingStore()
loadingStore.hide()
// 处理错误情况
handleError(error)
return Promise.reject(error)
}
)
// 错误处理函数
function handleError(error: any) {
// 这里可以使用你的提示组件或其他方式展示错误信息
console.error('请求错误:', error)
// 处理特定错误码
switch (error.code) {
case 401:
// 未授权,跳转到登录页
// router.push('/login')
break
case 403:
// 权限不足
break
case 404:
// 资源不存在
break
case 500:
// 服务器错误
break
default:
// 其他错误
break
}
}
// 封装请求方法
export const http = {
get<T = any>(url: string, params?: object): Promise<T> {
return service.get(url, { params })
},
post<T = any>(url: string, data?: object): Promise<T> {
return service.post(url, data)
},
put<T = any>(url: string, data?: object): Promise<T> {
return service.put(url, data)
},
delete<T = any>(url: string, params?: object): Promise<T> {
return service.delete(url, { params })
},
// 上传文件
upload<T = any>(url: string, file: File): Promise<T> {
const formData = new FormData()
formData.append('file', file)
return service.post(url, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
},
// 下载文件
download(url: string, params?: object) {
return service.get(url, {
params,
responseType: 'blob'
})
}
}
export default service