开始
在全局包装一层axios,方便之后的调用、权限、异常等处理。
utils/http.js
const axios = require('axios');const http = function() {// 全局的请求次数,请求的间隙,超时时间axios.defaults.retry = 1;axios.defaults.retryDelay = 100;axios.defaults.timeout = 1000 * 36;// 包装requestaxios.interceptors.request.use(function(config) {// Do something before request is sentreturn config;},function(error) {// Do something with request errorreturn Promise.reject(error);},);// 包装responseaxios.interceptors.response.use(function(response) {return response.data;},function(error) {// error.response 是接口返回等结构体// 如果为undefined,就视为没有返回,体现为超时if (error.response) {// 对特殊错误码进行处理if (error.response.status === 401) {window.location.href = '/login?callback=' + window.location.href;}return Promise.reject(error);} else {var config = error.config;// 如果配置不存在或未设置重试选项,就拒绝if (!config || !config.retry) return Promise.reject(error);// 设置用于跟踪重试计数的变量config.__retryCount = config.__retryCount || 0;// 检查我们是否已达到最大重试次数if (config.__retryCount >= config.retry) {// 以错误拒绝return Promise.reject(err);}// 增加重试次数config.__retryCount += 1;// 创建新承诺以处理指数退避var backoff = new Promise(function(resolve) {setTimeout(function() {resolve();}, config.retryDelay || 1);});// 返回撤回axios重试请求的承诺return backoff.then(function() {return axios(config);});}},);return axios;}Vue.prototype.$http = http();
其他的那个几十个.vue 页面的 this.$http 的 get 和 post 的方法根本就不需要去修改它们的代码。
