request.js
import axios from 'axios'import { MessageBox, Message } from 'element-ui'import store from '@/store'import router from '@/router'import { removeStorage, throttle } from '@/utils/index'// create an axios instanceconst service = axios.create({ // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url withCredentials: true, // send cookies when cross-domain requests validateStatus: null, timeout: 10000, // request timeout // headers: {'Content-Type': 'application/json'}})// request interceptorservice.interceptors.request.use( config => { return config }, error => { // do something with request error console.log(error) // for debug return Promise.reject(error) })var goLoginPageThrottle = throttle(() => { console.log('goLoginPageThrottle') MessageBox('登录状态已超时,请重新登录!', '提示', { confirmButtonText: '确定', center: true }).then((action) => { console.log(location) removeStorage('USER_INFO') router.push(`/login?redirect=${location.pathname + location.search}`) }).catch(err => { console.log('cancle', err) removeStorage('USER_INFO') router.push(`/login?redirect=${location.pathname + location.search}`) })}, 2000)// response interceptorservice.interceptors.response.use( /** * If you want to get http information such as headers or status * Please return response => response */ /** * Determine the request status by custom code * Here is just an example * You can also judge the status by HTTP Status Code */ response => { const res = response.data // console.log('response', response) // if the custom code is not 20000, it is judged as an error. switch (response.status) { case 200: return res case 401: if (location.pathname === '/login') { return Promise.reject(res) } else { // 加入缓冲,避免多次弹窗 goLoginPageThrottle() // if (loginGoing === false) { // loginGoing = true // // router.push(`/login?redirect=${location.pathname + location.search}`) // // router.push(`/login`) // } else { // console.log('loginGoing', loginGoing) // } return Promise.reject(res) } case 504: Message({ message: res.message || '请求超时,请稍后再试', type: 'error', duration: 5 * 1000 }) return Promise.reject(res) default: Message({ message: res.message || '服务器开小差了,请稍后再试', type: 'error', duration: 5 * 1000 }) return Promise.reject(res) } }, error => { console.log('err' + error) // for debug Message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error) })/* * @params {string} url 请求地址 * @params {object} resOpts 请求配置参数 */export const download = (url, resOpts = {}) => { const { type = 'get', data = {}} = resOpts const queryArgs = { url, method: type, data, responseType: 'blob', headers: { 'Content-Type': 'application/json;charset=utf-8', withCredentials: true, }, } // tips: 这里直接返回的是response整体! return axios.request(queryArgs).catch(err => console.log(err))}export default service