axios官方文档
说明:这里是在老项目中继续封装的,如果新项目可以将index.ts中的响应拦截异常处理和request中的异常处理合并在一起,无感刷新token,由于提供了思路,一共参考
index.ts
axios的基本封装(请求拦截、响应拦截)
import { message } from 'ant-design-vue';
import axios from 'axios';
import router from '../router';
import { globalData } from '../setting/global';
import { ref } from 'vue';
const host = ref('localhost');
const serverUrl = ref('localhost');
const Store = require('electron-store');
const store = new Store();
const serverAddressIp = store.get('serverAddressIp');
if (serverAddressIp) {
host.value = serverAddressIp;
}
serverUrl.value = 'http://' + host.value + ':8102';
export function updateServer(address: string) {
host.value = address;
serverUrl.value = 'http://' + host.value + ':8102';
}
export const serverAddress = () => serverUrl.value + '/';
export const serverIp = () => host.value;
axios.defaults.withCredentials = true;
let config = {
baseURL: serverUrl.value ? serverUrl.value : globalData.apiUrl,
withCredentials: true,
Headers: {
'Content-Type': 'application/json',
},
timeout: 10 * 60 * 1000,
};
const http = axios.create(config);
http.interceptors.request.use(
(config: any) => {
const token = sessionStorage.getItem('TOKEN');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
config.headers['Content-Type'] = 'application/json';
config.url = serverUrl.value + config.url;
return config;
},
(error) => {
return Promise.reject(error);
},
);
http.interceptors.response.use(
(response) => {
return response.data;
},
(error) => {
if (error.message.includes('timeout')) {
return Promise.reject('timeout');
message.error('任务执行时间过长');
} else if (error.response?.status === 401) {
message.error('身份已失效,请重新登录!');
router.push('/login');
} else if (error.response?.status === 405) {
message.error('请求方式错误');
} else if (error.response?.status === 500) {
message.error('服务器内部错误');
} else if (error.response?.status === 400) {
console.log('请求错误');
} else if (error.response?.status === 403) {
console.log('拒绝访问');
} else if (error.response?.status === 404) {
console.log('请求地址出错');
} else if (error.response?.status === 422) {
console.log('请求参数错误');
} else if (error.response?.status === 501) {
console.log('服务未实现');
} else if (error.response?.status === 502) {
console.log('网关错误');
} else if (error.response?.status === 503) {
console.log('服务不可用');
} else if (error.response?.status === 504) {
console.log('网关超时');
} else if (error.response?.status === 505) {
console.log('HTTP版本不受支持');
}
return Promise.reject(error.response);
},
);
export default http;
request.ts
在index.ts的基础上增加请求重试、请求终止(也可以实现无感刷新)
import http from './index';
const timeout = 60000;
let retryTime = 1;
let configTemp: any = {};
function request(config: any) {
configTemp = config;
return http({
...config,
})
.then((res) => {
return Promise.resolve(res);
})
.catch((error) => {
console.log(error);
if (error.includes('timeout'))
if (retryTime >= 3) {
} else {
retryTime++;
request(configTemp);
}
return Promise.reject(error);
});
}
export function get(url: string, params = {}, other?: any) {
return request({
url,
params,
method: 'get',
...other,
});
}
export function post(url: string, data = {}, other?: any) {
return request({
url,
data,
method: 'post',
...other,
});
}
export function put(url: string, data = {}) {
return request({
url,
data,
method: 'put',
});
}
export function del(url: string, params = {}) {
return request({
url,
params,
method: 'delete',
});
}
index.ts 和 request.ts 中的方法使用
import http from '../../index';
import { formatQuery } from '../../../libs/utils/format';
import { get, post, put, del } from '../../request';
const prefix: string = '/meta/tasks';
export const formatQuery = (q: any) => {
let query = '';
Object.keys(q).forEach((key) => {
if (q[key] !== '' && q[key] !== undefined) {
query += `${key}=${q[key]}&`;
}
});
return query.substring(0, query.length - 1);
};
export const getTasks = (
status: string | undefined,
page: number,
pageSize: number,
signal: any,
sorterName?: string,
sorterType?: string,
sixteen?: string,
generation?: string,
name?: string,
) => {
return http.get(
`${prefix}?${formatQuery({
query: status !== '' && status !== undefined ? `status:${status}` : '',
page,
pageSize,
sorterName,
sorterType,
sixteen,
generation,
name,
})}`,
);
};
export const getTasks2 = (
status: string | undefined,
page: number,
pageSize: number,
signal: any,
sorterName?: string,
sorterType?: string,
sixteen?: string,
generation?: string,
name?: string,
) => {
let params = {
query: status !== '' && status !== undefined ? `status:${status}` : '',
page,
pageSize,
sorterName,
sorterType,
sixteen,
generation,
name,
};
return get(prefix, params, { signal });
};