[本文出自天外歸雲的博客園]ios
這是個人Vue項目中的request.js文件,請求報錯了看console就會有具體請求信息,方便調試。分享一下。element-ui
其中用到了axios和element-ui的組件,axios是用來收發請求的,element-ui中的Message和Loading組件主要是配合axios對請求中和請求失敗的狀況在頁面上進行可視化配合。axios
代碼以下:app
import axios from 'axios' import { Message, Loading } from 'element-ui' let loading let needLoadingRequestCount = 0 function startLoading () { loading = Loading.service({ lock: true }) } export function showLoading () { if (needLoadingRequestCount === 0) { startLoading() } needLoadingRequestCount++ } export function hideLoading () { if (needLoadingRequestCount <= 0) return needLoadingRequestCount-- if (needLoadingRequestCount === 0) { loading.close() } } const instance = axios.create({ baseURL: process.env.BASE_API, timeout: 150000, headers: { 'Content-Type': 'application/x-www-form-urlencoded;' } }) instance.interceptors.request.use( function (config) { console.log('[發起請求]' + JSON.stringify(config.data)) showLoading() return config }, function (error) { return Promise.reject(error) } ) instance.interceptors.response.use( response => { const res = response.data if (res.retcode !== 200) { // Message({ // message: '[接口返回非200異常]請從新刷新頁面', // type: 'error', // duration: 5 * 1000 // }) hideLoading() return Promise.reject(new Error('返回非200')).catch( console.log('[請求]' + response.config.data + '\n[返回異常]' + res) ) } else if (JSON.stringify(res.data) === '{}') { return Promise.reject(new Error('no data')) .then(result => console.log(result)) .catch(error => console.log(error)) } else { hideLoading() return res.data } }, error => { Message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error).catch(console.log(error)) } ) export default instance
其中process.env在config/dev.env.js中定義:ide