66 lines
1.6 KiB
JavaScript
66 lines
1.6 KiB
JavaScript
// src/utils/axiosConfig.js
|
|
// Axios 全局配置和拦截器
|
|
|
|
import axios from 'axios';
|
|
import { getApiBase } from './apiConfig';
|
|
import { logger } from './logger';
|
|
|
|
// 判断当前是否是生产环境
|
|
const isProduction = process.env.NODE_ENV === 'production';
|
|
|
|
// 配置基础 URL
|
|
const API_BASE_URL = getApiBase();
|
|
|
|
// 配置 axios 默认值
|
|
axios.defaults.baseURL = API_BASE_URL;
|
|
axios.defaults.withCredentials = true;
|
|
axios.defaults.headers.common['Content-Type'] = 'application/json';
|
|
|
|
/**
|
|
* 请求拦截器
|
|
* 自动记录所有请求日志
|
|
*/
|
|
axios.interceptors.request.use(
|
|
(config) => {
|
|
const method = config.method?.toUpperCase() || 'GET';
|
|
const url = config.url || '';
|
|
const data = config.data || config.params || null;
|
|
|
|
logger.api.request(method, url, data);
|
|
|
|
return config;
|
|
},
|
|
(error) => {
|
|
logger.api.error('REQUEST', 'Interceptor', error);
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
/**
|
|
* 响应拦截器
|
|
* 自动记录所有响应/错误日志
|
|
*/
|
|
axios.interceptors.response.use(
|
|
(response) => {
|
|
const method = response.config.method?.toUpperCase() || 'GET';
|
|
const url = response.config.url || '';
|
|
const status = response.status;
|
|
const data = response.data;
|
|
|
|
logger.api.response(method, url, status, data);
|
|
|
|
return response;
|
|
},
|
|
(error) => {
|
|
const method = error.config?.method?.toUpperCase() || 'UNKNOWN';
|
|
const url = error.config?.url || 'UNKNOWN';
|
|
const requestData = error.config?.data || error.config?.params || null;
|
|
|
|
logger.api.error(method, url, error, requestData);
|
|
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default axios;
|