Axios封装(第二版)
· 阅读需 8 分钟
Axios封装
前言
本文基于Axios进行二次封装,皆在提供一种符合直觉且能够在大部分场景上进行使用的封装方式。
第一步创建Axios实例,配置统一的拦截器
import axios, { AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { showMessage } from '@/component/MessageManager';
interface IResponse<T = any> {
success: boolean;
message: string;
data?: T;
token?: string;
}
export interface IQueryList<T> {
itemList: T;
}
export interface IRequestConfig extends AxiosRequestConfig {
toastError?: boolean;
}
export interface IResponseParams<T = any, D = any> extends AxiosResponse<T, D> {
config: InternalAxiosRequestConfig & IRequestConfig;
}
const axiosInstance = axios.create({
baseURL: '/api'
});
//无需登录验证的接口
const noAuthRequestList = ['/user/login', '/user/register', '/song/list'];
axiosInstance.interceptors.request.use(async (config: InternalAxiosRequestConfig & IRequestConfig) => {
try {
if (noAuthRequestList.includes(config.url||'')) {
return config;
} else {
const token = localStorage.getItem('token');
if (!token) {
console.error('请先登录');
// 权限认证失败的情况下
showMessage({ type: 'warning', message: '请先登录' });
return Promise.reject('请先登录');
} else {
config.headers.Authorization = token;
return config;
}
}
} catch (e: any) {
console.error(e);
showMessage({ type: 'error', message: e.message });
return Promise.reject(e);
}
});
axiosInstance.interceptors.response.use(async (response: IResponseParams<IResponse, any>) => {
try {
const { data } = response;
if (data.success) {
if (data.token) {
localStorage.setItem('token', data.token);
}
return response;
} else {
const toastError = response.config.toastError ?? true;
// 服务端响应了数据,但是处理结果是失败的
if (toastError) {
showMessage({ type: 'error', message: data.message });
}
return Promise.reject(data.message);
}
} catch (e: any) {
console.error(e);
return Promise.reject(e);
}
});
关于拦截器的具体细节,大部分与之前保持一致Axios+TypeScript
值得注意的是IRequestConfig
