axios --- request 封装
/** * 网络请求(PC标准)/ 缓存公共方法 **/ import axios from 'axios'; import qs from 'qs'; import Vue from 'vue' import { delCookie, getCookie, setCookie, sessionRemoveItem } from "./index.js"; import { Message, Loading } from 'element-ui'; import { concatLimit } from 'async'; //设置超时时间 axios.defaults.timeout = 40000; //设置全局的请求次数,请求的间隙 axios.defaults.retry = 4; axios.defaults.retryDelay = 1000; axios.defaults.baseURL = process.env.VUE_APP_BASEURL; window.loginURL = process.env.VUE_APP_LOGINURL; window.baseURL = process.env.VUE_APP_BASEURL;
const currContentType = { urlencoded: "application/x-www-form-urlencoded;charset=utf-8", fromData: "ipart/form-data;charset=utf-8", json: "application/json;charset=utf-8", xml: "text/xml;charset=utf-8", form: "multipart/form-data;charset=utf-8" }; Vue.prototype.loadingCount = 0; const MyPlugin = { install: function(Vue, options) { Vue.prototype.nowloading = function() { const thisloading = this.$loading({ target: document.body }) return thisloading; }; Vue.prototype.$axios = axios; //post请求 /*flag是一个对象,back:true代表请求返回值不经过公共方法处理,可全部返回页面。 noloading:true:不展示加载中效果*/ Vue.prototype.$post = function(url, data = {}, config = { contentType: '', noLoading: false }, flag) { let that = this; data.token = getCookie('apToken');if (config.contentType) { config.contentType = currContentType[config.contentType] }; return new Promise((resolve, reject) => { axios.post(url, data, config).then(result => { that.handelResponse(result.data, resolve, flag); }).catch(error => { reject(error) }) }) }; //get请求 Vue.prototype.$get = function(url, params, config = { noLoading: false }, flag) { let that = this; return new Promise((resolve, reject) => { axios.get(url, { params: params, noLoading: config.noLoading }).then(response => { that.handelResponse(response.data, resolve, flag); }).catch(err => { reject(err) }) }) }; // put 请求 Vue.prototype.$put = function(url, params = {}, config = { noLoading: false }, flag) { let that = this; if (config.contentType) { config.contentType = currContentType[config.contentType] }; return new Promise((resolve, reject) => { axios.put(url, params, config).then(response => { that.handelResponse(response.data, resolve, flag); }).catch(err => { // this.$message.error("网络链接中断,请稍后重试!!!"); reject(err) }) }) }, //下载文件 Vue.prototype.$downloadFile = function(url,method, params, flag) { let that = this; return new Promise((resolve, reject) => {
this.$axios({
url:url,
data: params,
method:method,
contentType: "application/json;charset=utf-8", // post 且参数较多 后台接收参数为json 格式时可用此属性
responseType: 'blob' }, ).then(response => { resolve(response); }).catch(err => { reject(err) }) }) }; // 处理返回数据 handle 为true 不显示错误弹框 Vue.prototype.handelResponse = function(res, resolve, handle) { resolve(res) if (res.code == '200' || res.code == '2000' || res.code == '2026' || res.code == '2029' || res.code == '403' || res.code == '2030' || res.code == '2022') { } else { if (!handle) { if (res.msg) { Message.error(res.msg) } else { Message.error('网络链接中断,请稍后重试!!!') } } } }; //local Vue.prototype.localStorageSetItem = function(name, data) { window.localStorage.setItem(name, data) }; /** 获取缓存 **/ Vue.prototype.localStorageGetItem = function(data) { return window.localStorage.getItem(data); }; /** 删除缓存 **/ Vue.prototype.localStorageRemoveItem = function(data) { window.localStorage.removeItem(data) }; //local Vue.prototype.sessionSetItem = function(name, data) { window.localStorage.setItem(name, data) }; /** 获取缓存 **/ Vue.prototype.sessionGetItem = function(data) { return window.localStorage.getItem(data); }; /** 删除缓存 **/ Vue.prototype.sessionRemoveItem = function(data) { window.localStorage.removeItem(data) }; //获取当前domain Vue.prototype.getDomain = function() { var domain = document.domain; // if(domain != '127.0.0.1' && domain != 'localhost'){ if (domain != '127.0.0.1' && domain != 'localhost') { var dIndex = domain.indexOf("."); domain = domain.substring(dIndex, domain.length); } // console.log(domain); return domain; }; /** 设置cookie **/ Vue.prototype.setCookie = function(c_name, value, expiredays) { var exp = new Date(); exp.setTime(exp.getTime() + 30 * 24 * 60 * 60 * 1000 * 100000); document.cookie = c_name + "=" + value + ";path=/;expires=" + exp.toGMTString() + ';domain=' + this.getDomain(); }; /** 设置cookie 24小时 **/ Vue.prototype.setCookieDay = function(c_name, value, expiredays) { var exp = new Date(); exp.setTime(exp.getTime() + 24 * 60 * 60 * 1000 * 100000); document.cookie = c_name + "=" + value + ";path=/;expires=" + exp.toGMTString() + ';domain=' + this.getDomain(); } /** 获取cookie **/ Vue.prototype.getCookie = function(c_name) { if (document.cookie.length > 0) { let c_start, c_end; let l = document.cookie.split(';') for (let i = l.length - 1; i >= 0; i--) { if (l[i].split('=')[0] == c_name || l[i].split('=')[0] == (' ' + c_name) && l[i].split('=')[1] != '') { c_start = l[i].split('=')[1] return unescape(c_start) } } } return "" }; } } export default MyPlugin //http request 请求拦截器(请求拦截器不做过多操作) axios.interceptors.request.use( config => { //qs 系列化参数 if (!config.noLoading) { Vue.prototype.loadingCount++; Vue.prototype.nowloading(); } else if (Vue.prototype.loadingCount != 0) { Vue.prototype.loadingCount++; } if (config.contentType == 'application/json;charset=utf-8') { config.data = JSON.stringify(config.data) } else if (config.contentType == 'multipart/form-data;charset=utf-8') { config.data.append('token', getCookie('apToken')) } else { config.data = qs.stringify(config.data); } if (config.contentType) { config.headers['Content-Type'] = config.contentType; } //增加header参数(用户中心网关拦截) if (config.url.indexOf('openapi') > -1 || config.url.indexOf('http') == -1) { config.headers['btoken'] = getCookie('token'); }; return config; }, error => { return Promise.reject(error); } ); //添加响应之后拦截器 axios.interceptors.response.use(function(response) { if (Vue.prototype.loadingCount > 0) { Vue.prototype.loadingCount--; Vue.prototype.loadingCount == 0 && Vue.prototype.nowloading().close(); } else { Vue.prototype.loadingCount = 0; } //todo //对响应数据做些事 return response; }, function(error) { if (Vue.prototype.loadingCount > 0) { Vue.prototype.loadingCount = 0; Vue.prototype.nowloading().close(); } //请求错误时做些事 if (error.response && error.response.status == 401) { Message.error("登录信息无效,请重新登录!!!"); setCookie('apToken', '') sessionRemoveItem('systemPower') window.location.href = window.location.href.split('#')[0] + '#/login?backurl=' + encodeURIComponent(window.location.href) return; } return Promise.reject(error); });
标签:
axios
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本