/** * 对Axios进行了封装 * 1. 接口错误拦截 请求本身异常 或 服务端报错 均会触发catch 自动调用notify进行提示 * 本次请求response返回null 可以在config中配置 noNotify 禁用自动错误提示 * 2. 可以在config中添加catcher函数 处理异常 * 3. config 加上encode 会自动encode params */ import axios, { AxiosResponse, AxiosRequestConfig, AxiosError } from 'axios' import { warn } from './common' export type RequestResponse = null | AxiosResponse export type RequestConfig = { /** * @description 关闭默认错误提示 */ noNotify?: boolean /** * @description 异常处理器 */ catcher?: (err: RequestError) => RequestResponse /** * @description response处理器 */ transformResponse?: (data: Data) => Data /** * @description params参数格式 */ params?: { [propName: string]: any } /** * @description 是否对params进行encodeURLComponent */ encode?: true } & AxiosRequestConfig export type RequestError = AxiosError & { config: RequestConfig } function encodeParams(config: RequestConfig): RequestConfig { const { params } = config return { ...config, params: { ...Object.entries(params || {}).reduce((_, [key, value]) => { _[key] = typeof value === 'string' ? encodeURIComponent(value) : value return _ }, {} as typeof params), }, } } function requestWrapper(method: 'get' | 'patch' | 'post' | 'put' | 'delete') { return function ( url: string, payload?: any, config: RequestConfig = {} ): Promise> { const { noNotify, catcher, encode } = config config = { url, method, [method === 'get' || method === 'patch' ? 'params' : 'data']: payload || {}, ...config, withCredentials: true } if (encode) config = encodeParams(config) return axios .request(config) .then(response => { return response }) .catch((err: RequestError) => { if (catcher) return catcher(err) const { response } = err const message = response?.data?.message || '数据异常,请稍后再试!' if (!noNotify) warn(message) return null }) } } export const del = requestWrapper('delete') export const get = requestWrapper('get') export const put = requestWrapper('put') export const post = requestWrapper('post') export const patch = requestWrapper('patch')