通常在请求拦截器中可以做 Loading加载动画,token过期验证,登陆验证等等…
响应拦截器中可以做 统一报错信息处理
import Axios from 'axios'; import router from '../router'; import { Message } from 'element-ui';
Axios.defaults.baseURL = process.env.VUE_APP_BASE_API; Axios.defaults.timeout = 5000;
Axios.interceptors.request.use( config => { let token = JSON.parse(localStorage.getItem('token') || null); if (token) { config.headers['secretKey'] = token.secretKey; config.headers['timestamp'] = token.timestamp; config.headers['uuid'] = token.uuid; } return config; }, err => { console.log(err); } );
Axios.interceptors.response.use( res => { if (res.data.status_code !== 200) { Message({ message: res.data.message, type: 'error' }); if (res.data.status_code === 401) { router.push({ path: '/login' }); } } return res.data; }, err => { console.log(err); let originalRequest = err.config; console.log(err.message); if (err.code === 'ECONNABORTED' && err.message.indexOf('timeout') !== -1 && !originalRequest._retry) { originalRequest._retry = true Message.error('请求超时,尝试重新请求中...') return Axios.request(originalRequest); }
} );
|