前端

Vue+axios 实现http拦截及路由拦截实例

2018-07-06  本文已影响36人  若年

首先我们要明白设置拦截器的目的是什么,当我们需要统一处理http请求和响应时我们通过设置拦截器处理方便很多.

这个项目我引入了element ui框架,所以我是结合element中loading和message组件来处理的.我们可以单独建立一个http的js文件处理axios,再到main.js中引入.

http配置

// 引入axios以及element ui中的loading和message组件
import axios from 'axios'
import { Loading, Message } from 'element-ui'
// 超时时间
axios.defaults.timeout = 5000
// http请求拦截器
var loadinginstace
axios.interceptors.request.use(config => {
// element ui Loading方法
loadinginstace = Loading.service({ fullscreen: true })
return config
}, error => {
loadinginstace.close()
Message.error({
message: '加载超时'
})
return Promise.reject(error)
})
// http响应拦截器
axios.interceptors.response.use(data => {// 响应成功关闭loading
loadinginstace.close()
return data
}, error => {
loadinginstace.close()
Message.error({
message: '加载失败'
})
return Promise.reject(error)
})

export default axios

这样我们就统一处理了http请求和响应的拦截.当然我们可以根据具体的业务要求更改拦截中的处理.

设置重新连接

//拦截器
var asemVue = new Vue({
   router,
   store,
   template: '<App/>',
   components: { App }
}).$mount('#app');
// 超时时间
axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;
// http请求拦截器
axios.interceptors.request.use(  config => {
   if (config.url.indexOf('http://jwux.top:38028/avatar/t/')>-1) {
      return;
   }
      return config;
},error => {
   Vue.prototype.$message.error({
       message: '加载超时'
   });
   return Promise.reject(error);
});
// http响应拦截器
axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
   var config = err.config;
   // If config does not exist or the retry option is not set, reject
   if(!config || !config.retry) return Promise.reject(err);
   // Set the variable for keeping track of the retry count
   config.__retryCount = config.__retryCount || 0;
   // Check if we've maxed out the total number of retries
   if(config.__retryCount >= config.retry) {
       // Reject with the error
       Vue.prototype.$Message.warning(
       '网络异常,请稍后再试!'
     );
       return Promise.reject(err);
   }
   // Increase the retry count
   config.__retryCount += 1;
   // Create new promise to handle exponential backoff
   var backoff = new Promise(function(resolve) {
       setTimeout(function() {
           Vue.prototype.$Message.warning('正在重连');
           resolve();
       }, config.retryDelay || 1);
   });
   // Return the promise in which recalls axios to retry the request
   return backoff.then(function() {
       return axios(config);
   });
});
上一篇 下一篇

猜你喜欢

热点阅读