cellsysBase/utils/axios.js

68 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-12-26 11:21:07 +08:00
import axios from 'axios';
2024-12-26 16:18:03 +08:00
import { AdminQueryType } from '../cellsysUtil';
import cellsysSystem from '../cellsysSystem';
2024-12-26 11:21:07 +08:00
const service = axios.create({
baseURL: '/api', //api 的 base_url根据开发生产环境配置文件配置
withCredentials: true, // 跨域请求时发送 cookies
timeout: 0,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
responseType: 'json',
});
2024-12-26 16:18:03 +08:00
service.interceptors.request.use(
(config) => {
let url = config.url;
let token = cellsysSystem.token;
if (AdminQueryType.indexOf(url) !== -1) {
//这里应该再加一层用户身份判断才是正确的写法
token = cellsysSystem.adminToken;
}
if (token && !config.headers['Authorization']) {
config.headers['Authorization'] = 'Bearer ' + token;
}
return config;
},
(error) => {
console.error(error);
return Promise.reject(error);
},
);
//这里需要注意的是由于历史原因axios的response的成功回调格式是在本文件中封装而失败回调的格式是在引用CellsysBase的项目中按需进行封装。
2024-12-26 16:18:03 +08:00
service.interceptors.response.use(
(response) => {
let data;
if (response.data === undefined || response.data == null) {
switch (response.status) {
case 201:
data = { code: 201 };
break;
default:
data = { code: 200 };
break;
}
} else {
data = response.data;
}
return data;
},
(err) => {
return Promise.reject(err);
},
);
2024-12-26 11:21:07 +08:00
const post = (url, data, config) => {
return service.post(url, data, config);
};
const get = (url, data) => {
return service.get(url, {
params: data,
});
};
export { post, get, service };