| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- import axios from 'axios';
- import { message } from 'antd';
- import { redirect } from 'react-router-dom';
- const axiosInstance = axios.create({
- baseURL: '/api/v1',
- timeout: 2000,
- });
- // 加入拦截器
- // 添加请求拦截器
- axiosInstance.interceptors.request.use(
- function (config) {
- // 在发送请求之前做些什么
- //! 将token信息携带上
- let token = sessionStorage.getItem('token');
- token && (config.headers['Authorization'] = token);
- return config;
- },
- function (error) {
- // 对请求错误做些什么
- return Promise.reject(error);
- }
- );
- // 添加响应拦截器
- axiosInstance.interceptors.response.use(
- function (response) {
- // 2xx 范围内的状态码都会触发该函数。
- // 对响应数据做点什么
- return response.data;
- },
- function (error) {
- // 超出 2xx 范围的状态码都会触发该函数。
- // 对响应错误做点什么
- // 401错误处理
- console.log(error);
- if (error.response.status == 401) {
- //! 提示用户 未登录或者 登录超时
- message.error('您未登录或登录已超时!请重新登录。');
- //! 页面重定向到 登录上
- redirect('/login');
- return Promise.resolve({});
- }
- return Promise.reject(error);
- }
- );
- export default axiosInstance;
|