cellsysBase/utils/axios.js

68 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import axios from 'axios';
import { AdminQueryType } from '../cellsysUtil';
import cellsysSystem from '../cellsysSystem';
const service = axios.create({
baseURL: '/api', //api 的 base_url根据开发生产环境配置文件配置
withCredentials: true, // 跨域请求时发送 cookies
timeout: 0,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
responseType: 'json',
});
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的项目中按需进行封装。
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);
},
);
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 };