每篇文章仅做为自己的备忘笔记,若有描述不清或不对的地方还请指明,感谢^_^

小程序 网络请求

另一篇比较完善  uni装request请求  

 

/**
 * requestPromise用于将wx.request改写成Promise方式
 * @param:{string} myUrl 接口地址
 * @return: Promise实例对象
 */


/**=====================================================================核心:接口文件====*/
var apiUrlList={
    service:"https://***.com",//服务器
    "账单明细":{
        url:"/api/check/load.html",
        method:"POST"//提交方式
    },
};
/**=====================================================================核心:网络请求====*/
 function myAjax(api, data) {
    wx.showLoading({
        title: '加载中',
        mask:true
    });
    let that = this;
    var apiUrl = apiUrlList.service + apiUrlList[api].url;
    var method = apiUrlList[api].method;
    return new Promise(function (resolve, reject) {
        // console.clear();

        wx.request({//发起网络请求
            url: apiUrl,
            method:method,
            data: data,
            header: {
                'content-type': 'application/json' // 默认值
            },
            success(res) {
                if(res.data.code==0){
                    console.warn("%c 使用接口:", 'color:orange;font-size:15px', api,"\n 提交地址:",  apiUrl,"\n 提交data:",  data,"\n 请求返回", res.data,"\n 提交方式:", method);
                }else{
                    console.error("%c 使用接口:", 'color:orange;font-size:15px', api,"\n 提交地址:",  apiUrl,"\n 提交data:",  data,"\n 请求返回", res.data,"\n 提交方式:", method);
                }
                resolve(res.data);//成功返回,resolve是Promise的回调方式
            },
            fail(res) {
                console.warn("%c 使用接口:", 'color:red;font-size:15px', api,"\n 提交地址:",  apiUrl,"\n 提交data:",  data,"\n 请求返回", res,"\n 提交方式:", method);

                wx.showToast({
                    title: '网络请求失败',
                    icon: 'none',
                    duration: 5000,
                    mask:true
                });
                reject(res);//失败返回,resolve是Promise的回调方式
            },complete(){
                wx.hideLoading()
            }
        });

    })
}
/**=====================================================================核心:开放入口函数====*/
module.exports = {
    myAjax: myAjax
};

/**=====================================================================核心:如何使用====*/
/**
 * var util = require('/app/ajax.js');//1、引入当前的js文件
 *
 * util.myAjax("小程序登录", data).then((res) => {//2、调用myAjax
 * console.log("3-",res);//3、网络请求成功
 * }).catch((res) => {
 * console.log("3-",res);//3、网络请求失败
 * });
 * */
封装网络请求

使用方式:

 

 getWeb() {//获取网络数据
        let that = this;
        that.myAjax("授权手机号", data).then((res) => {
            console.log(res)
        }).catch((res) => {
            console.log(res)
        });
    },

 

 

posted @ 2020-05-22 17:36  菜汤不甜  阅读(187)  评论(0编辑  收藏  举报