| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- import axios from 'axios';
- import store from '../states/store';
- import { getApiBaseUrl } from './config';
- import { SystemMode } from '../states/systemModeSlice';
- import emitter from '../utils/eventEmitter';
- import { throttleCount } from '@/utils/throttle';
- const axiosInstance = axios.create({
- baseURL: getApiBaseUrl(),
- timeout: 30000, // 30秒超时,防止请求无限等待
- });
- function expensiveLog(mode) {
- console.log(`当前系统模式:${mode}`);
- }
- const log = throttleCount(expensiveLog, 60);
- axiosInstance.interceptors.request.use(
- (config) => {
- // ✅ 动态设置 baseURL,支持运行时修改
- config.baseURL = getApiBaseUrl();
-
- const state = store.getState();
- log(state.systemMode.mode);
- const token =
- state.systemMode.mode === SystemMode.Emergency
- ? state.product.guest
- : state.userInfo.token;
- const { productName, language, source } = state.product;
- config.headers.Authorization = `Bearer ${token}`;
- config.headers.Language = language;
- config.headers.Product = productName;
- config.headers.Source = source;
- return config;
- },
- (error) => {
- return Promise.reject(error);
- }
- );
- // 请求拦截器
- axiosInstance.interceptors.request.use(
- (config) => {
- if (config.url?.includes('/pub/quota')) {
- // 不打印配额查询请求日志
- return config;
- }
- console.log('【网络】🚀 请求:', {
- url: config.url,
- method: config.method,
- headers: config.headers,
- data: config.data,
- params: config.params,
- });
- return config;
- },
- (error) => {
- console.error('【网络】❌ 请求错误:', error);
- return Promise.reject(error);
- }
- );
- // 响应拦截器
- axiosInstance.interceptors.response.use(
- (response) => {
- if (response.data.code !== '0x000000') {
- console.error('【网络】❌ 响应错误,非"0x000000":', {
- url: response.config.url,
- status: response.status,
- data: response.data,
- });
- } else {
- if (!response.config.url?.includes('/pub/quota')) {
- // 非配额查询响应需要纪录日志
- console.log('【网络】✅ 响应:', {
- url: response.config.url,
- status: response.status,
- data: response.data,
- });
- }
- }
- return response;
- },
- (error) => {
- console.error('【网络】❌ 响应错误:', {
- url: error.config?.url,
- status: error.response?.status,
- message: error.message,
- data: error.response?.data,
- });
- return Promise.reject(error);
- }
- );
- axiosInstance.interceptors.response.use(
- (response) => {
- return response;
- },
- (error) => {
- if (error.response && error.response.data.code === 0x000101) {
- emitter.emit('tokenExpired');
- // eslint-disable-next-line
- return new Promise(() => { }); // Suspend the current execution
- }
- return Promise.reject(error);
- }
- );
- export default axiosInstance;
|