阅读 115

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);
});

 

原文:https://www.cnblogs.com/zhu-xl/p/14898423.html

文章分类
代码人生
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐