已经开发了几个vue项目,然后对 axios的封装 不断优化。现在我用起来也比较方便。
主要特点:
超时处理
统一http状态码 处理
统一错误处理
鉴权等
页面构成

页面构成.png
axios配置
需要 npm axios 和 store2
import axios from 'axios';import store2 from 'store2' //一个localStorage和sessionStorage 处理模块// import qs from 'qs';axios.defaults.baseURL = 'http://10.10.80.126:8081', //开发ip// axios.defaults.baseURL = 'http://45.105.126.130', //测试ipaxios.defaults.timeout = 6000; //超时时间axios.defaults.headers = { 'Content-Type': 'application/json'};
axios.defaults.retry = 4; //超时 全局的请求次数 再重新请求4次,也就是最多请求5次axios.defaults.retryDelay = 500; //超时 请求的间隔时间(比如超时后,下一次请求时间就是 超时时间 加上 超时请求间隔时间)axios.interceptors.request.use(config => { //(loding动画)开始
//我们采用token验证,所以在这里统一 给header 添加token
const token = store2.session('token'); if(token){
config.headers.Authorization = token.accessToken;
} return config
}, error => { return Promise.reject(error)
})
axios.interceptors.response.use(response => { //(loding动画)结束
return response
}, error => { //里面处理 超时请求
var config = error.config; console.log(config) // If config does not exist or the retry option is not set, reject
if(!config || !config.retry) return Promise.reject(error); // 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
alert('服务器请求超时,请检出网络,或联系客服') return Promise.reject(error);
} // Increase the retry count
config.__retryCount += 1; // Create new promise to handle exponential backoff
var backoff = new Promise(function(resolve) {
setTimeout(function() {
resolve();
}, config.retryDelay || 1);
}); // Return the promise in which recalls axios to retry the request
return backoff.then(function() { return axios(config);
});
})export default axios;请求、错误处理 ,作为插件使用
import axios from "./axios";//根据httpcode 状态码处理错误function checkStatus (res) { switch (res.status)
{ case 200 :{
alert(200) return res break;
} case 403 :{
alert('403');//我们后台 是处理登录过期
return false
break;
} case 500 :{
alert('500');//处理500错误
return false
break;
} default: return false
break;
}
}//统一处理 接口错误function checkCode (res) { console.log(res) if(res){ if(res.data.response.success){ //res.data.data.success 这里是我们后端数据是这样
return res
}else {
alert('具体接口错误'); //比如:登录密码错误等,所有接口错误 都在这里处理了
return false
}
}else { return false
}
}// 处理请求的差异,比如表单数据序列化,get,post 请求头是否一样 等function formatDate(method = 'GET', params) { switch (method) { case 'POST': return {
method, data: params
} case 'PUT': return {
method, data: params
} case 'DELETE': return {
method
} case 'GET': return {
method,
params
} default: return {
method,
params
}
}
}const api = { // 轮播图 Object.assign 是合并对象,也就是axios的配置
getCarouselList(params) { return axios(Object.assign(formatDate('GET', params), { url: `/carousel/1`
})).then(checkStatus).then(checkCode)
}, //登录
login(params){ return axios(Object.assign(formatDate('POST', params), { url: `/login`
})).then(checkStatus).then(checkCode)
}
}//定义插件export default { install: function(Vue, Option) { Object.defineProperty(Vue.prototype, "$http", { value: api });
}
};main.js应用
import api from './axios/api'Vue.use(api)
页面使用
//这里是在api.js定义的插件this.$http.getCarouselList().then(data => { if(data){ //处理数据
}
})
作者:xilong
链接:https://www.jianshu.com/p/7387a28a7e6f
随时随地看视频