约定 src/app.tsx 为运行时配置
import { request } from ‘umi’;
umijs 默认使用 request 请求数据,通过 request 配置来
- 自定义中间件
- 拦截器
- requestInterceptors 请求拦截器
- responseInterceptors 响应拦截器
- 错误处理适配
- errorConfig
axios
request 拦截器文档 https://umijs.org/docs/max/request#requestinterceptors
配置的规则将应用于所有的 request 和 useRequest 方法
其它配置都直接透传 axios 的 request 配置
import { message } from 'antd';import { isEmpty } from 'lodash-es';import type { RequestConfig } from '@umijs/max';import { JWT_TOKEN } from '@/constants';export const request = {timeout: 5000,// 请求设定统一的错误处理方案errorConfig: {errorHandler() {console.log('request errorHandler')},// catch 抛出的错误 触发条件,当 data.success = falseerrorThrower(err: { msg: string | null | undefined }) {message.destroy()message.error(err.msg)},},// 请求拦截器requestInterceptors: [(config: RequestConfig) => {if(config.version === 'v2') {config.baseURL = process.env.APP_BASE_API_V2}const { method, data } = configconst isMethod = filterMethods.includes(method)if (isMethod && !isEmpty(data)) {// 过滤 null等字段config.data = omitValues(data, ['createdAt', 'updatedAt'])}const token = localStorage.getItem(JWT_TOKEN)if (token) {config.headers!.Authorization = `Bearer ${token}`}return config},],// 响应拦截器responseInterceptors: [(response: { status: any; data: any }) => {// 不再需要异步处理读取返回体内容,可直接在data中读出,部分字段可在 config 中找到const { status, data } = responseif (status !== 200) {return response}if (data.code === 0) {return data}if (401 === data.status) {location.href = '/login'return}return response},],}
