117 lines
2.8 KiB
JavaScript
117 lines
2.8 KiB
JavaScript
import axios from 'axios'
|
|
import { message } from 'ant-design-vue'
|
|
import { ENV_CONFIG, debugLog } from '@/config/env'
|
|
import { AuthUtils } from '@/utils/auth'
|
|
|
|
// 创建axios实例
|
|
const request = axios.create({
|
|
baseURL: ENV_CONFIG.API_BASE_URL,
|
|
timeout: ENV_CONFIG.API_TIMEOUT,
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
}
|
|
})
|
|
|
|
// 打印环境信息
|
|
if (ENV_CONFIG.DEBUG_MODE) {
|
|
console.log('=== API配置信息 ===')
|
|
console.log('Base URL:', ENV_CONFIG.API_BASE_URL)
|
|
console.log('Timeout:', ENV_CONFIG.API_TIMEOUT)
|
|
console.log('Environment:', ENV_CONFIG.APP_ENV)
|
|
console.log('================')
|
|
}
|
|
|
|
// 请求拦截器
|
|
request.interceptors.request.use(
|
|
async (config) => {
|
|
// 自动刷新token(如果需要)
|
|
const token = await AuthUtils.autoRefreshToken()
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`
|
|
}
|
|
|
|
// 使用环境配置的调试日志
|
|
debugLog('发送请求:', config.method?.toUpperCase(), config.url, config.data || config.params)
|
|
return config
|
|
},
|
|
(error) => {
|
|
debugLog('请求错误:', error)
|
|
return Promise.reject(error)
|
|
}
|
|
)
|
|
|
|
// 响应拦截器
|
|
request.interceptors.response.use(
|
|
(response) => {
|
|
const { data } = response
|
|
debugLog('收到响应:', response.config.url, data)
|
|
|
|
// 统一处理响应格式
|
|
if (data.code === 200) {
|
|
return {
|
|
success: true,
|
|
data: data.data,
|
|
message: data.message
|
|
}
|
|
} else {
|
|
// 业务错误
|
|
const errorMsg = data.message || '请求失败'
|
|
message.error(errorMsg)
|
|
return {
|
|
success: false,
|
|
data: null,
|
|
message: errorMsg
|
|
}
|
|
}
|
|
},
|
|
(error) => {
|
|
debugLog('响应错误:', error)
|
|
|
|
let errorMsg = '网络错误'
|
|
|
|
if (error.response) {
|
|
const { status, data } = error.response
|
|
|
|
switch (status) {
|
|
case 400:
|
|
errorMsg = data.message || '请求参数错误'
|
|
break
|
|
case 401:
|
|
errorMsg = '未授权,请重新登录'
|
|
// 处理登录过期
|
|
AuthUtils.clearTokens()
|
|
// 跳转到登录页
|
|
if (window.location.pathname !== '/login') {
|
|
window.location.href = '/login'
|
|
}
|
|
break
|
|
case 403:
|
|
errorMsg = '拒绝访问'
|
|
break
|
|
case 404:
|
|
errorMsg = '请求的资源不存在'
|
|
break
|
|
case 500:
|
|
errorMsg = '服务器内部错误'
|
|
break
|
|
default:
|
|
errorMsg = data.message || `请求失败 (${status})`
|
|
}
|
|
} else if (error.request) {
|
|
errorMsg = '网络连接失败,请检查网络'
|
|
} else {
|
|
errorMsg = error.message || '请求配置错误'
|
|
}
|
|
|
|
message.error(errorMsg)
|
|
|
|
return {
|
|
success: false,
|
|
data: null,
|
|
message: errorMsg
|
|
}
|
|
}
|
|
)
|
|
|
|
export default request
|