petite_ming_mock.js

ming_mock的实现的过于庞杂,实际项目中大多数代码都是用不到的,因此需要根据需要对ming_mock做适当的删减或补充

极简版

(function (window) {
    var M = {};
    var App = {
        _get: {},
        _begin: function () {
        },
        begin(callback) {
            App._begin = callback;
        },
        get (methodName, callback) {
            //在M.IO上注册一个方法
            M.IO.reg(methodName.replace("/", ""));
            App._get[methodName] = callback;
        },
        async doget(methodName,params,callback) {
            const req = {};
            const res = {};
            req.url = methodName;
            req.params = params;
            await App._begin(req, res);
            res.send = function (d) {
                callback(d);
            }.bind(this);
            App._get[methodName](req, res);
        }
    };
    //服务方法注册
    M.IO = {};
    M.IO.reg = function (methedName) {
        M.IO[methedName] = (param) => {
            return new Promise(
                function (reslove) {
                    App.doget("/" + methedName,param,(d)=>{
                        reslove(d);
                    })
                }
            )
        }
    };
    window.M = M;
    window.MIO = M.IO;
    window.app = App;
})(window);

精简版实用版

/**
 * File : M_mock.js
 * By : Minglie
 * QQ: 934031452
 * Date :2021.12.05
 * version :2.5.0
 */
(function (window, undefined) {

    const M = {};

    /**
     * 接口返回错误
     */
    M.requestFailHandel=async (url,Resdata)=>{

        return
    }

    
    M.cache_req_data_enable=false;
    //全局状态
    M._global_state = {}

    //全局缓存map
    M._globle_cacheMap = {}
    //全局对象缓存
    M._globle_lib_cacheMap={}
    //全局插件地址缓存
    M._globle_plugin_url_cacheMap={};
    //全局插件
    M._globle_plugin=new Set();

    M.getGloblePlugin=(pluginKey)=>{
        let plugin=null;
        M._globle_plugin.forEach(u=>{
            if(u.key==pluginKey){
                plugin=u;
            }
        })
        return plugin;
    }

    const App = {
        _get: {},
        _begin: function () {
        },
        _end: function () {
        },
        begin(callback) {
            App._begin = callback;
        },
        end(callback) {
            App._end = callback;
        },
        use(url,callback){
            if(typeof url === 'function' || typeof url === 'object'  ){
                let plugin=url;
                let args=callback;
                if(plugin.installed){
                    return App;
                }
                if (typeof plugin === 'function') {
                    plugin(App, args);
                } else {
                    plugin.install(App, args);
                }
                plugin.installed = true;
                M._globle_plugin.add(plugin);
            }
            return App;
        },
        async installPlugin(pluginUrl,constructorParams,pluginParams){
            if(M._globle_plugin_url_cacheMap[pluginUrl]){
                return
            }
            M._globle_plugin_url_cacheMap[pluginUrl]=pluginUrl;
            return  new Promise(resolve => {
                import(pluginUrl).then(async modul=>{
                    const Plugin= modul.default;
                    const plugin= new Plugin(constructorParams);
                    App.use(plugin,pluginParams)
                    resolve(plugin);
                })

            })
        },

        /**
         * 注册get方法
         */
        get(methodName, callback) {
            M.IO.reg(methodName.replace("/", ""));
            App._get[methodName] = callback;
        },
        async doget(methodName,params,callback) {
            const req = {};
            const res = {};
            req.url = methodName;
            req.params = params;
            await App._begin(req, res);
            res.send = function (d) {
                callback(d);
            }.bind(this);
            App._get[methodName](req, res);
        }
    };


    /**
     * ----------------------其他工具函数START--------------------------------------------
     */
    M.sleep = function (numberMillis) {
        let now = new Date();
        let exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime) {
                return;
            }
        }
    };

    M.delayMs=async function (ms){
        return new Promise(r=>{
            setTimeout(()=>{
                r(1)
            },ms)
        })
    }


    M.randomStr = function () {
        return (Math.random().toString(36) + new Date().getTime()).slice(2);
    };

    M.urlStringify = function (obj) {
        if (obj !== null && typeof obj === 'object') {
            let keys = Object.keys(obj);
            let len = keys.length;
            let flast = len - 1;
            let fields = '';
            for (let i = 0; i < len; ++i) {
                let k = keys[i];
                let v = obj[k];
                let ks = k + "=";
                fields += ks + v;
                if (i < flast) {
                    fields += "&";
                }
            }
            return fields;
        }
        return '';
    };

    M.urlParse = function (url) {
        url = url.substr(url.indexOf("?") + 1);
        let t, n, r, i = url, s = {};
        t = i.split("&"),
            r = null,
            n = null;
        for (let o in t) {
            let u = t[o].indexOf("=");
            u !== -1 && (r = t[o].substr(0, u),
                n = t[o].substr(u + 1),
                s[r] = n);
        }
        return s
    };

    /**
     * 去掉参数加让斜杠
     */
    M.formatUrl = function (url) {
        if (url.indexOf("?") > 0) {
            url = url.substr(0, url.indexOf("?"));
        } else {
            url = url;
        }
        if (!url.endsWith('/')) {
            url = url + '/';
        }
        if (!url.startsWith('/')) {
            url = '/' + url;
        }
        return url;
    };


    M.encodeURIComponentObj = function (data) {
        let ret = '';
        for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
        }
        return ret
    };



    M.fileDownload = function (content, filename) {
        let eleLink = document.createElement('a');
        eleLink.download = filename;
        eleLink.style.display = 'none';
        let blob = new Blob([content]);
        eleLink.href = URL.createObjectURL(blob);
        document.body.appendChild(eleLink);
        eleLink.click();
        document.body.removeChild(eleLink);
    };

    //获取地址栏数据
    M.getParameter = function (name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = window.location.href.substr(window.location.href.indexOf('?')).substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };


    //服务方法注册
    M.IO = {};
    M.IO.reg = function (methed, type) {
        M.IO[methed] = (param) => {
            return new Promise(
                function (reslove) {
                    App.doget("/" + methed,param,(d)=>{
                        reslove(d);
                    })
                }
            )
        }
    };


    M.SetStateSession = (state) => {
        sessionStorage.setItem('state',JSON.stringify(state));
    }

    M.GetStateSession = () => {
        return JSON.parse(sessionStorage.getItem('state'));
    }

    M.RemoveStateSession = () => {
        sessionStorage.removeItem('state');
    }

    M.init = function () {
        Date.prototype.format = function (fmt) {
            let o = {
                "M+": this.getMonth() + 1,                 //月份
                "d+": this.getDate(),                    //日
                "h+": this.getHours(),                   //小时
                "m+": this.getMinutes(),                 //分
                "s+": this.getSeconds(),                 //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds()             //毫秒
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (let 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;
        }
    };

    M.urlToPath = function (url) {
        return url.replace(/^http(s?):\/\/[^/]+/, "");
    };

    M.beforeSend = function (options) {

        return true;
    };
    M.endResponse = function (data, xhr) {
        return data;
    };


    const translateApi=(api)=>{
        let url=M.config?M.config.baseUrl(api):api ;
        if(!api.startsWith("http")){
            api=url
        }
        return api;
    }

    const request= async function ({methed,api,params,headers}){
        api=translateApi(api)
        headers=Object.assign({'Content-Type': 'application/json'},headers);
        if(window.M.config.token){
            headers.token=window.M.config.token;
        }
        return new Promise((reslove, reject) => {
            fetch(api, {
                method: methed,
                mode: 'cors',
                headers: headers,
                body: JSON.stringify(params)
            }).then(function (response) {
                return response.json();
            }).then((res) => {
                M.requestFailHandel(api,res);
                reslove(res);
            }).catch((err) => {
                console.error(err);
                reject(err);
            });
        })
    }

    const post  = async (api, params = {},headers) => request({methed:"POST",api,params,headers})
    const del  = async (api, params = {},headers) => request({methed:"DELETE",api,params,headers})
    const put  = async (api, params = {},headers) => request({methed:"PUT",api,params,headers})
    const get = async (api, params = {},headers) => {
        api=translateApi(api)
        let getData = "";
        if (params) {
            getData = window.M.urlStringify(params);
            if (api.indexOf("?") > 0) {
                getData = "&" + getData;
            } else {
                getData = "?" + getData;
            }
        }
        api = api + getData;
        headers=Object.assign({'Content-Type': 'application/json'},headers);
        if(window.M.config.token){
            headers.token=window.M.config.token;
        }
        return new Promise((reslove, reject) => {
            fetch(api, {
                method: 'GET',
                mode: 'cors',
                headers: headers
            }).then(function (response) {
                return response.json();
            }).then((res) => {
                M.requestFailHandel(api,res);
                reslove(res)
            }).catch((err) => {
                console.error(err);
                reject(err)
            });
        })
    };
    const jsonp=async (url, callbackFunction)=>{
        return new Promise(resolve => {
            let callbackStr = M.urlParse(url).callback;
            window[callbackStr]=(...params)=>{
                if(callbackFunction) {
                    callbackFunction(params);
                }
                document.body.removeChild(document.getElementById("ming_mock_jsonp_id"))
                resolve(params);
            }
            var scriptElement = document.createElement('script');
            scriptElement.src = url;
            scriptElement.id="ming_mock_jsonp_id"
            document.body.appendChild(scriptElement);
        })
    };

    M.init();
    window.app = App;
    window.M = M;
    window.MIO = M.IO;
    window.M.request={}
    window.M.request.get=get;
    window.M.request.post=post;
    window.M.request.delete=del;
    window.M.request.put=put;
    window.M.request.jsonp=jsonp;
    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = { app: App, M, MIO: M.IO }
    }

})(window);

H5移动端

简单,可加入些工具函数

(function (window) {
    var M = {};
    var App = {
        _get: {},
        get (methodName, callback) {
            //在M.IO上注册一个方法
            M.IO.reg(methodName.replace("/", ""));
            App._get[methodName] = callback;
        },
        doget(methodName,params,callback) {
            req = {};
            res = {};
            req.params = params;
            res.send = function (d) {
                callback(d);
            }.bind(this);
            App._get[methodName](req, res);
        }
    };
    //服务方法注册
    M.IO = {};
    M.IO.reg = function (methedName) {
        M.IO[methedName] = (param) => {
            return new Promise(
                function (reslove) {
                    App.doget("/" + methedName,param,(d)=>{
                        reslove(d);
                    })
                }
            )
        }
    };
    M.get = function (url, param) {
        let u;
        App.doget(url,param,(d)=>{
            u = d;
        });
        return u;
    };

    M.init = function () {
        //格式化日期
        Date.prototype.format = function (fmt) {
            var o = {
                "M+": this.getMonth() + 1,                 //月份
                "d+": this.getDate(),                    //日
                "h+": this.getHours(),                   //小时
                "m+": this.getMinutes(),                 //分
                "s+": this.getSeconds(),                 //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds()             //毫秒
            };
            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;
        }
    };

    M.getUserInfo=function (){
        if(localStorage.getItem('userInfo')==null){
            return {}
        }
        return JSON.parse(localStorage.getItem('userInfo'))
    }

    M.setUserInfo=async function (userInfoObj){
         localStorage.setItem("userInfo", JSON.stringify(userInfoObj));
         let r=  M.getUserInfo();
         return r;
    }

    M.getParameter = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.href.substr(window.location.href.indexOf('?')).substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };
    const get = async (api, params = {},headers) => {
        console.log("gggggggggggggggg")
        api=M.config.oncegame_host+api;
        return new Promise((reslove, reject) => {
            $.ajax({
                type:"GET",
                url:api,
                dataType:"json",
                data:params,
                beforeSend: function(xhr) {

                },
                headers: headers|| {'Content-Type':'application/json;charset=utf8'},
                success:function(data){
                    reslove(data)
                },
                error: function(err){
                    reject(err)
                }
            });
        });
    };
    const post  = async (api, params = {},headers) => {
        console.log("pppppppppppppppppp")
        api=M.config.oncegame_host+api;
        return new Promise((reslove, reject) => {
            $.ajax({
                type:"POST",
                url:api,
                dataType:"json",
                data:JSON.stringify(params),
                beforeSend: function(xhr) {

                },
                headers:  headers||{'Content-Type':'application/json;charset=utf8'},
                success:function(data){
                    reslove(data)
                },
                error: function(err){
                    reject(err)
                }
            });
        });
    }


    M.throttle  = function(func, wait, options) {
        /* options的默认值
         *  表示首次调用返回值方法时,会马上调用func;否则仅会记录当前时刻,当第二次调用的时间间隔超过wait时,才调用func。
         *  options.leading = true;
         * 表示当调用方法时,未到达wait指定的时间间隔,则启动计时器延迟调用func函数,若后续在既未达到wait指定的时间间隔和func函数又未被调用的情况下调用返回值方法,则被调用请求将被丢弃。
         *  options.trailing = true;
         * 注意:当options.trailing = false时,效果与上面的简单实现效果相同
         */
        var context, args, result;
        var timeout = null;
        var previous = 0;
        if (!options) options = {};
        var later = function() {
            previous = options.leading === false ? 0 : new Date().getTime();
            timeout = null;
            result = func.apply(context, args);
            if (!timeout) context = args = null;
        };
        return function() {
            var now = new Date().getTime();
            if (!previous && options.leading === false) previous = now;
            // 计算剩余时间
            var remaining = wait - (now - previous);
            //console.log("wait",wait,"now",now,"previous",previous)
            //console.log("AAA",remaining)
            context = this;
            args = arguments;
            // 当到达wait指定的时间间隔,则调用func函数
            // 精彩之处:按理来说remaining <= 0已经足够证明已经到达wait的时间间隔,但这里还考虑到假如客户端修改了系统时间则马上执行func函数。
            if (remaining <= 0 || remaining > wait) {
                // 由于setTimeout存在最小时间精度问题,因此会存在到达wait的时间间隔,但之前设置的setTimeout操作还没被执行,因此为保险起见,这里先清理setTimeout操作
                if (timeout) {
                    clearTimeout(timeout);
                    timeout = null;
                }
                previous = now;
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            } else if (!timeout && options.trailing !== false) {
                // options.trailing=true时,延时执行func函数
                timeout = setTimeout(later, remaining);
            }
            return result;
        };
    };



    M.debounce =function(fn, wait, immediate) {
        immediate = immediate || false;
        var timer = null;
        var count = 0;
        return function () {
            var _this = this;
            var _arg = arguments;
            clearTimeout(timer);
            if (immediate && !count) {
                fn.apply(_this, _arg);
                count++;
            } else {
                timer = setTimeout(function () {
                    console.log(this);
                    fn.apply(_this, _arg);
                    count++;
                }, wait);
            }


        }

    }



    window.M = M;
    window.MIO = M.IO;
//将ajax请求挂到全局对象M上
    M.init();
    window.M.request={}
    window.M.request.get=get;
    window.M.request.post=post;
    window.app = App;
})(window);

H5 vue

(function (window) {
    const M = {};

    /**
     * 加载html文件 start
     */
    M._loadHtmlCache={};
    M._loadCssCache={};
    M.loadHtml= async function (htmlUrl){
        if(M._loadHtmlCache[htmlUrl]){
            return M._loadHtmlCache[htmlUrl];
        }
        return new Promise((resolve,reject)=>{
            fetch(htmlUrl).then(d=>d.text()).then(d=>{
                M._loadHtmlCache[htmlUrl]=d;
                resolve(d)
            })
        })
    }
    M.loadCss= async function (cssUrl){
        let cssContent=""
        if(M._loadCssCache[cssUrl]){
            cssContent= M._loadCssCache[cssUrl];
        }else {
            cssContent= await new Promise((resolve,reject)=>{
                fetch(cssUrl).then(d=>d.text()).then(d=>{
                    M._loadCssCache[cssUrl]=d;
                    resolve(d)
                })
            })
        }
        document.querySelector("#pageCss").innerHTML=cssContent;
    }

    M.setPageCss=function (cssContent){
        document.querySelector("#pageCss").innerHTML=cssContent;
    }

    M.html =function (htmlUrl){
        let r=  M._loadHtmlCache[htmlUrl]||"<h1>wait...</h1>";
        return r;
    }
    /**
     * 加载html文件 end
     */

    window.importStyle=(id,url)=>{
        let styleCss= document.querySelector("#"+id);
        if(styleCss==null){
            var head = document.getElementsByTagName('HEAD').item(0);
            var style  = document.createElement("link");
            style.id=id;
            style.rel  = "stylesheet";
            style.href = url;
            head.appendChild(style);
        }
    }


    window.Page=async (pageObj)=>{
        let pageName= pageObj.name;
        let htmlUrl=`./views/${pageName}/${pageName}.html`;
        let cssUrl=`./views/${pageName}/${pageName}.css`;
        if(!pageObj.template){
            await M.loadHtml(htmlUrl)
        }
        return {
            ...pageObj,
            template: pageObj.template || M.html(htmlUrl),
            beforeCreate: pageObj.beforeCreate|| (async ()=>await M.loadCss(cssUrl))
        }
    }

    M.isPc=(()=>{
        var sUserAgent = navigator.userAgent.toLowerCase();
        if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(sUserAgent)) {
           return false;
        }
        return true;
    })()


    var App = {
        _get: {},
        get (methodName, callback) {
            //在M.IO上注册一个方法
            M.IO.reg(methodName.replace("/", ""));
            App._get[methodName] = callback;
        },
        _begin: function () {
        },
        _end: function () {
        },

        begin(callback) {
            App._begin = callback;
        },
        end(callback) {
            App._end = callback;
        },
        async doget(methodName,params,callback) {
            const req = {};
            const res = {};
            req.params = params||{};
            req.url = methodName;
            res.send = function (d) {
                res.alreadySend = true;
                callback(d);
                App._end(req, d);
            }.bind(this);
            await App._begin(req, res);
            if (!res.alreadySend) await App._get[methodName](req, res);
        }
    };
    //服务方法注册
    M.IO = {};
    M.IO.reg = function (methedName) {
        M.IO[methedName] = (param) => {
            return new Promise(
                function (reslove) {
                    App.doget("/" + methedName,param,(d)=>{
                        reslove(d);
                    })
                }
            )
        }
    };
    M.get = function (url, param) {
        let u;
        App.doget(url,param,(d)=>{
            u = d;
        });
        return u;
    };



    M.init = function () {
        //格式化日期
        Date.prototype.format = function (fmt) {
            var o = {
                "M+": this.getMonth() + 1,                 //月份
                "d+": this.getDate(),                    //日
                "h+": this.getHours(),                   //小时
                "m+": this.getMinutes(),                 //分
                "s+": this.getSeconds(),                 //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds()             //毫秒
            };
            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;
        }
    };


    M.removeUserInfo=function (){
        localStorage.removeItem("userInfo");
    }
    M.getUserInfo=function (){
        if(localStorage.getItem('userInfo')==null){
            return null
        }
        return JSON.parse(localStorage.getItem('userInfo'))
    }

    M.setUserInfo=async function (userInfoObj){
         localStorage.setItem("userInfo", JSON.stringify(userInfoObj));
         let r=  M.getUserInfo();
         return r;
    }

    M.getParameter = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.href.substr(window.location.href.indexOf('?')).substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    M.urlStringify = function (obj) {
        if (obj !== null && typeof obj === 'object') {
            var keys = Object.keys(obj);
            var len = keys.length;
            var flast = len - 1;
            var fields = '';
            for (var i = 0; i < len; ++i) {
                var k = keys[i];
                var v = obj[k];
                var ks = k + "=";
                fields += ks + v;
                if (i < flast) {
                    fields += "&";
                }
            }
            return fields;
        }
        return '';
    };

    const translateApi=(api)=>{
        let url=M.config.baseUrl(api) ;
        if(!api.startsWith("http")){
            api=url
        }
        return api;
    }

    const post  = async (api, params = {},headers) => {
        api=translateApi(api)
        return new Promise((reslove, reject) => {
            fetch(api, {
                method: 'POST',
                mode: 'cors',
                headers: headers||{
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            }).then(function (response) {
                return response.json();
            }).then((res) => {
                reslove(res)
            }).catch((err) => {
                reject(err)
            });
        })
    }

    const get = async (api, params = {},headers) => {
        api=translateApi(api)
        let getData = "";
        if (params) {
            getData = window.M.urlStringify(params);
            if (api.indexOf("?") > 0) {
                getData = "&" + getData;
            } else {
                getData = "?" + getData;
            }
        }
        api = api + getData;
        return new Promise((reslove, reject) => {
            fetch(api, {
                method: 'GET',
                mode: 'cors',
                headers: headers||{
                    'Content-Type': 'application/json'
                }
            }).then(function (response) {
                return response.json();
            }).then((res) => {
                reslove(res)
            }).catch((err) => {
                reject(err)
            });
        })
    };
    window.M = M;
    window.MIO = M.IO;
//将ajax请求挂到全局对象M上
    M.init();
    window.M.request={}
    window.M.request.get=get;
    window.M.request.post=post;
    window.app = App;
})(window);

小程序端

const config={
		appletName:"",
    DOMAIN:""
}



function request({url, data = {}, method = 'GET',header}) {
  return new Promise((resolve,reject) => {
    wx.request({
      url:  url,
      method: method,
      data: data,
      header: header,
      success: function(res) {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res.errMsg)
        }
      },
      fail: function(err) {
        reject(err)
      }
    })
  })
}

const get = async (api, params = {}, headers) => {
  const app= getApp();
  let defaultHead={
    'Content-Type':'application/json',
    appletName: config.appletName,
    unionId: app.globalData.unionId,
    openId: app.globalData.openId
  }
  headers=Object.assign(defaultHead,headers)
  let url=config.DOMAIN + api;
  if(api.startsWith("http")){
    url=api;
 }
  const res = await request({
    url: url,
    data: params,
    header: headers ,
    method: "GET"
  });
  return res;
};

const post = async (api, params = {}, headers) => {
  let defaultHead={
    'Content-Type':'application/json',
    appletName: config.appletName,
    unionId: app.globalData.unionId,
    openId: app.globalData.openId
  }
  headers=Object.assign(defaultHead,headers)
  let url=config.DOMAIN + api;
  if(api.startsWith("http")){
    url=api;
 }
  const res = await request({
    url: url,
    data: params,
    header: headers || {},
    method: "POST"
  });
  return res;
};



const mApp = {
  _get: {},
  _begin: function () {
  },
  _end: function () {
  },

  begin(callback) {
    mApp._begin = callback;
  },  
  end(callback) {
    mApp._end = callback;
  },
  get (methodName, callback) {
      //在M.IO上注册一个方法
      M.IO.reg(methodName.replace("/", ""));
      mApp._get[methodName] = callback;
  },
  async doget(methodName,params,callback) {
      const req = {};
      const res = {};
      req.params = params||{};
      req.url = methodName;
      res.send = function (d) {
          res.alreadySend = true;
          callback(d);
          mApp._end(req, d);
      }.bind(this);
      await mApp._begin(req, res);
      if (!res.alreadySend) await mApp._get[methodName](req, res);
  }
};

const M={
  config:config,
  app:mApp,
  IO:{
    reg: function (methedName) {
         M.IO[methedName] = (param) => {
          return new Promise(
              function (reslove) {
                 mApp.doget("/" + methedName,param,(d)=>{
                      reslove(d);
                  })
              }
          )
      }
    }
  },
  request:{
    get,
    post
  }
}

export default M;




uniapp微信端

    const M = {};

	M.config={};
	
    M.app = {
        _get: {},
        _begin: function () {
        },
        begin(callback) {
            M.app._begin = callback;
        },
        get (methodName, callback) {
            M.IO.reg(methodName.replace("/", ""));
            M.app._get[methodName] = callback;
        },
        async doget(methodName,params,callback) {
            const req = {};
            const res = {};
            req.url = methodName;
            req.params = params;
            await M.app._begin(req, res);
            res.send = function (d) {
                callback(d);
            }.bind(this);
            M.app._get[methodName](req, res);
        }
    };
    //服务方法注册
    M.IO = {};
    M.IO.reg = function (methedName) {
        M.IO[methedName] = (param) => {
            return new Promise(
                function (reslove) {
                    M.app.doget("/" + methedName,param,(d)=>{
                        reslove(d);
                    })
                }
            )
        }
    };

const translateApi=(api)=>{
	let url=M.config.baseUrl(api) ;
	if(!api.startsWith("http")){
		api=url
	}
	return api;
}

let request = (params) => {
  uni.showLoading({
    title: '加载中',
  });

  return new Promise((reslove, reject) => {
    uni.request({
      ...params,
      success(res) {
        reslove(res.data);
      },
      fail(err) {
        reject(err);
      },
      complete() {
        uni.hideLoading();
      },
    });
  });
};


const get = async (api, params = {}, headers) => {
 api=translateApi(api)
  const res = await request({
    url: api,
    data: params,
    header: headers || {},
    method: "GET"
  });
  return res;
};

const post = async (api, params = {}, headers) => {
  api=translateApi(api)
  const res = request({
    url: api,
    data: params,
    header: headers || {},
    method: "POST"
  });
  return res;
};

//将ajax请求挂到全局对象M上
M.request = {}
M.request.get = get;
M.request.post = post;
// #ifdef H5
window.App={};
// #endif

App.M=M;
export default M;
	

config.js

const env="dev";


const devConfig={

}

const preConfig={
	
	

}
const prodConfig={



}

const commonConFig={
    baseUrl:(url)=>url,
    baseImgUrl:(url)=>"https://ming-bucket-01.oss-cn-beijing.aliyuncs.com/space/root/project/ruyunsuixing/img"+url,
}
let envConfig;
if(env=="dev"){
    envConfig=devConfig;
}else if(env=="pre"){
    envConfig=preConfig;
}else if(env=="prod"){
    envConfig=prodConfig;
}


App.M.config=Object.assign(commonConFig,envConfig);

controller.js

const app=  App.M.app;
app.get("/list",async (req,res)=>{
	let r= await App.M.request.get("https://autumnfish.cn/search?keywords=%E6%98%8E%E5%A4%A92")
	res.send(r)
})

PC端

/**
 * File : M_mock.js
 * By : Minglie
 * QQ: 934031452
 * Date :2021.06.19
 * version :2.0.10
 */
 (function (window, undefined) {

    const M = {};
    M.cache_req_data_enable=false;
    //全局状态
    M._global_state = {}
    //订阅全局状态的组件
    M._global_state_subscribe_component = {}
    //全局组件
    M.Component={}
    M.init_server_enable = true;
    M.host = "";
    M.map_path = "map_path";
    M.database_path = "database_path";

    if (typeof module === "object" && typeof module.exports === "object") {
        try {
            $ = require("jquery");
        } catch (e) {
            delete $;
        }
    }
    if (typeof $ == "undefined") {
        window.$ = {};
        window.$.ajax = function (options) {
            options.beforeSend();
        }
    }

    const App = {
        reqMap: new Map(),
        resMap: new Map(),

        // 缓存ajax方法
        ajax: $.ajax,
        //key为去除rest参数的url,val为原始url
        _rest: {},
        _get: {},
        _use: {},
        _post: {},
        _begin: function () {
        },
        _end: function () {
        },

        begin(callback) {
            App._begin = callback;
        },
        end(callback) {
            App._end = callback;
        },
        use(url,callback){
            if (Array.isArray(url)) {
                url.forEach(u=>{
                    let regExp=new RegExp(u)
                    App._use[u] = {url,regExp,callback};
                })
            } else {
                let regExp=new RegExp(url)
                App._use[url] = {url,regExp,callback};
            }
        },
        /**
         * 注册get方法
         */
        get(url, callback) {
            //非rest请求在M.IO上注册一个方法
            if (!url.includes(":")) {
                M.IO.reg(url.replace("/", ""), "get");
            }
            url = M.formatUrl(url);
            let realUrl = url;
            if (url.indexOf(":") > 0) {
                url = url.substr(0, url.indexOf(":"));
                App._rest[url] = realUrl;
            }
            App._get[url] = callback;
        },
        /**
         * 注册post方法
         */
        post(url, callback) {
            //非rest请求在M.IO上注册一个方法
            if (!url.includes(":")) {
                M.IO.reg(url.replace("/", ""), "post");
            }
            url = M.formatUrl(url);
            let realUrl = url;
            if (url.indexOf(":") > 0) {
                url = url.substr(0, url.indexOf(":"));
                App._rest[url] = realUrl;
            }
            App._post[url] = callback;
        },
        async doUse(req, res) {
            for (let key in App._use){
                if(App._use[key].regExp.test(req.url)){
                    await  App._use[key].callback(req,res);
                    return;
                }
            }
        },
        async doGet(pureUrl, options) {
            let req = {};
            let res = {};
            res.alreadySend = false;
            req.params =options.params;
            req.method = "get";
            req.pureUrl = pureUrl;
            req.url = options.url;
            res.send = function (d) {
                res.alreadySend = true;
                if(M.cache_req_data_enable){
                    this.resMap.set("get:" + pureUrl, d);
                }
                let data = d;
                App._end(req, data);
                options.success(data);
            }.bind(this);
            await App._begin(req, res);
            if (!res.alreadySend) await App.doUse(req, res);
            if (!res.alreadySend) await App._get[pureUrl](req, res);
        },
        async doPost(pureUrl, options) {
            let req = {};
            let res = {};
            res.alreadySend = false;
            req.params =options.params;
            req.method = "post";
            req.pureUrl = pureUrl;
            req.url = options.url;
            res.send = function (d) {
                res.alreadySend = true;
                if(M.cache_req_data_enable){
                    this.resMap.set("post:" + pureUrl, d);
                }
                let data = d;
                App._end(req,data);
                options.success(data);
            }.bind(this);
            await App._begin(req, res);
            if (!res.alreadySend) await App.doUse(req, res);
            if (!res.alreadySend) await App._post[pureUrl](req, res);
        }
    };


    /**
     * ----------------------其他工具函数START--------------------------------------------
     */
    M.sleep = function (numberMillis) {
        let now = new Date();
        let exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime) {
                return;
            }
        }
    };

    /**
     * ----------------------服务器端START--------------------------------------------
     */
    M.get = function (url, param) {
        return new Promise(
            function (reslove) {
                M.ajax({
                    url: url,
                    data: param,
                    type: "get",
                    success: function (data) {
                        reslove(data);
                    }
                });
            }
        )
    };


    M.post = function (url, param) {
        return new Promise(
            function (reslove) {
                M.ajax({
                    url: url,
                    data: param,
                    type: "post",
                    success: function (data) {
                        reslove(data);
                    }
                });
            }
        )
    };


    M.result = function (data, success) {
        let r = {};
        if (success == false) {
            r.code = -2;
            r.msg = "操作失败";
        } else {
            r.code = 200;
            r.msg = "success";
        }
        try {
            let obj = JSON.parse(data);
            if (typeof obj == 'object' && obj) {
                r.data = obj;
            } else {
                r.data = data;
            }
        } catch (e) {
            r.data = data;
        }
        return r;
    };

   


    M.randomStr = function () {
        return (Math.random().toString(36) + new Date().getTime()).slice(2);
    };


    M.urlStringify = function (obj) {
        if (obj !== null && typeof obj === 'object') {
            let keys = Object.keys(obj);
            let len = keys.length;
            let flast = len - 1;
            let fields = '';
            for (let i = 0; i < len; ++i) {
                let k = keys[i];
                let v = obj[k];
                let ks = k + "=";
                fields += ks + v;
                if (i < flast) {
                    fields += "&";
                }
            }
            return fields;
        }
        return '';
    };

    M.urlParse = function (url) {
        url = url.substr(url.indexOf("?") + 1);
        let t, n, r, i = url, s = {};
        t = i.split("&"),
            r = null,
            n = null;
        for (let o in t) {
            let u = t[o].indexOf("=");
            u !== -1 && (r = t[o].substr(0, u),
                n = t[o].substr(u + 1),
                s[r] = n);
        }
        return s
    };

    /**
     * 去掉参数加让斜杠
     */
    M.formatUrl = function (url) {
        if (url.indexOf("?") > 0) {
            url = url.substr(0, url.indexOf("?"));
        } else {
            url = url;
        }
        if (!url.endsWith('/')) {
            url = url + '/';
        }
        if (!url.startsWith('/')) {
            url = '/' + url;
        }
        return url;
    };


    M.encodeURIComponentObj = function (data) {
        let ret = '';
        for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
        }
        return ret
    };

    M.fileDownload = function (content, filename) {
        let eleLink = document.createElement('a');
        eleLink.download = filename;
        eleLink.style.display = 'none';
        let blob = new Blob([content]);
        eleLink.href = URL.createObjectURL(blob);
        document.body.appendChild(eleLink);
        eleLink.click();
        document.body.removeChild(eleLink);
    };


    //获取地址栏数据
    M.getParameter = function (name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = window.location.href.substr(window.location.href.indexOf('?')).substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

 
    /**
     *改写ajax方法
     */
    M.ajax = function (options) {
        let d = M.urlParse(options.url);
        options.data = Object.assign(d, options.data);
        if (true) {
            if (!Object.keys(App._rest).length == 0) {
                let pathname = M.formatUrl(options.url);
                let realPathName = pathname;
                let mapingPath = "";
                for (let i = 0; i < Object.keys(App._rest).length; i++) {
                    if (M.formatUrl(options.url).startsWith(Object.keys(App._rest)[i])) {
                        for (let i = 0; i < Object.keys(App._rest).length; i++) {
                            if (pathname.startsWith(Object.keys(App._rest)[i])) {
                                pathname = Object.keys(App._rest)[i];
                                mapingPath = App._rest[pathname];
                            }
                        }
                        if (!realPathName.endsWith('/')) {
                            realPathName = realPathName + '/';
                        }
                        let s1 = realPathName;
                        let s2 = mapingPath;
                        s1 = s1.substring(s2.indexOf(":") - 1, s1.length - 1).split("/").slice(1);
                        s2 = s2.substring(s2.indexOf(":") - 1, s2.length - 1).split("/:").slice(1);
                        let params = {};
                        for (let i = 0; i < s2.length; i++) { params[s2[i]] = s1[i]; }
                        options.data = Object.assign(params, options.data);
                        options.restUrl = pathname;
                    }
                }
            }
        }
        App.ajax({
            url: options.url,
            beforeSend(XHR) {
                let pureUrl = options.restUrl || M.formatUrl(options.url);
                if(M.cache_req_data_enable){
                    App.reqMap.set(options.type + ":" + pureUrl, options.data);
                }
                options.params=options.data;
                if (options.type == "get") {
                    App.doGet(pureUrl, options);
                } else {
                    App.doPost(pureUrl, options);
                }
                return false;
            },
            success(data) {
                options.success(data);
            }
        })
    };


    //服务方法注册
    M.IO = {};
    M.IO.reg = function (methed, type) {
        M.IO[methed] = (param) => {
            return new Promise(
                function (reslove) {
                    M.ajax({
                        url: "/" + methed,
                        data: param,
                        type: type,
                        success: function (data) {
                            reslove(data);
                        }
                    });
                }
            )
        }
    };


    M.EventSource = function (url, callback) {
        if (window.EventSource) {
            // 创建 EventSource 对象连接服务器
            const source = new EventSource(url);
            // 连接成功后会触发 open 事件
            source.addEventListener('open', () => {
                console.log('Connected');
            }, false);
            // 服务器发送信息到客户端时,如果没有 event 字段,默认会触发 message 事件
            source.addEventListener('message', e => {
                console.log(`data: ${e.data}`);
            }, false);
            // 自定义 EventHandler,在收到 event 字段为 slide 的消息时触发
            source.addEventListener('slide', e => {
                callback(e);
            }, false);
            // 连接异常时会触发 error 事件并自动重连
            source.addEventListener('error', e => {
                if (e.target.readyState === EventSource.CLOSED) {
                    console.log('Disconnected');
                } else if (e.target.readyState === EventSource.CONNECTING) {
                    console.log('ConnectinApp...');
                }
            }, false);
            return source;
        } else {
            console.error('Your browser doesn\'t support SSE');
        }

    };


   

    M.init = function () {
        /***
         * 下划线命名转为驼峰命名
         */
        String.prototype.underlineToHump = function () {
            let re = /_(\w)/g;
            let str = this.replace(re, function ($0, $1) {
                return $1.toUpperCase();
            });
            return str;
        };

        /***
         * 驼峰命名转下划线
         */
        String.prototype.humpToUnderline = function () {
            let re = /_(\w)/g;
            let str = this.replace(/([A-Z])/g, "_$1").toLowerCase();
            return str;
        };

        //首字母变大写
        String.prototype.firstChartoUpper = function () {
            return this.replace(/^([a-z])/g, function (word) {
                return word.replace(word.charAt(0), word.charAt(0).toUpperCase());
            });
        };
        //首字母变小写
        String.prototype.firstChartoLower = function () {
            return this.replace(/^([A-Z])/g, function (word) {
                return word.replace(word.charAt(0), word.charAt(0).toLowerCase());
            });
        };
        //格式化日期
        Date.prototype.format = function (fmt) {
            let o = {
                "M+": this.getMonth() + 1,                 //月份
                "d+": this.getDate(),                    //日
                "h+": this.getHours(),                   //小时
                "m+": this.getMinutes(),                 //分
                "s+": this.getSeconds(),                 //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds()             //毫秒
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (let 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;
        }
    };
   
    M.urlToPath = function (url) {
        return url.replace(/^http(s?):\/\/[^/]+/, "");
    };

    M.beforeSend = function (options) {

        return true;
    };
    M.endResponse = function (data, xhr) {
        return data;
    };


    M.getComponentName=function(componentName){
        let funStr=componentName._reactInternalFiber.type.toString();
        let re = /function\s*(\w*)/i;
        let matches = re.exec(funStr);
        return matches[1];
    }


    /**
     *  ajax 拦截 end
     */
    M.initRedux=function(){
        let handler = {
            get (target, key, receiver) {
                return Reflect.get(target, key, receiver)
            },
            set (target, key, value, receiver) {
                if(M._global_state_subscribe_component[key]){
                    let oldValue=M._global_state[key]
                    let newValue=value
                    if(oldValue){
                        newValue=Object.assign(oldValue,value)
                    }
                    M._global_state_subscribe_component[key].forEach(c=>c.setState(newValue))
                }
                return Reflect.set(target, key, value, receiver)
            }
        }
        M.State = new Proxy(M._global_state , handler);

        M.subReg=function (componentName,componentThis,stateName,initState){
            if(typeof(componentName)!="string"){
                initState=stateName;
                stateName=componentThis;
                componentThis=componentName;
                componentName=M.getComponentName(componentName);
            }
            M.Component[componentName]=componentThis;
            if(stateName){
                if( !M._global_state_subscribe_component[stateName]){
                    let  subscribe_component_set=new Set();
                    //初始状态
                    M._global_state[stateName]=initState;
                    if(componentThis){
                        subscribe_component_set.add(componentThis);
                    }
                    M._global_state_subscribe_component[stateName]=subscribe_component_set;
                }else {
                    let  subscribe_component_set= M._global_state_subscribe_component[stateName]
                    if(componentThis){
                        subscribe_component_set.add(componentThis)
                    }
                }
            }
        }
        //取消订阅注册
        M.unSubReg=function (componentName,stateName){
            //取消注册
            if(stateName && M.Component[componentName]){
                if( M._global_state_subscribe_component[stateName]){
                    let  subscribe_component_set= M._global_state_subscribe_component[stateName]
                    subscribe_component_set.delete(M.Component[componentName])
                }
            }
            if(!componentName && stateName ){
                M._global_state_subscribe_component[stateName]=null
            }
            M.Component[componentName]=null;
        }
    }


    M.init();
    M.initRedux();
    window.app = App;
    window.M = M;
    window.MIO = M.IO;
    //$.ajax = M.ajax;
    if (M.init_server_enable) M.initServer();


    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = { app: App, M, MIO: M.IO }
    }


})(window);

ming_mock_vue.js

浏览器vue3-sfc-loader解析vue文件的demo,缺点是浏览器占用内存会变的很高
https://gitee.com/minglie/ming_pure_browser_vue

(function (window) {
    const M = {};

    /**
     * 加载html文件 start
     */
    M._loadHtmlCache={};
    M._loadCssCache={};
    //全局缓存map
    M._globle_cacheMap = {}
    //全局对象缓存
    M._globle_lib_cacheMap={}
    //全局插件地址缓存
    M._globle_plugin_url_cacheMap={};
    //全局插件
    M._globle_plugin=new Set();

    M.pushRouter=function (){


    }


    M.loadHtml= async function (htmlUrl){
        if(M._loadHtmlCache[htmlUrl]){
            return M._loadHtmlCache[htmlUrl];
        }
        return new Promise((resolve,reject)=>{
            fetch(htmlUrl).then(d=>d.text()).then(d=>{
                M._loadHtmlCache[htmlUrl]=d;
                //alert(d)
                resolve(d)
            })
        })
    }
    M.loadCss= async function (cssUrl){
        let cssContent=""
        if(M._loadCssCache[cssUrl]){
            cssContent= M._loadCssCache[cssUrl];
        }else {
            cssContent= await new Promise((resolve,reject)=>{
                fetch(cssUrl).then(d=>d.text()).then(d=>{
                    M._loadCssCache[cssUrl]=d;
                    resolve(d)
                })
            })
        }
        document.querySelector("#pageCss").innerHTML=cssContent;
    }

    M.setPageCss=function (cssContent){
        document.querySelector("#pageCss").innerHTML=cssContent;
    }

    M.html =function (htmlUrl){
        let r=  M._loadHtmlCache[htmlUrl]||"<h1>wait...</h1>";
        return r;
    }
    /**
     * 加载html文件 end
     */

    M.urlParse = function (url) {
        url = url.substr(url.indexOf("?") + 1);
        let t, n, r, i = url, s = {};
        t = i.split("&"),
            r = null,
            n = null;
        for (let o in t) {
            let u = t[o].indexOf("=");
            u !== -1 && (r = t[o].substr(0, u),
                n = t[o].substr(u + 1),
                s[r] = n);
        }
        return s
    };


    window.importStyle=(id,url)=>{
        let styleCss= document.querySelector("#"+id);
        if(styleCss==null){
            var head = document.getElementsByTagName('HEAD').item(0);
            var style  = document.createElement("link");
            style.id=id;
            style.rel  = "stylesheet";
            style.href = url;
            head.appendChild(style);
        }else if(styleCss.href !=url){
            styleCss.href=url;
        }
    }

    window.importTemplate=async (id,url)=>{
        return new Promise(resolve => {
            let templateId= document.querySelector("#"+id);
            if(templateId==null){
                var bodyElement = document.getElementsByTagName('body').item(0);
                var templateEl  = document.createElement("template");
                templateEl.id=id;
                templateEl.url=url;
                M.loadHtml(url).then(d=>{
                    templateEl.innerHTML = d;
                    bodyElement.appendChild(templateEl);
                    resolve(true);
                })
            }else if(templateId.url !=url){
                templateId.url=url;
                M.loadHtml(url).then(d=>{
                    templateEl.innerHTML = d;
                    resolve(true);
                })
            }
        })
    }


    window.Page=async (pageObj)=>{
        let pageName= pageObj.name;
        let htmlUrl=`./views/${pageName}/${pageName}.html`;
        if(!pageObj.template){
            await M.loadHtml(htmlUrl)
        }
        return {
            ...pageObj,
            template: pageObj.template || M.html(htmlUrl),
        }
    }

    M.isPc=(()=>{
        var sUserAgent = navigator.userAgent.toLowerCase();
        if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(sUserAgent)) {
           return false;
        }
        return true;
    })();

    M.isWeiXin=(()=>{
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true;
        } else {
            return false;
        }
    })();


    var App = {
        _get: {},
        get (methodName, callback) {
            M.IO.reg(methodName.replace("/", ""));
            methodName = M.formatUrl(methodName);
            App._get[methodName] = callback;
        },
        _begin: function () {
        },
        _end: function () {
        },

        begin(callback) {
            App._begin = callback;
        },
        end(callback) {
            App._end = callback;
        },
        use(url,callback){
            if(typeof url === 'function' || (typeof url === 'object' && !Array.isArray(url))  ){
                let plugin=url;
                let args=callback;
                if(plugin.installed){
                    return App;
                }
                if (typeof plugin === 'function') {
                    plugin(App, args);
                } else {
                    plugin.install(App, args);
                }
                plugin.installed = true;
                M._globle_plugin.add(plugin);
            }else {
                if (Array.isArray(url)) {
                    url.forEach(u=>{
                        let regExp=new RegExp(u)
                        App._use[u] = {url,regExp,callback};
                    })
                } else {
                    let regExp=new RegExp(url)
                    App._use[url] = {url,regExp,callback};
                }
            }
            return App;
        },
        async installPlugin(pluginUrl,constructorParams,pluginParams){
            if(M._globle_plugin_url_cacheMap[pluginUrl]){
                return
            }
            M._globle_plugin_url_cacheMap[pluginUrl]=pluginUrl;
            return  new Promise(resolve => {
                import(pluginUrl).then(async modul=>{
                    const Plugin= modul.default;
                    const plugin= new Plugin(constructorParams);
                    App.use(plugin,pluginParams)
                    resolve(plugin);
                })
            })
        },
        async doget(methodName,params,callback) {
            const req = {};
            const res = {};
            req.params = params||{};
            req.url = methodName;
            res.send = function (d) {
                res.alreadySend = true;
                callback(d);
                App._end(req, d);
            }.bind(this);
            await App._begin(req, res);
            if (!res.alreadySend) await App._get[methodName](req, res);
        }
    };
    //服务方法注册
    M.IO = {};
    M.IO.reg = function (methedName) {
        M.IO[methedName] = (param) => {
            return new Promise(
                function (reslove) {
                    App.doget("/" + methedName,param,(d)=>{
                        reslove(d);
                    })
                }
            )
        }
    };

    /**
     * 去掉参数加让斜杠
     */
    M.formatUrl = function (url) {
        if (url.indexOf("?") > 0) {
            url = url.substr(0, url.indexOf("?"));
        } else {
            url = url;
        }
        if (!url.startsWith('/')) {
            url = '/' + url;
        }
        return url;
    };


    M.get = function (url, param) {
        let u;
        App.doget(url,param,(d)=>{
            u = d;
        });
        return u;
    };

    M.init = function () {
        //格式化日期
        Date.prototype.format = function (fmt) {
            var o = {
                "M+": this.getMonth() + 1,                 //月份
                "d+": this.getDate(),                    //日
                "h+": this.getHours(),                   //小时
                "m+": this.getMinutes(),                 //分
                "s+": this.getSeconds(),                 //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds()             //毫秒
            };
            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;
        }
    };

    M.removeUserInfo=function (){
        localStorage.removeItem("lj_member_info");
    }
    M.getUserInfo=function (){
        if(localStorage.getItem('lj_member_info')==null || localStorage.getItem('lj_member_info')=='{}'){
            return null
        }
        return JSON.parse(localStorage.getItem('lj_member_info'))
    }

    M.setUserInfo=async function (userInfoObj){
         if(userInfoObj.unionid){
             if(userInfoObj.unionid.includes("#")){
                 userInfoObj.unionid.replaceAll("#","")
             }
             if(userInfoObj.unionid.includes("/")){
                 userInfoObj.unionid.replaceAll("/","")
             }
         }
         //alert(JSON.stringify(userInfoObj))
         localStorage.setItem("lj_member_info", JSON.stringify(userInfoObj));
         let r=  M.getUserInfo();
         return r;
    }

    M.removeUserData=function (){
        localStorage.removeItem("lj_member_data");
    }
    M.getUserData=function (){
        if(localStorage.getItem('lj_member_data')==null){
            return null
        }
        return JSON.parse(localStorage.getItem('lj_member_data'))
    }

    M.setUserData=async function (userInfoObj){
        localStorage.setItem("lj_member_data", JSON.stringify(userInfoObj));
        let r=  M.getUserInfo();
        return r;
    }


    M.getParameter = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.href.substr(window.location.href.indexOf('?')).substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    M.urlStringify = function (obj) {
        if (obj !== null && typeof obj === 'object') {
            var keys = Object.keys(obj);
            var len = keys.length;
            var flast = len - 1;
            var fields = '';
            for (var i = 0; i < len; ++i) {
                var k = keys[i];
                var v = obj[k];
                var ks = k + "=";
                fields += ks + v;
                if (i < flast) {
                    fields += "&";
                }
            }
            return fields;
        }
        return '';
    };

    const translateApi=(api)=>{
        let url=M.config.baseUrl(api) ;
        if(!api.startsWith("http")){
            api=url
        }
        return api;
    }

    const post  = async (api, params = {},headers) => {
        api=translateApi(api)
       // alert(api)
        return new Promise((reslove, reject) => {
            fetch(api, {
                method: 'POST',
                mode: 'cors',
                headers: headers||{
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            }).then(function (response) {
                return response.json();
            }).then((res) => {
                reslove(res)
            }).catch((err) => {
                reject(err)
            });
        })
    }
    const get = async (api, params = {},headers) => {
        api=translateApi(api)
        let getData = "";
        if (params) {
            getData = window.M.urlStringify(params);
            if (api.indexOf("?") > 0) {
                getData = "&" + getData;
            } else {
                getData = "?" + getData;
            }
        }
        api = api + getData;
        return new Promise((reslove, reject) => {
            fetch(api, {
                method: 'GET',
                mode: 'cors',
                headers: headers||{
                    'Content-Type': 'application/json'
                }
            }).then(function (response) {
                return response.json();
            }).then((res) => {
                reslove(res)
            }).catch((err) => {
                reject(err)
            });
        })
    };
    const jsonp=async (url, callbackFunction)=>{
        return new Promise(resolve => {
            let callbackStr = M.urlParse(url).callback;
            window[callbackStr]=(...params)=>{
                if(callbackFunction) {
                    callbackFunction(params);
                }
                document.body.removeChild(document.getElementById("ming_mock_jsonp_id"))
                resolve(params);
            }
            var scriptElement = document.createElement('script');
            scriptElement.src = url;
            scriptElement.id="ming_mock_jsonp_id"
            document.body.appendChild(scriptElement);
        })
    };

    const options = {
        moduleCache: {
            vue: Vue
        },
        async getFile(url) {
            const res = await fetch(url);
            if ( !res.ok )
                throw Object.assign(new Error(url+' '+res.statusText), { res });
            return await res.text();
        },
        addStyle(textContent) {
            const style = Object.assign(document.createElement('style'), { textContent });
            const ref = document.head.getElementsByTagName('style')[0] || null;
            document.head.insertBefore(style, ref);
        },
    }

    const { loadModule } = window['vue3-sfc-loader'];

    M.loadVueModule=function (filePath){
        return  loadModule(filePath, options);
    }

    window.M = M;
    window.MIO = M.IO;
//将ajax请求挂到全局对象M上
    M.init();
    window.M.request={}
    window.M.request.get=get;
    window.M.request.post=post;
    window.M.request.jsonp=jsonp;
    window.app = App;
})(window);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值