之前有发过Fetch请求封装,有朋友问跟axios有什么区别,顺便发一份axios请求封装.
主要代码
import qs from 'qs';import axios from 'axios';import { Message } from 'iview';import uitls from './util';let baseUrl = 'http://192.168.0.1:8888/'; //设置你的baseUrlconst CancelToken = axios.CancelToken;const source = CancelToken.source();//设置tokenfunction setToken() { if (utils.local.get('token')) { axios.defaults.headers.common['token'] = utils.getLocal('token'); } }//请求验证拦截器axios.interceptors.request.use(config => { store.commit('UPDATE_LOADING', true); //显示loading,这里没有用vuex可以省去 //判断请求不是登陆接口的时候,字段是不是过期了,(根据业务逻辑做对应的处理) if (config.url.indexOf('login') < 0) { let lessTime = Number(uitls.local.get('expireTime')) - Date.now(); //后台返回的过期时间与现在的进行计算 if (lessTime <= 0) { Message.error({ content: '登陆过期', duration: 5 }); source.token('token过期了'); store.commit('UPDATE_LOADING', false); //隐藏loading window.location.href = '/login'; utils.local.clear(); } } return config; });//返回数据拦截器axios.interceptors.response.use(res => { if (res.config.url.indexOf('login') >= 0) { const { token, expireTime, code, data } = res.data; if (code == '200') { //登陆后做出一些本地的处理,按需加载,() //................... utils.local.set('expireTime', expireTime); //过期时间 utils.local.set('token', token); } } return res; });//封装请求方法function formatReq(type, url, data) { setToken(); return new Promise((reslove, reject) => { axios({ method: type, url: `${baseUrl}${url}`, headers: { //这里的请求头与后台商量设置 'content-Type': 'application/x-www-form-urlencoded' }, cancelToken: source.token, data: qs.stringify(data) //java后台用qs转 // data:JSON.stringify(data)//PHP后台用JSON转 }) .then(r => { store.commit('UPDATE_LOADING', false); //隐藏loading //这里可以添加指定对应状态码的处理方式,比如登陆过期,res.data.code === '6666' 路由跳转到login reslove(r); }) .catch(e => { store.commit('UPDATE_LOADING', false); //隐藏loading reject(e.message); Message.error(e.message); }); }); }const Http = { get: (url, query) => { url = utils.formatUrl(url, query); setToken(); return axios.get(`${baseUrl}${url}`, { cancelToken: source.token }).then(r => r); }, post: (url, data) => formatReq('post', url, data), put: (url, data) => formatReq('put', url, data), patch: (url, data) => formatReq('patch', url, data), delete: (url, data) => formatReq('delete', url, data) };export default Http;
util.js
//处理get请求,传入参数对象拼接let formatUrl = obj => { let params = Object.values(obj).reduce((a, b, i) => `${a}${Object.keys(obj)[i]}=${b}&`, '?'); return params.substring(0, params.length - 1); };//增删改查本地存储let local = { set(key, value) { if (checkLocalStorage()) { window.localStorage.setItem(key, value); } else { let Days = 30; let exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = key + '=' + escape(value) + ';expires=' + exp.toGMTString(); } }, get(key) { if (checkLocalStorage()) { return window.localStorage.getItem(key) ? window.localStorage.getItem(key) : null; } else { return getCookie(key); } }, clear(key) { if (checkLocalStorage()) { window.localStorage.removeItem(key); } else { let exp = new Date(); exp.setTime(exp.getTime() - 1); let cval = getCookie(key); if (cval != null) document.cookie = key + '=' + cval + ';expires=' + exp.toGMTString(); } } };function checkLocalStorage() { //确认是否支持Localstorage return window.localStorage && (window.localStorage.setItem('a', 123), window.localStorage.getItem('a') == 123) ? true : false; }function getCookie(name) { let arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); if ((arr = document.cookie.match(reg))) return unescape(arr[2]); else return null; }export default { formatUrl, local };
main.js 引入
import Http from './helper/api/axios.js'; Vue.prototype.Http = Http;
使用
async getData(){ let res = await this.Http.get('url', data); }
作者:会拐弯的蜗牛
链接:https://www.jianshu.com/p/07309e077b28
点击查看更多内容
2人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦