uniapp请求封装

作者: 在下高姓 | 来源:发表于2020-08-22 09:35 被阅读0次
    Vue.prototype.sendRequest = function(url,param,method,callBack){
        var _self = this, 
            // method = param.method,
            header = {},
            data = param|| {}, 
            token =uni.getStorageSync("access_token");
        //拼接完整请求地址
        var requestUrl = this.websiteUrl + url;
    
        var timestamp = Date.parse(new Date());//时间戳
        data["timestamp"] = timestamp;
        // #ifdef MP-WEIXIN
        data["device"] = "wxapp";
        data["ver"] = "1.1.30";
        // #endif
        // #ifdef APP-PLUS || H5
        data["device"] = "iosapp";
        data["ver"] = "1.0.0";
        data["access_token"]=token;
        // #endif
        //请求方式:GET或POST(POST需配置header: {'content-type' : "application/x-www-form-urlencoded"},)
        if(method){
            method = method.toUpperCase();//小写改为大写
            if(method=="POST"){
                header = {'content-type' : "application/x-www-form-urlencoded"};
            }else{
                header = {'content-type' : "application/json"};
            }
        }else{
            method = "GET";
            header = {'content-type' : "application/json"};
        }
        //网络请求
        uni.request({
            url: requestUrl,
            data: data,
            method: method, 
            header: header,
            success: res => {
                if(res.data.code==200){
                    callBack(res.data.data); 
                }else{
                    _self.login(false);
                }
            },
            fail: (e) => {
                //console.log("网络请求fail:" + JSON.stringify(e));
                uni.showModal({
                    content:"" + e.errMsg
                });
                // typeof param.fail == "function" && param.fail(e.data);
            },
            complete: () => {
                //console.log("网络请求complete");
                // uni.hideLoading();
                // typeof param.complete == "function" && param.complete();
                //return;
            }
        });
    

    相关文章

      网友评论

        本文标题:uniapp请求封装

        本文链接:https://www.haomeiwen.com/subject/elfhdktx.html