axios
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| import axios from 'axios'
export const request = createAxiosInstance()
function createAxiosInstance () { const instance = axios.create({ baseURL: process.env.REACT_APP_BASE_URL, timeout: 5000, headers: { post: { 'Content-Type': 'application/json' } ... } }) instance.interceptors.request.use((config) => { loading.open() token && (config.headers.Authorization = token) cleanObject() return config }) instance.interceptors.response.use((response) => { loading.close() const res = response.data const validateStatus = /^(2|3)\d{2}$/ if (validateStatus.test(res.code)) { return res.data } if (res.code === 401) { message.error(res.msg) } else { message.warning(res.msg) } return Promise.reject(res) }, (error) => { loading.close() if (error.response.status === 401) { message.error('token失效,请重新登录!') removeStorageToken() setTimeout(() => { window.location.href = '/login' }, 2000) } else { if (!window.navigator.onLine) { message.warning('网络异常,请检查网络是否正常连接') } else if (error.code === 'ECONNABORTED') { message.warning('请求超时') } else { message.warning('服务器异常,请联系管理员') } } return Promise.reject(error) } )
return instance }
|
axios 默认配置
全局 axios 默认值
1 2 3 4
| axios.defaults.baseURL = "https://api.example.com"; axios.defaults.headers.common["Authorization"] = AUTH_TOKEN; axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
|
自定义实例默认值
1 2 3 4 5 6 7
| const instance = axios.create({ baseURL: "https://api.example.com", });
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;
|
优先级
1 2 3 4 5 6 7 8 9 10 11 12
|
const instance = axios.create();
instance.defaults.timeout = 2500;
instance.get("/longRequest", { timeout: 5000, });
|
请求配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
params: { ID: 12345 },
paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) },
data: { firstName: 'Fred' },
data: 'Country=Brasil&City=Belo Horizonte',
|
Authorization
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const accessToken = localStorage.getItem("accessToken");
this.instance = axios.create(config);
this.instance.defaults.headers.common["Authorization"] = accessToken ? `Bearer ${accessToken}` : null;
this.instance.interceptors.request.use( (config) => { config.headers["Authorization"] = accessToken ? `Bearer ${accessToken}` : null;
return config; }, (error) => { Promise.reject(error); } );
|
竞态问题
无法保证异步操作会按照开始时的顺序执行。比如快速切换分页,但是网络刷新较慢,导致第 2 页请求到了,第 1 页才到。
如何解决
- 取消请求
- 忽略过期请求