import axios from 'axios' import { MessageBox, Message } from 'element-ui' import store from '@/store' import { getToken } from '@/utils/auth' import { Loading } from 'element-ui'; //开始加载动画 let loading; let loadingFlag = false; function startLoading() { loadingFlag = true; loading = Loading.service({ // target: '.main-container', text:'拼命加载中...',//加载中需要显示的文字 background:'rgba(0,0,0,.7)',//背景颜色 }); } //结束加载动画 function endLoading() { loading.close(); } // create an axios instance const service = axios.create({ baseURL: process.env.VUE_APP_BASE_API + '/api', // url = base url + request url // withCredentials: true, // send cookies when cross-domain requests timeout: 10000 // request timeout }) // request interceptor service.interceptors.request.use( config => { // do something before request is sent if (store.getters.Authorization) { // let each request carry token // ['X-Token'] is a custom headers key // please modify it according to the actual situation config.headers['Authorization'] = getToken(); startLoading(); // 判断当前请求是否设置了不显示Loading if(config.headers.showLoading !== false){ startLoading();//请求时的加载动画 } } return config }, error => { // do something with request error console.log(error) // for debug return Promise.reject(error) } ) // response interceptor service.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; // if the custom code is not 20000, it is judged as an error. if (res.code != 200) { Message({ message: res.msg || 'Error', type: 'error', duration: 10 * 1000 }) // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired; if (res.code == "1003") { // to re-login MessageBox.confirm(res.msg, { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => { store.dispatch('user/resetToken').then(() => { location.reload() }) }) } if(loadingFlag){ endLoading(); } } else { if(loadingFlag){ endLoading(); } return res } }, error => { if(loadingFlag){ endLoading(); } console.log('err' + error) // for debug // 判断请求异常信息中是否含有超时timeout字符串 if(error.message.includes('timeout')){ Message({ message: '请求超时', type: 'error', duration: 5 * 1000 }) }else if(error.response.status == '502'){ Message({ message: '网关错误', type: 'error', duration: 5 * 1000 }) }else if(error.response.status == '500'){ Message({ message: '服务器错误,请联系管理员', type: 'error', duration: 5 * 1000 }) } else{ Message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error); } // return Promise.reject(error) } ) export default service
vue axios请求全局配置返回提示信息&且全局配置加载loading
最新推荐文章于 2024-05-23 15:25:32 发布