2025-03-10 19:01:21 +08:00
|
|
|
import axios from 'axios';
|
2025-04-19 15:28:32 +08:00
|
|
|
import AESCrypto from "./AESCrypto.js";
|
|
|
|
|
import {Message} from '@arco-design/web-vue';
|
|
|
|
|
import {useUserStore} from "../pinia/UserStore/index.js";
|
2025-03-10 19:01:21 +08:00
|
|
|
|
2025-04-24 19:17:53 +08:00
|
|
|
export const BASEURL = import.meta.env.MODE === 'development' ? '/baseApi' : import.meta.env.VITE_API_URL;
|
|
|
|
|
|
2025-03-10 19:01:21 +08:00
|
|
|
// 创建 Axios 实例
|
|
|
|
|
const request = axios.create({
|
2025-04-24 19:17:53 +08:00
|
|
|
baseURL: BASEURL, // 替换为你的基础 URL
|
2025-03-10 19:01:21 +08:00
|
|
|
timeout: 10000, // 请求超时设置
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// 请求拦截器
|
2025-04-19 15:28:32 +08:00
|
|
|
request.interceptors.request.use((config) => {
|
|
|
|
|
const {token} = useUserStore();
|
|
|
|
|
|
|
|
|
|
// 如果 token 存在,则将其添加到请求头中
|
|
|
|
|
if (token) {
|
|
|
|
|
config.headers['Access-Token'] = token;
|
2025-03-10 19:01:21 +08:00
|
|
|
}
|
2025-04-19 15:28:32 +08:00
|
|
|
|
|
|
|
|
console.log('请求拦截器', config.data);
|
|
|
|
|
|
2025-04-23 19:48:47 +08:00
|
|
|
if (!config.UN_AES) {
|
|
|
|
|
const {context, iv} = AESCrypto.encrypt(JSON.stringify(config.data));
|
2025-04-19 15:28:32 +08:00
|
|
|
|
2025-04-23 19:48:47 +08:00
|
|
|
config.data = {
|
|
|
|
|
requestData: context, iv: iv,
|
|
|
|
|
};
|
|
|
|
|
}
|
2025-04-19 15:28:32 +08:00
|
|
|
|
|
|
|
|
return config;
|
|
|
|
|
}, (error) => {
|
|
|
|
|
return Promise.reject(error);
|
|
|
|
|
});
|
2025-03-10 19:01:21 +08:00
|
|
|
|
|
|
|
|
// 响应拦截器
|
2025-04-19 15:28:32 +08:00
|
|
|
request.interceptors.response.use((response) => {
|
|
|
|
|
const {data: {msg, code, data}, config: {url}} = response;
|
|
|
|
|
console.log(response)
|
2025-04-21 10:30:45 +08:00
|
|
|
if (code === 401) {
|
|
|
|
|
const {logout} = useUserStore();
|
|
|
|
|
logout();
|
|
|
|
|
}
|
2025-04-19 15:28:32 +08:00
|
|
|
if (code !== 1) {
|
|
|
|
|
Message.error(msg);
|
2025-04-23 19:48:47 +08:00
|
|
|
return Promise.reject(msg);
|
2025-04-19 15:28:32 +08:00
|
|
|
}
|
|
|
|
|
if (!data.data) {
|
|
|
|
|
return {msg, code, data}
|
|
|
|
|
} else {
|
|
|
|
|
const resp = JSON.parse(AESCrypto.decrypt(data.data, data.iv));
|
|
|
|
|
console.log(`接口${url}返回`, resp);
|
|
|
|
|
return {data: resp};
|
2025-03-10 19:01:21 +08:00
|
|
|
}
|
2025-04-19 15:28:32 +08:00
|
|
|
}, (error) => {
|
|
|
|
|
if (error.response) {
|
|
|
|
|
return Promise.reject(error.response.data); // 返回错误信息
|
|
|
|
|
} else { // 网络错误
|
|
|
|
|
return Promise.reject(error.message);
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-03-10 19:01:21 +08:00
|
|
|
|
|
|
|
|
export default request; // 导出 Axios 实例
|