zoukankan      html  css  js  c++  java
  • axios的post传参时,将参数转为form表单格式

    import axios from 'axios';
    import alert from './alert.js';
    import Qs from 'qs'  //引入qs  时axios的自带模块
    
    let env = process.env.NODE_ENV;
    let root = '';
    
    if (env === 'development') {
        console.log("api");
    } else if (env === 'production') {
        console.log("pro");
        root = '';
    } else {
        throw '请检查process.env.NODE_ENV的值,是否符合这些值之一:development,production';
    }
    
    Date.prototype.format = function (fmt) {
        var o = {
            "y+": this.getFullYear(),
            "M+": this.getMonth() + 1, //月份 
            "d+": this.getDate(), //日 
            "H+": this.getHours(), //小时 
            "m+": this.getMinutes(), //分 
            "s+": this.getSeconds() //秒 
        };
        if (!fmt) {
            fmt = 'yyyy-MM-dd HH:mm:ss';
        }
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }
    
    // 自定义判断元素类型JS
    function toType(obj) {
        return ({}).toString.call(obj).match(/s([a-zA-Z]+)/)[1].toLowerCase();
    }
    
    // 参数过滤函数
    function filterNull(o) {
        for (var key in o) {
            if (o[key] === null) {
                delete o[key];
            }
            if (toType(o[key]) === 'string') {
                o[key] = o[key].trim();
            } else if (toType(o[key]) === 'date') {
                o[key] = (o[key].format());
            } else if (toType(o[key]) === 'object') {
                o[key] = filterNull(o[key]);
            } else if (toType(o[key]) === 'array') {
                o[key] = filterNull(o[key]);
            }
        }
        return o;
    }
    
    function apiAxios(method, url, params, success, failure, authFail) {
        console.log('url:' + url);
        if (params) {
            params = filterNull(params);
        }
    
        var base = "";
        if (url.indexOf(".html") != -1) {
            base = "";
        } else {
            base = root;
        }
    
        axios({
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' 
            },
            transformRequest: [function(data) {//在请求之前对data传参进行格式转换
                data = Qs.stringify(data)
                return data
            }],
            method: method,
            url: url,
            data: method === 'POST' || method === 'PUT' || method === 'DELETE' ? params : null,
            params: method === 'GET' ? params : null,
            baseURL: base,
            withCredentials: true
        }).then(function (res) {
            if (res.status >= 200 && res.status <= 210) {
                if (success) {
                    success(res);
                }
            } else {
                //不走
                // window.alert('error: ' + JSON.stringify(res.data));
            }
        }).catch(function (err) {
            let res = err.response;
            if (err && res) {
                console.log(res.status);
                if (res.status == 504) {
                    alert.eduToast("服务器连接失败!请检查您的网络或服务器!!",2000);
                    return;
                } else if (res.status == 401) {
                    console.log('------------------:status'+res.status);
                    console.log('------------------:authFail'+authFail);
                }
                if (failure) {
                    failure(res);
                } else {
                    alert.eduToast(res.data,2000);
                }
            } else {
                if(authFail){
                    // localStorage.setItem('login', '');
                }else{
                    console.log(err);
                }
            }
        });
    }
    
    // 返回在vue模板中的调用接口
    export default {
        get: function (url, params, success, failure,authFail) {
            return apiAxios('GET', url, params, success, failure,authFail);
        },
        post: function (url, params, success, failure) {
            return apiAxios('POST', url, params, success, failure);
        },
        put: function (url, params, success, failure) {
            return apiAxios('PUT', url, params, success, failure);
        },
        delete: function (url, params, success, failure) {
            return apiAxios('DELETE', url, params, success, failure);
        },
        initHeader: function () {
            console.log('------------------:initHeader');
        }
    };

    若传json格式,不用加header,和transformRequest   在合适地方将对象用JSON.stringfiy(),转化即可

  • 相关阅读:
    Atitit 引流矩阵与矩阵引流 推广方法 attilax总结
    Atitit 怎么阅读一本书 消化 分析 检索 attilax总结 1. 读书的本质 是数据的处理,大量的数据,处理能力有限的大脑 2 2. ETL数据清洗转换 摘要,缩小数据规模 2 2.1
    Atitit 为什么要读书,读书的好处是什么 attilax总结
    Atititi. naming spec 联系人命名与remark备注指南规范v5 r99.docx
    Atitit 安全规范 指南 常见五种意外防止规范 attilax总结
    数据安全 密码学原理与概论
    Atitit 理财之道分期与利率的比较列表 attilax总结
    Atitit 完整知识体系表 attilax总结 要读哪些书
    Atitit 为什么互联网机会这么大
    Atitit 建立新组织集团模型的框架基本制度与一些原则
  • 原文地址:https://www.cnblogs.com/fqh123/p/10846168.html
Copyright © 2011-2022 走看看