67 lines
2.0 KiB
JavaScript
67 lines
2.0 KiB
JavaScript
// api.js
|
||
import axios from 'axios';
|
||
import AsyncStorage from '@/storage/index';
|
||
import {filterEmptyValue} from '@/utils/common';
|
||
import Env from '@/config/env';
|
||
|
||
// const BASE_URL = 'http://129.226.148.140:8000'
|
||
// 测试环境
|
||
// const BASE_URL = 'https://me.dreamwork.site/eladmin/';
|
||
// 正式环境
|
||
// const BASE_URL = 'https://mesystem.online/eladmin/'
|
||
// 创建 Axios 实例
|
||
const api = axios.create({
|
||
baseURL: `${Env.URL}${Env.BASE}`, // 设置你的基地址
|
||
timeout: 10000, // 设置请求超时时间
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
});
|
||
|
||
// 请求拦截器
|
||
api.interceptors.request.use(
|
||
async config => {
|
||
// config.url = config.url.replace('mesapi', '');
|
||
// console.log('🚀 ~ config:', config);
|
||
try {
|
||
// 假设获取 token 是一个异步操作
|
||
const token = await AsyncStorage.getItem('appToken');
|
||
|
||
// 将 token 添加到请求头
|
||
// config.headers.Authorization = `Bearer ${token}`;
|
||
|
||
if (token && token.appToken) {
|
||
config.headers.Authorization = token.appToken;
|
||
config.headers.token = token.appToken; // 让每个请求携带自定义token 请根据实际情况自行修改
|
||
}
|
||
} catch (error) {
|
||
console.error('获取 token 失败:', error);
|
||
// 处理错误,比如可以抛出错误或者记录日志
|
||
// 也可以重试以获取 token,视需求而定
|
||
}
|
||
// console.log('🚀 ~ config:', config);
|
||
|
||
config.params = filterEmptyValue(config.params || {});
|
||
if (config.headers['Content-Type'] != 'multipart/form-data') {
|
||
config.data = filterEmptyValue(config.data || {});
|
||
}
|
||
|
||
return config;
|
||
},
|
||
error => Promise.reject(error),
|
||
);
|
||
|
||
// 响应拦截器
|
||
api.interceptors.response.use(
|
||
response => {
|
||
return response.data;
|
||
},
|
||
error => {
|
||
// 可以在这里统一处理错误(如错误提示、日志记录等)
|
||
console.error('API response error:',error , error && error.response);
|
||
return Promise.reject(error);
|
||
},
|
||
);
|
||
|
||
export default api;
|