1.设置baseURL,timeout
const service = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 50000,
});
2.请求拦截器中添加token,自定义loadding
const service = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 50000,
defaultLoadding: true,
});
service.interceptors.request.use((config) => {
const userInfoStore = useUserInfoStore(pinia);
console.log(config, "zdrconfig");
const { defaultLoadding, loadding } = config || {};
const defaultHeader = {};
if (userInfoStore.token) {
defaultHeader.token = userInfoStore.token;
}
config.headers = { ...defaultHeader, defaultLoadding, loadding };
return config;
});
export const getUserInfoApi = () => {
return request.get<any, userInfoResponseModel>(Api.getUserInfo, { a: 1 });
};
3.响应拦截器中第一个参数是成功的callback,第二个参数是失败的callback
在第一个callback对code不等于200的接口做全局统一错误提示
如果是401的code,要把token,name,等用户信息都重置为空,并中断Promise链(返回一个reject的Promise)
在第二个callback中进行错误提示,并返回错误状态Promise
4.取消重复请求
const requestListMap = new Map();
function getRequestKey(config: AxiosRequestConfig) {
const { url, method, params = {}, data = {} } = config;
return [url, method, JSON.stringify(params), JSON.stringify(data)].join("&");
}
const CancelToken = axios.CancelToken;
function removeRequestKey(config: AxiosRequestConfig, completed?: boolean) {
const requestKey = getRequestKey(config);
if (requestListMap.has(requestKey)) {
const { cancel } = requestListMap.get(requestKey);
!completed && cancel();
requestListMap.delete(requestKey);
}
}
function addRequestKey(config: AxiosRequestConfig) {
const requestKey = getRequestKey(config);
config.cancelToken = new CancelToken((cancel) => {
if (!requestListMap.has(requestKey)) {
requestListMap.set(requestKey, {
cancel,
pathname: window.location.pathname,
});
}
});
}
request.interceptors.request.use((config) => {
const token = useUserStore().token;
if (token) {
config.headers.token = token;
}
removeRequestKey(config);
addRequestKey(config);
return config;
});
1.创建一个map结构
2.把每次请求的url,请求方式,请求参数拼接成map的key,然后封装两个函数,第一个函数删除之前存过key,和取消请求cancel的方法,第二个函数是添加每个请求的key和存当前的cancle函数以及当前的pathname(window.location)
5.取消上一个页面的请求
import { requestListMap } from '@/utils/request';
router.beforeEach((to, from, next) => {
requestListMap.forEach((value, key) => {
const { pathname, cancel } = value;
if (pathname !== to.path) {
cancal();
requestListMap.delete(key);
}
})
})