2021-08-26 11:25:15 +08:00
|
|
|
import axios from 'axios';
|
|
|
|
import proxy from '../config/proxy';
|
|
|
|
|
|
|
|
const env = import.meta.env.MODE || 'development';
|
|
|
|
|
|
|
|
const host = env === 'mock' ? '/' : proxy[env].host; // 如果是mock模式 就不配置host 会走本地Mock拦截
|
|
|
|
|
|
|
|
const CODE = {
|
|
|
|
LOGIN_TIMEOUT: 1000,
|
|
|
|
REQUEST_SUCCESS: 0,
|
|
|
|
REQUEST_FOBID: 1001,
|
|
|
|
};
|
|
|
|
|
|
|
|
const instance = axios.create({
|
|
|
|
baseURL: host,
|
|
|
|
timeout: 1000,
|
|
|
|
withCredentials: true,
|
|
|
|
});
|
|
|
|
|
2021-11-26 10:45:04 +08:00
|
|
|
instance.interceptors.request.use((config) => config);
|
2021-08-26 11:25:15 +08:00
|
|
|
|
|
|
|
instance.defaults.retry = 3;
|
|
|
|
|
|
|
|
instance.interceptors.response.use(
|
|
|
|
(response) => {
|
|
|
|
if (response.status === 200) {
|
|
|
|
const { data } = response;
|
|
|
|
if (data.code === CODE.REQUEST_SUCCESS) {
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
}
|
2021-11-26 10:45:04 +08:00
|
|
|
return response;
|
2021-08-26 11:25:15 +08:00
|
|
|
},
|
|
|
|
(err) => {
|
|
|
|
const { config } = err;
|
|
|
|
|
|
|
|
if (!config || !config.retry) return Promise.reject(err);
|
|
|
|
|
|
|
|
config.retryCount = config.retryCount || 0;
|
|
|
|
|
|
|
|
if (config.retryCount >= config.retry) {
|
|
|
|
return Promise.reject(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
config.retryCount += 1;
|
|
|
|
|
|
|
|
const backoff = new Promise((resolve) => {
|
|
|
|
setTimeout(() => {
|
|
|
|
resolve();
|
|
|
|
}, config.retryDelay || 1);
|
|
|
|
});
|
|
|
|
|
|
|
|
return backoff.then(() => instance(config));
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
export default instance;
|