拦截器

PPG007 ... 2021-12-26 Less than 1 minute

# 拦截器

Interceptor (opens new window)

# 请求拦截器

Tips

use() 方法的两个参数都是函数,要返回参数类型的变量。

axios.interceptors.request.use(
  (config) => {
    // 对请求做配置
    config.headers[UserInfoKeys.TOKENKEY] = sessionStorage.getItem(UserInfoKeys.TOKENKEY);
    return config;
  },
  // 错误处理
  (error) => Promise.reject(error),
);
1
2
3
4
5
6
7
8
9

# 响应拦截器

axios.interceptors.response.use(
  // 正常情况下直接返回响应
  (response) => response,
  // 出错后再处理
  (error) => {
    if (error.response === 401) {
      message.warn('请先登录');
    } else {
      message.error('网络错误');
    }
    return Promise.reject(error);
  },
);
1
2
3
4
5
6
7
8
9
10
11
12
13

注意

在配置了拦截器后,要将配置过的 axios 导出:

export default axios;
1
Last update: November 4, 2022 16:14
Contributors: PPG007 , Koston Zhuang , PPG007